Path: blob/master/modules/navigation_2d/2d/nav_mesh_queries_2d.cpp
11353 views
/**************************************************************************/1/* nav_mesh_queries_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_mesh_queries_2d.h"3132#include "../nav_base_2d.h"33#include "../nav_map_2d.h"34#include "../triangle2.h"35#include "nav_region_iteration_2d.h"3637#include "core/math/geometry_2d.h"3839using namespace Nav2D;4041#define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (-((m_c) - (m_a)).cross((m_b) - (m_a)))4243bool NavMeshQueries2D::emit_callback(const Callable &p_callback) {44ERR_FAIL_COND_V(!p_callback.is_valid(), false);4546Callable::CallError ce;47Variant result;48p_callback.callp(nullptr, 0, result, ce);4950return ce.error == Callable::CallError::CALL_OK;51}5253Vector2 NavMeshQueries2D::polygons_get_random_point(const LocalVector<Polygon> &p_polygons, uint32_t p_navigation_layers, bool p_uniformly) {54const LocalVector<Polygon> ®ion_polygons = p_polygons;5556if (region_polygons.is_empty()) {57return Vector2();58}5960if (p_uniformly) {61real_t accumulated_area = 0;62RBMap<real_t, uint32_t> region_area_map;6364for (uint32_t rp_index = 0; rp_index < region_polygons.size(); rp_index++) {65const Polygon ®ion_polygon = region_polygons[rp_index];66real_t polyon_area = region_polygon.surface_area;6768if (polyon_area == 0.0) {69continue;70}71region_area_map[accumulated_area] = rp_index;72accumulated_area += polyon_area;73}74if (region_area_map.is_empty() || accumulated_area == 0) {75// All polygons have no real surface / no area.76return Vector2();77}7879real_t region_area_map_pos = Math::random(real_t(0), accumulated_area);8081RBMap<real_t, uint32_t>::Iterator region_E = region_area_map.find_closest(region_area_map_pos);82ERR_FAIL_COND_V(!region_E, Vector2());83uint32_t rrp_polygon_index = region_E->value;84ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector2());8586const Polygon &rr_polygon = region_polygons[rrp_polygon_index];8788real_t accumulated_polygon_area = 0;89RBMap<real_t, uint32_t> polygon_area_map;9091for (uint32_t rpp_index = 2; rpp_index < rr_polygon.vertices.size(); rpp_index++) {92real_t triangle_area = Triangle2(rr_polygon.vertices[0], rr_polygon.vertices[rpp_index - 1], rr_polygon.vertices[rpp_index]).get_area();9394if (triangle_area == 0.0) {95continue;96}97polygon_area_map[accumulated_polygon_area] = rpp_index;98accumulated_polygon_area += triangle_area;99}100if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {101// All faces have no real surface / no area.102return Vector2();103}104105real_t polygon_area_map_pos = Math::random(real_t(0), accumulated_polygon_area);106107RBMap<real_t, uint32_t>::Iterator polygon_E = polygon_area_map.find_closest(polygon_area_map_pos);108ERR_FAIL_COND_V(!polygon_E, Vector2());109uint32_t rrp_face_index = polygon_E->value;110ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.vertices.size(), Vector2());111112const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);113114Vector2 triangle_random_position = triangle.get_random_point_inside();115return triangle_random_position;116117} else {118uint32_t rrp_polygon_index = Math::random(int(0), region_polygons.size() - 1);119120const Polygon &rr_polygon = region_polygons[rrp_polygon_index];121122uint32_t rrp_face_index = Math::random(int(2), rr_polygon.vertices.size() - 1);123124const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);125126Vector2 triangle_random_position = triangle.get_random_point_inside();127return triangle_random_position;128}129}130131void NavMeshQueries2D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask2D &p_query_task, const Vector2 &p_point, const Polygon *p_point_polygon) {132if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {133p_query_task.path_meta_point_types.push_back(p_point_polygon->owner->get_type());134}135136if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {137p_query_task.path_meta_point_rids.push_back(p_point_polygon->owner->get_self());138}139140if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {141p_query_task.path_meta_point_owners.push_back(p_point_polygon->owner->get_owner_id());142}143144p_query_task.path_points.push_back(p_point);145}146147void NavMeshQueries2D::map_query_path(NavMap2D *p_map, const Ref<NavigationPathQueryParameters2D> &p_query_parameters, Ref<NavigationPathQueryResult2D> p_query_result, const Callable &p_callback) {148ERR_FAIL_NULL(p_map);149ERR_FAIL_COND(p_query_parameters.is_null());150ERR_FAIL_COND(p_query_result.is_null());151152using namespace NavigationDefaults2D;153154NavMeshQueries2D::NavMeshPathQueryTask2D query_task;155query_task.start_position = p_query_parameters->get_start_position();156query_task.target_position = p_query_parameters->get_target_position();157query_task.navigation_layers = p_query_parameters->get_navigation_layers();158query_task.callback = p_callback;159160const TypedArray<RID> &_excluded_regions = p_query_parameters->get_excluded_regions();161const TypedArray<RID> &_included_regions = p_query_parameters->get_included_regions();162163uint32_t _excluded_region_count = _excluded_regions.size();164uint32_t _included_region_count = _included_regions.size();165166query_task.exclude_regions = _excluded_region_count > 0;167query_task.include_regions = _included_region_count > 0;168169if (query_task.exclude_regions) {170query_task.excluded_regions.resize(_excluded_region_count);171for (uint32_t i = 0; i < _excluded_region_count; i++) {172query_task.excluded_regions[i] = _excluded_regions[i];173}174}175176if (query_task.include_regions) {177query_task.included_regions.resize(_included_region_count);178for (uint32_t i = 0; i < _included_region_count; i++) {179query_task.included_regions[i] = _included_regions[i];180}181}182183switch (p_query_parameters->get_pathfinding_algorithm()) {184case NavigationPathQueryParameters2D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR: {185query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;186} break;187default: {188WARN_PRINT("No match for used PathfindingAlgorithm - fallback to default");189query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;190} break;191}192193switch (p_query_parameters->get_path_postprocessing()) {194case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {195query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;196} break;197case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {198query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;199} break;200case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_NONE: {201query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_NONE;202} break;203default: {204WARN_PRINT("No match for used PathPostProcessing - fallback to default");205query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;206} break;207}208209query_task.metadata_flags = (int64_t)p_query_parameters->get_metadata_flags();210query_task.simplify_path = p_query_parameters->get_simplify_path();211query_task.simplify_epsilon = p_query_parameters->get_simplify_epsilon();212query_task.path_return_max_length = p_query_parameters->get_path_return_max_length();213query_task.path_return_max_radius = p_query_parameters->get_path_return_max_radius();214query_task.path_search_max_polygons = p_query_parameters->get_path_search_max_polygons();215query_task.path_search_max_distance = p_query_parameters->get_path_search_max_distance();216query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_STARTED;217218p_map->query_path(query_task);219220p_query_result->set_data(221query_task.path_points,222query_task.path_meta_point_types,223query_task.path_meta_point_rids,224query_task.path_meta_point_owners);225p_query_result->set_path_length(query_task.path_length);226227if (query_task.callback.is_valid()) {228if (emit_callback(query_task.callback)) {229query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_DISPATCHED;230} else {231query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_FAILED;232}233}234}235236void NavMeshQueries2D::_query_task_find_start_end_positions(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {237real_t begin_d = FLT_MAX;238real_t end_d = FLT_MAX;239240const LocalVector<Ref<NavRegionIteration2D>> ®ions = p_map_iteration.region_iterations;241242for (const Ref<NavRegionIteration2D> ®ion : regions) {243if (!_query_task_is_connection_owner_usable(p_query_task, region.ptr())) {244continue;245}246247// Find the initial poly and the end poly on this map.248for (const Polygon &p : region->get_navmesh_polygons()) {249// Only consider the polygon if it in a region with compatible layers.250if ((p_query_task.navigation_layers & p.owner->get_navigation_layers()) == 0) {251continue;252}253254// For each triangle check the distance between the origin/destination.255for (uint32_t point_id = 2; point_id < p.vertices.size(); point_id++) {256const Triangle2 triangle(p.vertices[0], p.vertices[point_id - 1], p.vertices[point_id]);257258Vector2 point = triangle.get_closest_point_to(p_query_task.start_position);259real_t distance_to_point = point.distance_to(p_query_task.start_position);260if (distance_to_point < begin_d) {261begin_d = distance_to_point;262p_query_task.begin_polygon = &p;263p_query_task.begin_position = point;264}265266point = triangle.get_closest_point_to(p_query_task.target_position);267distance_to_point = point.distance_to(p_query_task.target_position);268if (distance_to_point < end_d) {269end_d = distance_to_point;270p_query_task.end_polygon = &p;271p_query_task.end_position = point;272}273}274}275}276}277278void NavMeshQueries2D::_query_task_search_polygon_connections(NavMeshPathQueryTask2D &p_query_task, const Connection &p_connection, uint32_t p_least_cost_id, const NavigationPoly &p_least_cost_poly, real_t p_poly_enter_cost, const Vector2 &p_end_point) {279const NavBaseIteration2D *connection_owner = p_connection.polygon->owner;280ERR_FAIL_NULL(connection_owner);281const bool owner_is_usable = _query_task_is_connection_owner_usable(p_query_task, connection_owner);282if (!owner_is_usable) {283return;284}285286Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>287&traversable_polys = p_query_task.path_query_slot->traversable_polys;288LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;289290real_t poly_travel_cost = p_least_cost_poly.poly->owner->get_travel_cost();291292Vector2 new_entry = Geometry2D::get_closest_point_to_segment(p_least_cost_poly.entry, p_connection.pathway_start, p_connection.pathway_end);293real_t new_traveled_distance = p_least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost + p_poly_enter_cost + p_least_cost_poly.traveled_distance;294295// Check if the neighbor polygon has already been processed.296NavigationPoly &neighbor_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[p_connection.polygon]];297if (new_traveled_distance < neighbor_poly.traveled_distance) {298// Add the polygon to the heap of polygons to traverse next.299neighbor_poly.back_navigation_poly_id = p_least_cost_id;300neighbor_poly.back_navigation_edge = p_connection.edge;301neighbor_poly.back_navigation_edge_pathway_start = p_connection.pathway_start;302neighbor_poly.back_navigation_edge_pathway_end = p_connection.pathway_end;303neighbor_poly.traveled_distance = new_traveled_distance;304neighbor_poly.distance_to_destination =305new_entry.distance_to(p_end_point) *306connection_owner->get_travel_cost();307neighbor_poly.entry = new_entry;308309if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {310traversable_polys.shift(neighbor_poly.traversable_poly_index);311} else {312neighbor_poly.poly = p_connection.polygon;313traversable_polys.push(&neighbor_poly);314}315}316}317318void NavMeshQueries2D::_query_task_build_path_corridor(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {319const Vector2 p_target_position = p_query_task.target_position;320const Polygon *begin_poly = p_query_task.begin_polygon;321const Polygon *end_poly = p_query_task.end_polygon;322Vector2 begin_point = p_query_task.begin_position;323Vector2 end_point = p_query_task.end_position;324325// Heap of polygons to travel next.326Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>327&traversable_polys = p_query_task.path_query_slot->traversable_polys;328traversable_polys.clear();329330LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;331for (NavigationPoly &polygon : navigation_polys) {332polygon.reset();333}334335// Initialize the matching navigation polygon.336NavigationPoly &begin_navigation_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[begin_poly]];337begin_navigation_poly.poly = begin_poly;338begin_navigation_poly.entry = begin_point;339begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;340begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;341begin_navigation_poly.traveled_distance = 0.f;342343// This is an implementation of the A* algorithm.344uint32_t least_cost_id = p_query_task.path_query_slot->poly_to_id[begin_poly];345bool found_route = false;346347const Polygon *reachable_end = nullptr;348real_t distance_to_reachable_end = FLT_MAX;349bool is_reachable = true;350real_t poly_enter_cost = 0.0;351352const HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = p_map_iteration.navbases_polygons_external_connections;353354// True if we reached the max polygon search count or distance from the begin position.355bool path_search_max_reached = false;356357const float path_search_max_distance_sqr = p_query_task.path_search_max_distance * p_query_task.path_search_max_distance;358bool has_path_search_max_distance = path_search_max_distance_sqr > 0.0;359360int processed_polygon_count = 0;361bool has_path_search_max_polygons = p_query_task.path_search_max_polygons > 0;362363bool has_path_search_max = p_query_task.path_search_max_polygons > 0 || path_search_max_distance_sqr > 0.0;364365while (true) {366const NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];367368const NavBaseIteration2D *least_cost_navbase = least_cost_poly.poly->owner;369370processed_polygon_count += 1;371372const uint32_t navbase_local_polygon_id = least_cost_poly.poly->id;373const LocalVector<LocalVector<Connection>> &navbase_polygons_to_connections = least_cost_poly.poly->owner->get_internal_connections();374375if (navbase_polygons_to_connections.size() > 0) {376const LocalVector<Connection> &polygon_connections = navbase_polygons_to_connections[navbase_local_polygon_id];377378for (const Connection &connection : polygon_connections) {379_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);380}381}382383// Search region external navmesh polygon connections, aka connections to other regions created by outline edge merge or links.384for (const Connection &connection : navbases_polygons_external_connections[least_cost_navbase][navbase_local_polygon_id]) {385_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);386}387388if (has_path_search_max && !path_search_max_reached) {389if (has_path_search_max_polygons && processed_polygon_count >= p_query_task.path_search_max_polygons) {390path_search_max_reached = true;391traversable_polys.clear();392} else if (has_path_search_max_distance && begin_point.distance_squared_to(least_cost_poly.entry) > path_search_max_distance_sqr) {393path_search_max_reached = true;394traversable_polys.clear();395}396}397398poly_enter_cost = 0;399// When the heap of traversable polygons is empty at this point it means the end polygon is400// unreachable.401if (traversable_polys.is_empty()) {402// Thus use the further reachable polygon403ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");404is_reachable = false;405if (reachable_end == nullptr) {406// The path is not found and there is not a way out.407break;408}409410// Set as end point the furthest reachable point.411end_poly = reachable_end;412real_t end_d = FLT_MAX;413414for (uint32_t point_id = 2; point_id < end_poly->vertices.size(); point_id++) {415Triangle2 t(end_poly->vertices[0], end_poly->vertices[point_id - 1], end_poly->vertices[point_id]);416Vector2 spoint = t.get_closest_point_to(p_target_position);417real_t dpoint = spoint.distance_squared_to(p_target_position);418if (dpoint < end_d) {419end_point = spoint;420end_d = dpoint;421}422}423424// Search all faces of start polygon as well.425bool closest_point_on_start_poly = false;426427for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {428Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);429Vector2 spoint = t.get_closest_point_to(p_target_position);430real_t dpoint = spoint.distance_squared_to(p_target_position);431if (dpoint < end_d) {432end_point = spoint;433end_d = dpoint;434closest_point_on_start_poly = true;435}436}437438if (closest_point_on_start_poly) {439// No point to run PostProcessing when start and end convex polygon is the same.440p_query_task.path_clear();441442_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);443_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);444p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;445return;446}447448for (NavigationPoly &nav_poly : navigation_polys) {449nav_poly.poly = nullptr;450nav_poly.traveled_distance = FLT_MAX;451}452uint32_t _bp_id = p_query_task.path_query_slot->poly_to_id[begin_poly];453navigation_polys[_bp_id].poly = begin_poly;454navigation_polys[_bp_id].traveled_distance = 0;455least_cost_id = _bp_id;456reachable_end = nullptr;457} else {458// Pop the polygon with the lowest travel cost from the heap of traversable polygons.459least_cost_id = p_query_task.path_query_slot->poly_to_id[traversable_polys.pop()->poly];460461// Store the farthest reachable end polygon in case our goal is not reachable.462if (is_reachable) {463real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);464if (distance_to_reachable_end > distance) {465distance_to_reachable_end = distance;466reachable_end = navigation_polys[least_cost_id].poly;467}468}469470// Check if we reached the end471if (navigation_polys[least_cost_id].poly == end_poly) {472found_route = true;473break;474}475476if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {477ERR_FAIL_NULL(least_cost_poly.poly->owner);478poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();479}480}481}482483// We did not find a route but we have both a start polygon and an end polygon at this point.484// Usually this happens because there was not a single external or internal connected edge, e.g. our start polygon is an isolated, single convex polygon.485if (!found_route) {486real_t end_d = FLT_MAX;487// Search all faces of the start polygon for the closest point to our target position.488489for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {490Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);491Vector2 spoint = t.get_closest_point_to(p_target_position);492real_t dpoint = spoint.distance_squared_to(p_target_position);493if (dpoint < end_d) {494end_point = spoint;495end_d = dpoint;496}497}498499p_query_task.path_clear();500501_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);502_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);503p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;504} else {505p_query_task.end_position = end_point;506p_query_task.end_polygon = end_poly;507p_query_task.begin_position = begin_point;508p_query_task.begin_polygon = begin_poly;509p_query_task.least_cost_id = least_cost_id;510}511}512513void NavMeshQueries2D::query_task_map_iteration_get_path(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {514p_query_task.path_clear();515516_query_task_find_start_end_positions(p_query_task, p_map_iteration);517518// Check for trivial cases.519if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {520p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;521return;522}523if (p_query_task.begin_polygon == p_query_task.end_polygon) {524p_query_task.path_clear();525_query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);526_query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);527_query_task_process_path_result_limits(p_query_task);528p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;529return;530}531532_query_task_build_path_corridor(p_query_task, p_map_iteration);533534if (p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FAILED) {535_query_task_process_path_result_limits(p_query_task);536return;537}538539// Post-Process path.540switch (p_query_task.path_postprocessing) {541case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {542_query_task_post_process_corridorfunnel(p_query_task);543} break;544case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {545_query_task_post_process_edgecentered(p_query_task);546} break;547case PathPostProcessing::PATH_POSTPROCESSING_NONE: {548_query_task_post_process_nopostprocessing(p_query_task);549} break;550default: {551WARN_PRINT("No match for used PathPostProcessing - fallback to default");552_query_task_post_process_corridorfunnel(p_query_task);553} break;554}555556p_query_task.path_reverse();557558if (p_query_task.simplify_path) {559_query_task_simplified_path_points(p_query_task);560}561562_query_task_process_path_result_limits(p_query_task);563564#ifdef DEBUG_ENABLED565// Ensure post conditions as path meta arrays if used MUST match in array size with the path points.566if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {567DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());568}569570if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {571DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());572}573574if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {575DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());576}577#endif // DEBUG_ENABLED578579p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;580}581582float NavMeshQueries2D::_calculate_path_length(const LocalVector<Vector2> &p_path, uint32_t p_start_index, uint32_t p_end_index) {583const uint32_t path_size = p_path.size();584if (path_size < 2) {585return 0.0;586}587588ERR_FAIL_COND_V(p_start_index >= p_end_index, 0.0);589ERR_FAIL_COND_V(p_start_index >= path_size - 1, 0.0);590ERR_FAIL_COND_V(p_end_index >= path_size, 0.0);591592const Vector2 *path_ptr = p_path.ptr();593594float path_length = 0.0;595596for (uint32_t i = p_start_index; i < p_end_index; i++) {597const Vector2 &vertex1 = path_ptr[i];598const Vector2 &vertex2 = path_ptr[i + 1];599float edge_length = vertex1.distance_to(vertex2);600path_length += edge_length;601}602603return path_length;604}605606void NavMeshQueries2D::_query_task_process_path_result_limits(NavMeshPathQueryTask2D &p_query_task) {607if (p_query_task.path_points.size() < 2) {608return;609}610611bool check_max_length = p_query_task.path_return_max_length > 0.0;612bool check_max_radius = p_query_task.path_return_max_radius > 0.0;613614if (!check_max_length && !check_max_radius) {615p_query_task.path_length = _calculate_path_length(p_query_task.path_points, 0, p_query_task.path_points.size() - 1);616return;617}618619LocalVector<Vector2> &path = p_query_task.path_points;620621const float max_length = p_query_task.path_return_max_length;622const float max_radius = p_query_task.path_return_max_radius;623const float max_radius_sqr = max_radius * max_radius;624625const Vector2 &start_pos = path[0];626627float accumulated_path_length = 0.0;628629Vector2 *path_ptrw = path.ptr();630631uint32_t path_max_size = path.size();632bool path_max_reached = false;633634for (uint32_t i = 0; i < path.size() - 1; i++) {635uint32_t next_index = i + 1;636const Vector2 &vertex1 = path_ptrw[i];637Vector2 &vertex2 = path_ptrw[next_index];638639float edge_length = (vertex2 - vertex1).length();640641if (check_max_radius && start_pos.distance_squared_to(vertex2) > max_radius_sqr) {642// Path point segment goes over max radius, clip it.643644real_t intersect_distance = Geometry2D::segment_intersects_circle(vertex2, vertex1, start_pos, max_radius);645if (intersect_distance != -1) {646edge_length = intersect_distance;647Vector2 intersect_positon = vertex1 + (vertex1.direction_to(vertex2) * intersect_distance);648649path_ptrw[next_index] = intersect_positon;650path_max_size = next_index + 1;651path_max_reached = true;652}653}654655if (check_max_length && accumulated_path_length + edge_length > max_length) {656// Path point segment goes over max length, clip it.657edge_length = max_length - accumulated_path_length;658Vector2 edge_direction = vertex1.direction_to(vertex2);659660path_ptrw[next_index] = vertex1 + (edge_direction * edge_length);661path_max_size = next_index + 1;662663p_query_task.path_length = accumulated_path_length + edge_length;664path_max_reached = true;665}666667accumulated_path_length += edge_length;668669if (path_max_reached) {670break;671}672}673674p_query_task.path_length = accumulated_path_length;675676if (path_max_size < path.size()) {677p_query_task.path_points.resize(path_max_size);678679if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {680p_query_task.path_meta_point_types.resize(path_max_size);681}682683if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {684p_query_task.path_meta_point_rids.resize(path_max_size);685}686687if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {688p_query_task.path_meta_point_owners.resize(path_max_size);689}690}691}692693void NavMeshQueries2D::_query_task_simplified_path_points(NavMeshPathQueryTask2D &p_query_task) {694if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {695return;696}697698const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries2D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);699700uint32_t index_count = simplified_path_indices.size();701702{703Vector2 *points_ptr = p_query_task.path_points.ptr();704for (uint32_t i = 0; i < index_count; i++) {705points_ptr[i] = points_ptr[simplified_path_indices[i]];706}707p_query_task.path_points.resize(index_count);708}709710if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {711int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();712for (uint32_t i = 0; i < index_count; i++) {713types_ptr[i] = types_ptr[simplified_path_indices[i]];714}715p_query_task.path_meta_point_types.resize(index_count);716}717718if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {719RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();720for (uint32_t i = 0; i < index_count; i++) {721rids_ptr[i] = rids_ptr[simplified_path_indices[i]];722}723p_query_task.path_meta_point_rids.resize(index_count);724}725726if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {727int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();728for (uint32_t i = 0; i < index_count; i++) {729owners_ptr[i] = owners_ptr[simplified_path_indices[i]];730}731p_query_task.path_meta_point_owners.resize(index_count);732}733}734735void NavMeshQueries2D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask2D &p_query_task) {736Vector2 end_point = p_query_task.end_position;737const Polygon *end_poly = p_query_task.end_polygon;738Vector2 begin_point = p_query_task.begin_position;739const Polygon *begin_poly = p_query_task.begin_polygon;740uint32_t least_cost_id = p_query_task.least_cost_id;741LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;742743// Set the apex poly/point to the end point.744NavigationPoly *apex_poly = &navigation_polys[least_cost_id];745746const Vector2 back_edge_closest_point = Geometry2D::get_closest_point_to_segment(end_point, apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end);747if (end_point.is_equal_approx(back_edge_closest_point)) {748// The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.749// At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.750if (apex_poly->back_navigation_poly_id != -1) {751apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];752}753}754755Vector2 apex_point = end_point;756757NavigationPoly *left_poly = apex_poly;758Vector2 left_portal = apex_point;759NavigationPoly *right_poly = apex_poly;760Vector2 right_portal = apex_point;761762NavigationPoly *p = apex_poly;763764_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);765766while (p) {767// Set left and right points of the pathway between polygons.768Vector2 left = p->back_navigation_edge_pathway_start;769Vector2 right = p->back_navigation_edge_pathway_end;770if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right) < 0) {771SWAP(left, right);772}773774bool skip = false;775if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left) >= 0) {776// Process.777if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal) > 0) {778left_poly = p;779left_portal = left;780} else {781_query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);782783apex_point = right_portal;784p = right_poly;785left_poly = p;786apex_poly = p;787left_portal = apex_point;788right_portal = apex_point;789790_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);791skip = true;792}793}794795if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right) <= 0) {796// Process.797if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal) < 0) {798right_poly = p;799right_portal = right;800} else {801_query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);802803apex_point = left_portal;804p = left_poly;805right_poly = p;806apex_poly = p;807right_portal = apex_point;808left_portal = apex_point;809810_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);811}812}813814// Go to the previous polygon.815if (p->back_navigation_poly_id != -1) {816p = &navigation_polys[p->back_navigation_poly_id];817} else {818// The end819p = nullptr;820}821}822823// If the last point is not the begin point, add it to the list.824if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {825_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);826}827}828829void NavMeshQueries2D::_query_task_post_process_edgecentered(NavMeshPathQueryTask2D &p_query_task) {830Vector2 end_point = p_query_task.end_position;831const Polygon *end_poly = p_query_task.end_polygon;832Vector2 begin_point = p_query_task.begin_position;833const Polygon *begin_poly = p_query_task.begin_polygon;834uint32_t least_cost_id = p_query_task.least_cost_id;835LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;836837_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);838839// Add mid points.840int np_id = least_cost_id;841while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {842if (navigation_polys[np_id].back_navigation_edge != -1) {843int prev = navigation_polys[np_id].back_navigation_edge;844int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->vertices.size();845Vector2 point = (navigation_polys[np_id].poly->vertices[prev] + navigation_polys[np_id].poly->vertices[prev_n]) * 0.5;846847_query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);848} else {849_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);850}851852np_id = navigation_polys[np_id].back_navigation_poly_id;853}854855_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);856}857858void NavMeshQueries2D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask2D &p_query_task) {859Vector2 end_point = p_query_task.end_position;860const Polygon *end_poly = p_query_task.end_polygon;861Vector2 begin_point = p_query_task.begin_position;862const Polygon *begin_poly = p_query_task.begin_polygon;863uint32_t least_cost_id = p_query_task.least_cost_id;864LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;865866_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);867868// Add mid points.869int np_id = least_cost_id;870while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {871_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);872873np_id = navigation_polys[np_id].back_navigation_poly_id;874}875876_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);877}878879Vector2 NavMeshQueries2D::map_iteration_get_closest_point(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {880ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);881return cp.point;882}883884RID NavMeshQueries2D::map_iteration_get_closest_point_owner(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {885ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);886return cp.owner;887}888889ClosestPointQueryResult NavMeshQueries2D::map_iteration_get_closest_point_info(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {890ClosestPointQueryResult result;891real_t closest_point_distance_squared = FLT_MAX;892893// TODO: Check for further 2D improvements.894895const LocalVector<Ref<NavRegionIteration2D>> ®ions = p_map_iteration.region_iterations;896for (const Ref<NavRegionIteration2D> ®ion : regions) {897for (const Polygon &polygon : region->get_navmesh_polygons()) {898real_t cross = -(polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);899Vector2 closest_on_polygon;900real_t closest = FLT_MAX;901bool inside = true;902Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];903for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {904Vector2 edge = polygon.vertices[point_id] - previous;905Vector2 to_point = p_point - previous;906real_t edge_to_point_cross = -edge.cross(to_point);907bool clockwise = (edge_to_point_cross * cross) > 0;908// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.909if (!clockwise) {910inside = false;911real_t point_projected_on_edge = edge.dot(to_point);912real_t edge_square = edge.length_squared();913914if (point_projected_on_edge > edge_square) {915real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);916if (distance < closest) {917closest_on_polygon = polygon.vertices[point_id];918closest = distance;919}920} else if (point_projected_on_edge < 0.0) {921real_t distance = previous.distance_squared_to(p_point);922if (distance < closest) {923closest_on_polygon = previous;924closest = distance;925}926} else {927// If we project on this edge, this will be the closest point.928real_t percent = point_projected_on_edge / edge_square;929closest_on_polygon = previous + percent * edge;930break;931}932}933previous = polygon.vertices[point_id];934}935936if (inside) {937closest_point_distance_squared = 0.0;938result.point = p_point;939result.owner = polygon.owner->get_self();940941break;942} else {943real_t distance = closest_on_polygon.distance_squared_to(p_point);944if (distance < closest_point_distance_squared) {945closest_point_distance_squared = distance;946result.point = closest_on_polygon;947result.owner = polygon.owner->get_self();948}949}950}951}952953return result;954}955956Vector2 NavMeshQueries2D::map_iteration_get_random_point(const NavMapIteration2D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {957if (p_map_iteration.region_iterations.is_empty()) {958return Vector2();959}960961LocalVector<uint32_t> accessible_regions;962accessible_regions.reserve(p_map_iteration.region_iterations.size());963964for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {965const Ref<NavRegionIteration2D> ®ion = p_map_iteration.region_iterations[i];966if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {967continue;968}969accessible_regions.push_back(i);970}971972if (accessible_regions.is_empty()) {973// All existing region polygons are disabled.974return Vector2();975}976977if (p_uniformly) {978real_t accumulated_region_surface_area = 0;979RBMap<real_t, uint32_t> accessible_regions_area_map;980981for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {982const Ref<NavRegionIteration2D> ®ion = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];983984real_t region_surface_area = region->surface_area;985986if (region_surface_area == 0.0f) {987continue;988}989990accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;991accumulated_region_surface_area += region_surface_area;992}993if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {994// All faces have no real surface / no area.995return Vector2();996}997998real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);9991000RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);1001ERR_FAIL_COND_V(!E, Vector2());1002uint32_t random_region_index = E->value;1003ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector2());10041005const Ref<NavRegionIteration2D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10061007return NavMeshQueries2D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);10081009} else {1010uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);10111012const Ref<NavRegionIteration2D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10131014return NavMeshQueries2D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);1015}1016}10171018Vector2 NavMeshQueries2D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1019ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1020return cp.point;1021}10221023ClosestPointQueryResult NavMeshQueries2D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1024ClosestPointQueryResult result;1025real_t closest_point_distance_squared = FLT_MAX;10261027// TODO: Check for further 2D improvements.10281029for (const Polygon &polygon : p_polygons) {1030real_t cross = -(polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);1031Vector2 closest_on_polygon;1032real_t closest = FLT_MAX;1033bool inside = true;1034Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];1035for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {1036Vector2 edge = polygon.vertices[point_id] - previous;1037Vector2 to_point = p_point - previous;1038real_t edge_to_point_cross = -edge.cross(to_point);1039bool clockwise = (edge_to_point_cross * cross) > 0;1040// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.1041if (!clockwise) {1042inside = false;1043real_t point_projected_on_edge = edge.dot(to_point);1044real_t edge_square = edge.length_squared();10451046if (point_projected_on_edge > edge_square) {1047real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);1048if (distance < closest) {1049closest_on_polygon = polygon.vertices[point_id];1050closest = distance;1051}1052} else if (point_projected_on_edge < 0.0) {1053real_t distance = previous.distance_squared_to(p_point);1054if (distance < closest) {1055closest_on_polygon = previous;1056closest = distance;1057}1058} else {1059// If we project on this edge, this will be the closest point.1060real_t percent = point_projected_on_edge / edge_square;1061closest_on_polygon = previous + percent * edge;1062break;1063}1064}1065previous = polygon.vertices[point_id];1066}10671068if (inside) {1069closest_point_distance_squared = 0.0;1070result.point = p_point;1071result.owner = polygon.owner->get_self();1072break;1073} else {1074real_t distance = closest_on_polygon.distance_squared_to(p_point);1075if (distance < closest_point_distance_squared) {1076closest_point_distance_squared = distance;1077result.point = closest_on_polygon;1078result.owner = polygon.owner->get_self();1079}1080}1081}10821083return result;1084}10851086RID NavMeshQueries2D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1087ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1088return cp.owner;1089}10901091static bool _line_intersects_segment(const Vector2 &p_line_normal, real_t p_line_d, const Vector2 &p_segment_begin, const Vector2 &p_segment_end, Vector2 &r_intersection) {1092Vector2 segment = p_segment_begin - p_segment_end;1093real_t den = p_line_normal.dot(segment);10941095if (Math::is_zero_approx(den)) {1096return false;1097}10981099real_t dist = (p_line_normal.dot(p_segment_begin) - p_line_d) / den;11001101if (dist < (real_t)-CMP_EPSILON || dist > (1.0 + (real_t)CMP_EPSILON)) {1102return false;1103}11041105r_intersection = p_segment_begin - segment * dist;1106return true;1107}11081109void NavMeshQueries2D::_query_task_clip_path(NavMeshPathQueryTask2D &p_query_task, const NavigationPoly *p_from_poly, const Vector2 &p_to_point, const NavigationPoly *p_to_poly) {1110Vector2 from = p_query_task.path_points[p_query_task.path_points.size() - 1];1111const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;11121113if (from.is_equal_approx(p_to_point)) {1114return;1115}11161117// Compute line parameters (equivalent to the Plane case in 3D).1118const Vector2 normal = -(from - p_to_point).orthogonal().normalized();1119const real_t d = normal.dot(from);11201121while (p_from_poly != p_to_poly) {1122Vector2 pathway_start = p_from_poly->back_navigation_edge_pathway_start;1123Vector2 pathway_end = p_from_poly->back_navigation_edge_pathway_end;11241125ERR_FAIL_COND(p_from_poly->back_navigation_poly_id == -1);1126p_from_poly = &p_navigation_polys[p_from_poly->back_navigation_poly_id];11271128if (!pathway_start.is_equal_approx(pathway_end)) {1129Vector2 inters;1130if (_line_intersects_segment(normal, d, pathway_start, pathway_end, inters)) {1131if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {1132_query_task_push_back_point_with_metadata(p_query_task, inters, p_from_poly->poly);1133}1134}1135}1136}1137}11381139bool NavMeshQueries2D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask2D &p_query_task, const NavBaseIteration2D *p_owner) {1140ERR_FAIL_NULL_V(p_owner, false);11411142bool owner_usable = true;11431144if (!p_owner->get_enabled()) {1145owner_usable = false;1146return owner_usable;1147}11481149if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {1150// Not usable. No matching bit between task filter bitmask and owner bitmask.1151owner_usable = false;1152return owner_usable;1153}11541155if (p_query_task.exclude_regions || p_query_task.include_regions) {1156switch (p_owner->get_type()) {1157case NavigationEnums2D::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {1158if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {1159// Not usable. Exclude region filter is active and this region is excluded.1160owner_usable = false;1161} else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {1162// Not usable. Include region filter is active and this region is not included.1163owner_usable = false;1164}1165} break;1166case NavigationEnums2D::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {1167const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();1168if (link_polygons.size() != 2) {1169// Not usable. Whatever this is, it is not a valid connected link.1170owner_usable = false;1171} else {1172const RID link_start_region = link_polygons[0].owner->get_self();1173const RID link_end_region = link_polygons[1].owner->get_self();1174if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {1175// Not usable. Exclude region filter is active and at least one region of the link is excluded.1176owner_usable = false;1177}1178if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {1179// Not usable. Include region filter is active and not both regions of the links are included.1180owner_usable = false;1181}1182}1183} break;1184}1185}11861187return owner_usable;1188}11891190LocalVector<uint32_t> NavMeshQueries2D::get_simplified_path_indices(const LocalVector<Vector2> &p_path, real_t p_epsilon) {1191p_epsilon = MAX(0.0, p_epsilon);1192real_t squared_epsilon = p_epsilon * p_epsilon;11931194LocalVector<uint32_t> simplified_path_indices;1195simplified_path_indices.reserve(p_path.size());1196simplified_path_indices.push_back(0);1197simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);1198simplified_path_indices.push_back(p_path.size() - 1);11991200return simplified_path_indices;1201}12021203void NavMeshQueries2D::simplify_path_segment(int p_start_inx, int p_end_inx, const LocalVector<Vector2> &p_points, real_t p_epsilon, LocalVector<uint32_t> &r_simplified_path_indices) {1204real_t point_max_distance = 0.0;1205int point_max_index = 0;12061207for (int i = p_start_inx; i < p_end_inx; i++) {1208const Vector2 &checked_point = p_points[i];12091210const Vector2 closest_point = Geometry2D::get_closest_point_to_segment(checked_point, p_points[p_start_inx], p_points[p_end_inx]);1211real_t distance_squared = closest_point.distance_squared_to(checked_point);12121213if (distance_squared > point_max_distance) {1214point_max_index = i;1215point_max_distance = distance_squared;1216}1217}12181219if (point_max_distance > p_epsilon) {1220simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);1221r_simplified_path_indices.push_back(point_max_index);1222simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);1223}1224}122512261227