Path: blob/master/modules/navigation_2d/2d/nav_map_builder_2d.cpp
10278 views
/**************************************************************************/1/* nav_map_builder_2d.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "nav_map_builder_2d.h"3132#include "../nav_link_2d.h"33#include "../nav_map_2d.h"34#include "../nav_region_2d.h"35#include "../triangle2.h"36#include "nav_map_iteration_2d.h"37#include "nav_region_iteration_2d.h"3839using namespace Nav2D;4041PointKey NavMapBuilder2D::get_point_key(const Vector2 &p_pos, const Vector2 &p_cell_size) {42const int x = static_cast<int>(Math::floor(p_pos.x / p_cell_size.x));43const int y = static_cast<int>(Math::floor(p_pos.y / p_cell_size.y));4445PointKey p;46p.key = 0;47p.x = x;48p.y = y;49return p;50}5152void NavMapBuilder2D::build_navmap_iteration(NavMapIterationBuild2D &r_build) {53PerformanceData &performance_data = r_build.performance_data;5455performance_data.pm_polygon_count = 0;56performance_data.pm_edge_count = 0;57performance_data.pm_edge_merge_count = 0;58performance_data.pm_edge_connection_count = 0;59performance_data.pm_edge_free_count = 0;6061_build_step_gather_region_polygons(r_build);6263_build_step_find_edge_connection_pairs(r_build);6465_build_step_merge_edge_connection_pairs(r_build);6667_build_step_edge_connection_margin_connections(r_build);6869_build_step_navlink_connections(r_build);7071_build_update_map_iteration(r_build);72}7374void NavMapBuilder2D::_build_step_gather_region_polygons(NavMapIterationBuild2D &r_build) {75PerformanceData &performance_data = r_build.performance_data;76NavMapIteration2D *map_iteration = r_build.map_iteration;7778const LocalVector<Ref<NavRegionIteration2D>> ®ions = map_iteration->region_iterations;79HashMap<const NavBaseIteration2D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;8081map_iteration->navbases_polygons_external_connections.clear();8283// Remove regions connections.84region_external_connections.clear();8586// Copy all region polygons in the map.87int polygon_count = 0;88for (const Ref<NavRegionIteration2D> ®ion : regions) {89const uint32_t polygons_size = region->navmesh_polygons.size();90polygon_count += polygons_size;9192region_external_connections[region.ptr()] = LocalVector<Connection>();93map_iteration->navbases_polygons_external_connections[region.ptr()] = LocalVector<LocalVector<Connection>>();94map_iteration->navbases_polygons_external_connections[region.ptr()].resize(polygons_size);95}9697performance_data.pm_polygon_count = polygon_count;98r_build.polygon_count = polygon_count;99}100101void NavMapBuilder2D::_build_step_find_edge_connection_pairs(NavMapIterationBuild2D &r_build) {102PerformanceData &performance_data = r_build.performance_data;103NavMapIteration2D *map_iteration = r_build.map_iteration;104int polygon_count = r_build.polygon_count;105106HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;107108// Group all edges per key.109connection_pairs_map.clear();110connection_pairs_map.reserve(polygon_count);111int free_edges_count = 0; // How many ConnectionPairs have only one Connection.112113for (const Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {114for (const ConnectableEdge &connectable_edge : region->get_external_edges()) {115const EdgeKey &ek = connectable_edge.ek;116117HashMap<EdgeKey, EdgeConnectionPair, EdgeKey>::Iterator pair_it = connection_pairs_map.find(ek);118if (!pair_it) {119pair_it = connection_pairs_map.insert(ek, EdgeConnectionPair());120performance_data.pm_edge_count += 1;121++free_edges_count;122}123EdgeConnectionPair &pair = pair_it->value;124if (pair.size < 2) {125// Add the polygon/edge tuple to this key.126Connection new_connection;127new_connection.polygon = ®ion->navmesh_polygons[connectable_edge.polygon_index];128new_connection.edge = connectable_edge.edge;129new_connection.pathway_start = connectable_edge.pathway_start;130new_connection.pathway_end = connectable_edge.pathway_end;131132pair.connections[pair.size] = new_connection;133++pair.size;134if (pair.size == 2) {135--free_edges_count;136}137138} else {139// The edge is already connected with another edge, skip.140ERR_PRINT_ONCE("Navigation map synchronization error. Attempted to merge a navigation mesh polygon edge with another already-merged edge. This is usually caused by crossing edges, overlapping polygons, or a mismatch of the NavigationMesh / NavigationPolygon baked 'cell_size' and navigation map 'cell_size'. If you're certain none of above is the case, change 'navigation/2d/merge_rasterizer_cell_scale' to 0.001.");141}142}143}144145r_build.free_edge_count = free_edges_count;146}147148void NavMapBuilder2D::_build_step_merge_edge_connection_pairs(NavMapIterationBuild2D &r_build) {149PerformanceData &performance_data = r_build.performance_data;150151HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;152LocalVector<Connection> &free_edges = r_build.iter_free_edges;153int free_edges_count = r_build.free_edge_count;154bool use_edge_connections = r_build.use_edge_connections;155156free_edges.clear();157free_edges.reserve(free_edges_count);158159NavMapIteration2D *map_iteration = r_build.map_iteration;160161HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;162163for (const KeyValue<EdgeKey, EdgeConnectionPair> &pair_it : connection_pairs_map) {164const EdgeConnectionPair &pair = pair_it.value;165if (pair.size == 2) {166// Connect edge that are shared in different polygons.167const Connection &c1 = pair.connections[0];168const Connection &c2 = pair.connections[1];169170navbases_polygons_external_connections[c1.polygon->owner][c1.polygon->id].push_back(c2);171navbases_polygons_external_connections[c2.polygon->owner][c2.polygon->id].push_back(c1);172performance_data.pm_edge_connection_count += 1;173174} else {175CRASH_COND_MSG(pair.size != 1, vformat("Number of connection != 1. Found: %d", pair.size));176if (use_edge_connections && pair.connections[0].polygon->owner->get_use_edge_connections()) {177free_edges.push_back(pair.connections[0]);178}179}180}181}182183void NavMapBuilder2D::_build_step_edge_connection_margin_connections(NavMapIterationBuild2D &r_build) {184PerformanceData &performance_data = r_build.performance_data;185NavMapIteration2D *map_iteration = r_build.map_iteration;186187real_t edge_connection_margin = r_build.edge_connection_margin;188189LocalVector<Connection> &free_edges = r_build.iter_free_edges;190HashMap<const NavBaseIteration2D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;191192HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;193194// Find the compatible near edges.195//196// Note:197// Considering that the edges must be compatible (for obvious reasons)198// to be connected, create new polygons to remove that small gap is199// not really useful and would result in wasteful computation during200// connection, integration and path finding.201performance_data.pm_edge_free_count = free_edges.size();202203const real_t edge_connection_margin_squared = edge_connection_margin * edge_connection_margin;204205for (uint32_t i = 0; i < free_edges.size(); i++) {206const Connection &free_edge = free_edges[i];207const Vector2 &edge_p1 = free_edge.pathway_start;208const Vector2 &edge_p2 = free_edge.pathway_end;209210for (uint32_t j = 0; j < free_edges.size(); j++) {211const Connection &other_edge = free_edges[j];212if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {213continue;214}215216const Vector2 &other_edge_p1 = other_edge.pathway_start;217const Vector2 &other_edge_p2 = other_edge.pathway_end;218219// Compute the projection of the opposite edge on the current one220Vector2 edge_vector = edge_p2 - edge_p1;221real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());222real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());223if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {224continue;225}226227// Check if the two edges are close to each other enough and compute a pathway between the two regions.228Vector2 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;229Vector2 other1;230if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {231other1 = other_edge_p1;232} else {233other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));234}235if (other1.distance_squared_to(self1) > edge_connection_margin_squared) {236continue;237}238239Vector2 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;240Vector2 other2;241if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {242other2 = other_edge_p2;243} else {244other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));245}246if (other2.distance_squared_to(self2) > edge_connection_margin_squared) {247continue;248}249250// The edges can now be connected.251Connection new_connection = other_edge;252new_connection.pathway_start = (self1 + other1) / 2.0;253new_connection.pathway_end = (self2 + other2) / 2.0;254//free_edge.polygon->connections.push_back(new_connection);255256// Add the connection to the region_connection map.257region_external_connections[free_edge.polygon->owner].push_back(new_connection);258navbases_polygons_external_connections[free_edge.polygon->owner][free_edge.polygon->id].push_back(new_connection);259performance_data.pm_edge_connection_count += 1;260}261}262}263264void NavMapBuilder2D::_build_step_navlink_connections(NavMapIterationBuild2D &r_build) {265NavMapIteration2D *map_iteration = r_build.map_iteration;266267real_t link_connection_radius = r_build.link_connection_radius;268269const LocalVector<Ref<NavLinkIteration2D>> &links = map_iteration->link_iterations;270271int polygon_count = r_build.polygon_count;272273real_t link_connection_radius_sqr = link_connection_radius * link_connection_radius;274275HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;276LocalVector<Nav2D::Polygon> &navlink_polygons = map_iteration->navlink_polygons;277navlink_polygons.clear();278navlink_polygons.resize(links.size());279uint32_t navlink_index = 0;280281// Search for polygons within range of a nav link.282for (const Ref<NavLinkIteration2D> &link : links) {283polygon_count++;284Polygon &new_polygon = navlink_polygons[navlink_index++];285286new_polygon.id = 0;287new_polygon.owner = link.ptr();288289const Vector2 link_start_pos = link->get_start_position();290const Vector2 link_end_pos = link->get_end_position();291292Polygon *closest_start_polygon = nullptr;293real_t closest_start_sqr_dist = link_connection_radius_sqr;294Vector2 closest_start_point;295296Polygon *closest_end_polygon = nullptr;297real_t closest_end_sqr_dist = link_connection_radius_sqr;298Vector2 closest_end_point;299300for (const Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {301Rect2 region_bounds = region->get_bounds().grow(link_connection_radius);302if (!region_bounds.has_point(link_start_pos) && !region_bounds.has_point(link_end_pos)) {303continue;304}305306for (Polygon &polyon : region->navmesh_polygons) {307for (uint32_t point_id = 2; point_id < polyon.vertices.size(); point_id += 1) {308const Triangle2 triangle(polyon.vertices[0], polyon.vertices[point_id - 1], polyon.vertices[point_id]);309310{311const Vector2 start_point = triangle.get_closest_point_to(link_start_pos);312const real_t sqr_dist = start_point.distance_squared_to(link_start_pos);313314// Pick the polygon that is within our radius and is closer than anything we've seen yet.315if (sqr_dist < closest_start_sqr_dist) {316closest_start_sqr_dist = sqr_dist;317closest_start_point = start_point;318closest_start_polygon = &polyon;319}320}321322{323const Vector2 end_point = triangle.get_closest_point_to(link_end_pos);324const real_t sqr_dist = end_point.distance_squared_to(link_end_pos);325326// Pick the polygon that is within our radius and is closer than anything we've seen yet.327if (sqr_dist < closest_end_sqr_dist) {328closest_end_sqr_dist = sqr_dist;329closest_end_point = end_point;330closest_end_polygon = &polyon;331}332}333}334}335}336337// If we have both a start and end point, then create a synthetic polygon to route through.338if (closest_start_polygon && closest_end_polygon) {339new_polygon.vertices.resize(4);340341// Build a set of vertices that create a thin polygon going from the start to the end point.342new_polygon.vertices[0] = closest_start_point;343new_polygon.vertices[1] = closest_start_point;344new_polygon.vertices[2] = closest_end_point;345new_polygon.vertices[3] = closest_end_point;346347// Setup connections to go forward in the link.348{349Connection entry_connection;350entry_connection.polygon = &new_polygon;351entry_connection.edge = -1;352entry_connection.pathway_start = new_polygon.vertices[0];353entry_connection.pathway_end = new_polygon.vertices[1];354navbases_polygons_external_connections[closest_start_polygon->owner][closest_start_polygon->id].push_back(entry_connection);355356Connection exit_connection;357exit_connection.polygon = closest_end_polygon;358exit_connection.edge = -1;359exit_connection.pathway_start = new_polygon.vertices[2];360exit_connection.pathway_end = new_polygon.vertices[3];361navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());362navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);363}364365// If the link is bi-directional, create connections from the end to the start.366if (link->is_bidirectional()) {367Connection entry_connection;368entry_connection.polygon = &new_polygon;369entry_connection.edge = -1;370entry_connection.pathway_start = new_polygon.vertices[2];371entry_connection.pathway_end = new_polygon.vertices[3];372navbases_polygons_external_connections[closest_end_polygon->owner][closest_end_polygon->id].push_back(entry_connection);373374Connection exit_connection;375exit_connection.polygon = closest_start_polygon;376exit_connection.edge = -1;377exit_connection.pathway_start = new_polygon.vertices[0];378exit_connection.pathway_end = new_polygon.vertices[1];379navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());380navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);381}382}383}384385r_build.polygon_count = polygon_count;386}387388void NavMapBuilder2D::_build_update_map_iteration(NavMapIterationBuild2D &r_build) {389NavMapIteration2D *map_iteration = r_build.map_iteration;390391map_iteration->navmesh_polygon_count = r_build.polygon_count;392393uint32_t navmesh_polygon_count = r_build.polygon_count;394uint32_t total_polygon_count = navmesh_polygon_count;395396map_iteration->path_query_slots_mutex.lock();397for (NavMeshQueries2D::PathQuerySlot &p_path_query_slot : map_iteration->path_query_slots) {398p_path_query_slot.traversable_polys.clear();399p_path_query_slot.traversable_polys.reserve(navmesh_polygon_count * 0.25);400p_path_query_slot.path_corridor.clear();401402p_path_query_slot.path_corridor.resize(total_polygon_count);403404p_path_query_slot.poly_to_id.clear();405p_path_query_slot.poly_to_id.reserve(total_polygon_count);406407int polygon_id = 0;408for (Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {409for (const Polygon &polygon : region->navmesh_polygons) {410p_path_query_slot.poly_to_id[&polygon] = polygon_id;411polygon_id++;412}413}414415for (const Polygon &polygon : map_iteration->navlink_polygons) {416p_path_query_slot.poly_to_id[&polygon] = polygon_id;417polygon_id++;418}419420DEV_ASSERT(p_path_query_slot.path_corridor.size() == p_path_query_slot.poly_to_id.size());421}422423map_iteration->path_query_slots_mutex.unlock();424}425426427