Path: blob/master/modules/navigation_2d/2d/nav_mesh_queries_2d.cpp
10278 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"38#include "servers/navigation/navigation_utilities.h"3940using namespace Nav2D;4142#define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))4344bool NavMeshQueries2D::emit_callback(const Callable &p_callback) {45ERR_FAIL_COND_V(!p_callback.is_valid(), false);4647Callable::CallError ce;48Variant result;49p_callback.callp(nullptr, 0, result, ce);5051return ce.error == Callable::CallError::CALL_OK;52}5354Vector2 NavMeshQueries2D::polygons_get_random_point(const LocalVector<Polygon> &p_polygons, uint32_t p_navigation_layers, bool p_uniformly) {55const LocalVector<Polygon> ®ion_polygons = p_polygons;5657if (region_polygons.is_empty()) {58return Vector2();59}6061if (p_uniformly) {62real_t accumulated_area = 0;63RBMap<real_t, uint32_t> region_area_map;6465for (uint32_t rp_index = 0; rp_index < region_polygons.size(); rp_index++) {66const Polygon ®ion_polygon = region_polygons[rp_index];67real_t polyon_area = region_polygon.surface_area;6869if (polyon_area == 0.0) {70continue;71}72region_area_map[accumulated_area] = rp_index;73accumulated_area += polyon_area;74}75if (region_area_map.is_empty() || accumulated_area == 0) {76// All polygons have no real surface / no area.77return Vector2();78}7980real_t region_area_map_pos = Math::random(real_t(0), accumulated_area);8182RBMap<real_t, uint32_t>::Iterator region_E = region_area_map.find_closest(region_area_map_pos);83ERR_FAIL_COND_V(!region_E, Vector2());84uint32_t rrp_polygon_index = region_E->value;85ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector2());8687const Polygon &rr_polygon = region_polygons[rrp_polygon_index];8889real_t accumulated_polygon_area = 0;90RBMap<real_t, uint32_t> polygon_area_map;9192for (uint32_t rpp_index = 2; rpp_index < rr_polygon.vertices.size(); rpp_index++) {93real_t triangle_area = Triangle2(rr_polygon.vertices[0], rr_polygon.vertices[rpp_index - 1], rr_polygon.vertices[rpp_index]).get_area();9495if (triangle_area == 0.0) {96continue;97}98polygon_area_map[accumulated_polygon_area] = rpp_index;99accumulated_polygon_area += triangle_area;100}101if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {102// All faces have no real surface / no area.103return Vector2();104}105106real_t polygon_area_map_pos = Math::random(real_t(0), accumulated_polygon_area);107108RBMap<real_t, uint32_t>::Iterator polygon_E = polygon_area_map.find_closest(polygon_area_map_pos);109ERR_FAIL_COND_V(!polygon_E, Vector2());110uint32_t rrp_face_index = polygon_E->value;111ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.vertices.size(), Vector2());112113const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);114115Vector2 triangle_random_position = triangle.get_random_point_inside();116return triangle_random_position;117118} else {119uint32_t rrp_polygon_index = Math::random(int(0), region_polygons.size() - 1);120121const Polygon &rr_polygon = region_polygons[rrp_polygon_index];122123uint32_t rrp_face_index = Math::random(int(2), rr_polygon.vertices.size() - 1);124125const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);126127Vector2 triangle_random_position = triangle.get_random_point_inside();128return triangle_random_position;129}130}131132void NavMeshQueries2D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask2D &p_query_task, const Vector2 &p_point, const Polygon *p_point_polygon) {133if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {134p_query_task.path_meta_point_types.push_back(p_point_polygon->owner->get_type());135}136137if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {138p_query_task.path_meta_point_rids.push_back(p_point_polygon->owner->get_self());139}140141if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {142p_query_task.path_meta_point_owners.push_back(p_point_polygon->owner->get_owner_id());143}144145p_query_task.path_points.push_back(p_point);146}147148void NavMeshQueries2D::map_query_path(NavMap2D *p_map, const Ref<NavigationPathQueryParameters2D> &p_query_parameters, Ref<NavigationPathQueryResult2D> p_query_result, const Callable &p_callback) {149ERR_FAIL_NULL(p_map);150ERR_FAIL_COND(p_query_parameters.is_null());151ERR_FAIL_COND(p_query_result.is_null());152153using namespace NavigationUtilities;154155NavMeshQueries2D::NavMeshPathQueryTask2D query_task;156query_task.start_position = p_query_parameters->get_start_position();157query_task.target_position = p_query_parameters->get_target_position();158query_task.navigation_layers = p_query_parameters->get_navigation_layers();159query_task.callback = p_callback;160161const TypedArray<RID> &_excluded_regions = p_query_parameters->get_excluded_regions();162const TypedArray<RID> &_included_regions = p_query_parameters->get_included_regions();163164uint32_t _excluded_region_count = _excluded_regions.size();165uint32_t _included_region_count = _included_regions.size();166167query_task.exclude_regions = _excluded_region_count > 0;168query_task.include_regions = _included_region_count > 0;169170if (query_task.exclude_regions) {171query_task.excluded_regions.resize(_excluded_region_count);172for (uint32_t i = 0; i < _excluded_region_count; i++) {173query_task.excluded_regions[i] = _excluded_regions[i];174}175}176177if (query_task.include_regions) {178query_task.included_regions.resize(_included_region_count);179for (uint32_t i = 0; i < _included_region_count; i++) {180query_task.included_regions[i] = _included_regions[i];181}182}183184switch (p_query_parameters->get_pathfinding_algorithm()) {185case NavigationPathQueryParameters2D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR: {186query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;187} break;188default: {189WARN_PRINT("No match for used PathfindingAlgorithm - fallback to default");190query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;191} break;192}193194switch (p_query_parameters->get_path_postprocessing()) {195case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {196query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;197} break;198case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {199query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;200} break;201case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_NONE: {202query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_NONE;203} break;204default: {205WARN_PRINT("No match for used PathPostProcessing - fallback to default");206query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;207} break;208}209210query_task.metadata_flags = (int64_t)p_query_parameters->get_metadata_flags();211query_task.simplify_path = p_query_parameters->get_simplify_path();212query_task.simplify_epsilon = p_query_parameters->get_simplify_epsilon();213query_task.path_return_max_length = p_query_parameters->get_path_return_max_length();214query_task.path_return_max_radius = p_query_parameters->get_path_return_max_radius();215query_task.path_search_max_polygons = p_query_parameters->get_path_search_max_polygons();216query_task.path_search_max_distance = p_query_parameters->get_path_search_max_distance();217query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_STARTED;218219p_map->query_path(query_task);220221p_query_result->set_data(222query_task.path_points,223query_task.path_meta_point_types,224query_task.path_meta_point_rids,225query_task.path_meta_point_owners);226p_query_result->set_path_length(query_task.path_length);227228if (query_task.callback.is_valid()) {229if (emit_callback(query_task.callback)) {230query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_DISPATCHED;231} else {232query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_FAILED;233}234}235}236237void NavMeshQueries2D::_query_task_find_start_end_positions(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {238real_t begin_d = FLT_MAX;239real_t end_d = FLT_MAX;240241const LocalVector<Ref<NavRegionIteration2D>> ®ions = p_map_iteration.region_iterations;242243for (const Ref<NavRegionIteration2D> ®ion : regions) {244if (!_query_task_is_connection_owner_usable(p_query_task, region.ptr())) {245continue;246}247248// Find the initial poly and the end poly on this map.249for (const Polygon &p : region->get_navmesh_polygons()) {250// Only consider the polygon if it in a region with compatible layers.251if ((p_query_task.navigation_layers & p.owner->get_navigation_layers()) == 0) {252continue;253}254255// For each triangle check the distance between the origin/destination.256for (uint32_t point_id = 2; point_id < p.vertices.size(); point_id++) {257const Triangle2 triangle(p.vertices[0], p.vertices[point_id - 1], p.vertices[point_id]);258259Vector2 point = triangle.get_closest_point_to(p_query_task.start_position);260real_t distance_to_point = point.distance_to(p_query_task.start_position);261if (distance_to_point < begin_d) {262begin_d = distance_to_point;263p_query_task.begin_polygon = &p;264p_query_task.begin_position = point;265}266267point = triangle.get_closest_point_to(p_query_task.target_position);268distance_to_point = point.distance_to(p_query_task.target_position);269if (distance_to_point < end_d) {270end_d = distance_to_point;271p_query_task.end_polygon = &p;272p_query_task.end_position = point;273}274}275}276}277}278279void 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) {280const NavBaseIteration2D *connection_owner = p_connection.polygon->owner;281ERR_FAIL_NULL(connection_owner);282const bool owner_is_usable = _query_task_is_connection_owner_usable(p_query_task, connection_owner);283if (!owner_is_usable) {284return;285}286287Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>288&traversable_polys = p_query_task.path_query_slot->traversable_polys;289LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;290291real_t poly_travel_cost = p_least_cost_poly.poly->owner->get_travel_cost();292293Vector2 new_entry = Geometry2D::get_closest_point_to_segment(p_least_cost_poly.entry, p_connection.pathway_start, p_connection.pathway_end);294real_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;295296// Check if the neighbor polygon has already been processed.297NavigationPoly &neighbor_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[p_connection.polygon]];298if (new_traveled_distance < neighbor_poly.traveled_distance) {299// Add the polygon to the heap of polygons to traverse next.300neighbor_poly.back_navigation_poly_id = p_least_cost_id;301neighbor_poly.back_navigation_edge = p_connection.edge;302neighbor_poly.back_navigation_edge_pathway_start = p_connection.pathway_start;303neighbor_poly.back_navigation_edge_pathway_end = p_connection.pathway_end;304neighbor_poly.traveled_distance = new_traveled_distance;305neighbor_poly.distance_to_destination =306new_entry.distance_to(p_end_point) *307connection_owner->get_travel_cost();308neighbor_poly.entry = new_entry;309310if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {311traversable_polys.shift(neighbor_poly.traversable_poly_index);312} else {313neighbor_poly.poly = p_connection.polygon;314traversable_polys.push(&neighbor_poly);315}316}317}318319void NavMeshQueries2D::_query_task_build_path_corridor(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {320const Vector2 p_target_position = p_query_task.target_position;321const Polygon *begin_poly = p_query_task.begin_polygon;322const Polygon *end_poly = p_query_task.end_polygon;323Vector2 begin_point = p_query_task.begin_position;324Vector2 end_point = p_query_task.end_position;325326// Heap of polygons to travel next.327Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>328&traversable_polys = p_query_task.path_query_slot->traversable_polys;329traversable_polys.clear();330331LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;332for (NavigationPoly &polygon : navigation_polys) {333polygon.reset();334}335336// Initialize the matching navigation polygon.337NavigationPoly &begin_navigation_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[begin_poly]];338begin_navigation_poly.poly = begin_poly;339begin_navigation_poly.entry = begin_point;340begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;341begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;342begin_navigation_poly.traveled_distance = 0.f;343344// This is an implementation of the A* algorithm.345uint32_t least_cost_id = p_query_task.path_query_slot->poly_to_id[begin_poly];346bool found_route = false;347348const Polygon *reachable_end = nullptr;349real_t distance_to_reachable_end = FLT_MAX;350bool is_reachable = true;351real_t poly_enter_cost = 0.0;352353const HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = p_map_iteration.navbases_polygons_external_connections;354355// True if we reached the max polygon search count or distance from the begin position.356bool path_search_max_reached = false;357358const float path_search_max_distance_sqr = p_query_task.path_search_max_distance * p_query_task.path_search_max_distance;359bool has_path_search_max_distance = path_search_max_distance_sqr > 0.0;360361int processed_polygon_count = 0;362bool has_path_search_max_polygons = p_query_task.path_search_max_polygons > 0;363364bool has_path_search_max = p_query_task.path_search_max_polygons > 0 || path_search_max_distance_sqr > 0.0;365366while (true) {367const NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];368369const NavBaseIteration2D *least_cost_navbase = least_cost_poly.poly->owner;370371processed_polygon_count += 1;372373const uint32_t navbase_local_polygon_id = least_cost_poly.poly->id;374const LocalVector<LocalVector<Connection>> &navbase_polygons_to_connections = least_cost_poly.poly->owner->get_internal_connections();375376if (navbase_polygons_to_connections.size() > 0) {377const LocalVector<Connection> &polygon_connections = navbase_polygons_to_connections[navbase_local_polygon_id];378379for (const Connection &connection : polygon_connections) {380_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);381}382}383384// Search region external navmesh polygon connections, aka connections to other regions created by outline edge merge or links.385for (const Connection &connection : navbases_polygons_external_connections[least_cost_navbase][navbase_local_polygon_id]) {386_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);387}388389if (has_path_search_max && !path_search_max_reached) {390if (has_path_search_max_polygons && processed_polygon_count >= p_query_task.path_search_max_polygons) {391path_search_max_reached = true;392traversable_polys.clear();393} else if (has_path_search_max_distance && begin_point.distance_squared_to(least_cost_poly.entry) > path_search_max_distance_sqr) {394path_search_max_reached = true;395traversable_polys.clear();396}397}398399poly_enter_cost = 0;400// When the heap of traversable polygons is empty at this point it means the end polygon is401// unreachable.402if (traversable_polys.is_empty()) {403// Thus use the further reachable polygon404ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");405is_reachable = false;406if (reachable_end == nullptr) {407// The path is not found and there is not a way out.408break;409}410411// Set as end point the furthest reachable point.412end_poly = reachable_end;413real_t end_d = FLT_MAX;414415for (uint32_t point_id = 2; point_id < end_poly->vertices.size(); point_id++) {416Triangle2 t(end_poly->vertices[0], end_poly->vertices[point_id - 1], end_poly->vertices[point_id]);417Vector2 spoint = t.get_closest_point_to(p_target_position);418real_t dpoint = spoint.distance_squared_to(p_target_position);419if (dpoint < end_d) {420end_point = spoint;421end_d = dpoint;422}423}424425// Search all faces of start polygon as well.426bool closest_point_on_start_poly = false;427428for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {429Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);430Vector2 spoint = t.get_closest_point_to(p_target_position);431real_t dpoint = spoint.distance_squared_to(p_target_position);432if (dpoint < end_d) {433end_point = spoint;434end_d = dpoint;435closest_point_on_start_poly = true;436}437}438439if (closest_point_on_start_poly) {440// No point to run PostProcessing when start and end convex polygon is the same.441p_query_task.path_clear();442443_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);444_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);445p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;446return;447}448449for (NavigationPoly &nav_poly : navigation_polys) {450nav_poly.poly = nullptr;451nav_poly.traveled_distance = FLT_MAX;452}453uint32_t _bp_id = p_query_task.path_query_slot->poly_to_id[begin_poly];454navigation_polys[_bp_id].poly = begin_poly;455navigation_polys[_bp_id].traveled_distance = 0;456least_cost_id = _bp_id;457reachable_end = nullptr;458} else {459// Pop the polygon with the lowest travel cost from the heap of traversable polygons.460least_cost_id = p_query_task.path_query_slot->poly_to_id[traversable_polys.pop()->poly];461462// Store the farthest reachable end polygon in case our goal is not reachable.463if (is_reachable) {464real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);465if (distance_to_reachable_end > distance) {466distance_to_reachable_end = distance;467reachable_end = navigation_polys[least_cost_id].poly;468}469}470471// Check if we reached the end472if (navigation_polys[least_cost_id].poly == end_poly) {473found_route = true;474break;475}476477if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {478ERR_FAIL_NULL(least_cost_poly.poly->owner);479poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();480}481}482}483484// We did not find a route but we have both a start polygon and an end polygon at this point.485// 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.486if (!found_route) {487real_t end_d = FLT_MAX;488// Search all faces of the start polygon for the closest point to our target position.489490for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {491Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);492Vector2 spoint = t.get_closest_point_to(p_target_position);493real_t dpoint = spoint.distance_squared_to(p_target_position);494if (dpoint < end_d) {495end_point = spoint;496end_d = dpoint;497}498}499500p_query_task.path_clear();501502_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);503_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);504p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;505} else {506p_query_task.end_position = end_point;507p_query_task.end_polygon = end_poly;508p_query_task.begin_position = begin_point;509p_query_task.begin_polygon = begin_poly;510p_query_task.least_cost_id = least_cost_id;511}512}513514void NavMeshQueries2D::query_task_map_iteration_get_path(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {515p_query_task.path_clear();516517_query_task_find_start_end_positions(p_query_task, p_map_iteration);518519// Check for trivial cases.520if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {521p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;522return;523}524if (p_query_task.begin_polygon == p_query_task.end_polygon) {525p_query_task.path_clear();526_query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);527_query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);528_query_task_process_path_result_limits(p_query_task);529p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;530return;531}532533_query_task_build_path_corridor(p_query_task, p_map_iteration);534535if (p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FAILED) {536_query_task_process_path_result_limits(p_query_task);537return;538}539540// Post-Process path.541switch (p_query_task.path_postprocessing) {542case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {543_query_task_post_process_corridorfunnel(p_query_task);544} break;545case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {546_query_task_post_process_edgecentered(p_query_task);547} break;548case PathPostProcessing::PATH_POSTPROCESSING_NONE: {549_query_task_post_process_nopostprocessing(p_query_task);550} break;551default: {552WARN_PRINT("No match for used PathPostProcessing - fallback to default");553_query_task_post_process_corridorfunnel(p_query_task);554} break;555}556557p_query_task.path_reverse();558559if (p_query_task.simplify_path) {560_query_task_simplified_path_points(p_query_task);561}562563_query_task_process_path_result_limits(p_query_task);564565#ifdef DEBUG_ENABLED566// Ensure post conditions as path meta arrays if used MUST match in array size with the path points.567if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {568DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());569}570571if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {572DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());573}574575if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {576DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());577}578#endif // DEBUG_ENABLED579580p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;581}582583float NavMeshQueries2D::_calculate_path_length(const LocalVector<Vector2> &p_path, uint32_t p_start_index, uint32_t p_end_index) {584const uint32_t path_size = p_path.size();585if (path_size < 2) {586return 0.0;587}588589ERR_FAIL_COND_V(p_start_index >= p_end_index, 0.0);590ERR_FAIL_COND_V(p_start_index >= path_size - 1, 0.0);591ERR_FAIL_COND_V(p_end_index >= path_size, 0.0);592593const Vector2 *path_ptr = p_path.ptr();594595float path_length = 0.0;596597for (uint32_t i = p_start_index; i < p_end_index; i++) {598const Vector2 &vertex1 = path_ptr[i];599const Vector2 &vertex2 = path_ptr[i + 1];600float edge_length = vertex1.distance_to(vertex2);601path_length += edge_length;602}603604return path_length;605}606607void NavMeshQueries2D::_query_task_process_path_result_limits(NavMeshPathQueryTask2D &p_query_task) {608if (p_query_task.path_points.size() < 2) {609return;610}611612bool check_max_length = p_query_task.path_return_max_length > 0.0;613bool check_max_radius = p_query_task.path_return_max_radius > 0.0;614615if (!check_max_length && !check_max_radius) {616p_query_task.path_length = _calculate_path_length(p_query_task.path_points, 0, p_query_task.path_points.size() - 1);617return;618}619620LocalVector<Vector2> &path = p_query_task.path_points;621622const float max_length = p_query_task.path_return_max_length;623const float max_radius = p_query_task.path_return_max_radius;624const float max_radius_sqr = max_radius * max_radius;625626const Vector2 &start_pos = path[0];627628float accumulated_path_length = 0.0;629630Vector2 *path_ptrw = path.ptr();631632uint32_t path_max_size = path.size();633bool path_max_reached = false;634635for (uint32_t i = 0; i < path.size() - 1; i++) {636uint32_t next_index = i + 1;637const Vector2 &vertex1 = path_ptrw[i];638Vector2 &vertex2 = path_ptrw[next_index];639640float edge_length = (vertex2 - vertex1).length();641642if (check_max_radius && start_pos.distance_squared_to(vertex2) > max_radius_sqr) {643// Path point segment goes over max radius, clip it.644645real_t intersect_distance = Geometry2D::segment_intersects_circle(vertex2, vertex1, start_pos, max_radius);646if (intersect_distance != -1) {647edge_length = intersect_distance;648Vector2 intersect_positon = vertex1 + (vertex1.direction_to(vertex2) * intersect_distance);649650path_ptrw[next_index] = intersect_positon;651path_max_size = next_index + 1;652path_max_reached = true;653}654}655656if (check_max_length && accumulated_path_length + edge_length > max_length) {657// Path point segment goes over max length, clip it.658edge_length = max_length - accumulated_path_length;659Vector2 edge_direction = vertex1.direction_to(vertex2);660661path_ptrw[next_index] = vertex1 + (edge_direction * edge_length);662path_max_size = next_index + 1;663664p_query_task.path_length = accumulated_path_length + edge_length;665path_max_reached = true;666}667668accumulated_path_length += edge_length;669670if (path_max_reached) {671break;672}673}674675p_query_task.path_length = accumulated_path_length;676677if (path_max_size < path.size()) {678p_query_task.path_points.resize(path_max_size);679680if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {681p_query_task.path_meta_point_types.resize(path_max_size);682}683684if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {685p_query_task.path_meta_point_rids.resize(path_max_size);686}687688if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {689p_query_task.path_meta_point_owners.resize(path_max_size);690}691}692}693694void NavMeshQueries2D::_query_task_simplified_path_points(NavMeshPathQueryTask2D &p_query_task) {695if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {696return;697}698699const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries2D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);700701uint32_t index_count = simplified_path_indices.size();702703{704Vector2 *points_ptr = p_query_task.path_points.ptr();705for (uint32_t i = 0; i < index_count; i++) {706points_ptr[i] = points_ptr[simplified_path_indices[i]];707}708p_query_task.path_points.resize(index_count);709}710711if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {712int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();713for (uint32_t i = 0; i < index_count; i++) {714types_ptr[i] = types_ptr[simplified_path_indices[i]];715}716p_query_task.path_meta_point_types.resize(index_count);717}718719if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {720RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();721for (uint32_t i = 0; i < index_count; i++) {722rids_ptr[i] = rids_ptr[simplified_path_indices[i]];723}724p_query_task.path_meta_point_rids.resize(index_count);725}726727if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {728int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();729for (uint32_t i = 0; i < index_count; i++) {730owners_ptr[i] = owners_ptr[simplified_path_indices[i]];731}732p_query_task.path_meta_point_owners.resize(index_count);733}734}735736void NavMeshQueries2D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask2D &p_query_task) {737Vector2 end_point = p_query_task.end_position;738const Polygon *end_poly = p_query_task.end_polygon;739Vector2 begin_point = p_query_task.begin_position;740const Polygon *begin_poly = p_query_task.begin_polygon;741uint32_t least_cost_id = p_query_task.least_cost_id;742LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;743744// Set the apex poly/point to the end point.745NavigationPoly *apex_poly = &navigation_polys[least_cost_id];746747const 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);748if (end_point.is_equal_approx(back_edge_closest_point)) {749// The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.750// At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.751if (apex_poly->back_navigation_poly_id != -1) {752apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];753}754}755756Vector2 apex_point = end_point;757758NavigationPoly *left_poly = apex_poly;759Vector2 left_portal = apex_point;760NavigationPoly *right_poly = apex_poly;761Vector2 right_portal = apex_point;762763NavigationPoly *p = apex_poly;764765_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);766767while (p) {768// Set left and right points of the pathway between polygons.769Vector2 left = p->back_navigation_edge_pathway_start;770Vector2 right = p->back_navigation_edge_pathway_end;771if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right) < 0) {772SWAP(left, right);773}774775bool skip = false;776if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left) >= 0) {777// Process.778if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal) > 0) {779left_poly = p;780left_portal = left;781} else {782_query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);783784apex_point = right_portal;785p = right_poly;786left_poly = p;787apex_poly = p;788left_portal = apex_point;789right_portal = apex_point;790791_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);792skip = true;793}794}795796if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right) <= 0) {797// Process.798if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal) < 0) {799right_poly = p;800right_portal = right;801} else {802_query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);803804apex_point = left_portal;805p = left_poly;806right_poly = p;807apex_poly = p;808right_portal = apex_point;809left_portal = apex_point;810811_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);812}813}814815// Go to the previous polygon.816if (p->back_navigation_poly_id != -1) {817p = &navigation_polys[p->back_navigation_poly_id];818} else {819// The end820p = nullptr;821}822}823824// If the last point is not the begin point, add it to the list.825if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {826_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);827}828}829830void NavMeshQueries2D::_query_task_post_process_edgecentered(NavMeshPathQueryTask2D &p_query_task) {831Vector2 end_point = p_query_task.end_position;832const Polygon *end_poly = p_query_task.end_polygon;833Vector2 begin_point = p_query_task.begin_position;834const Polygon *begin_poly = p_query_task.begin_polygon;835uint32_t least_cost_id = p_query_task.least_cost_id;836LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;837838_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);839840// Add mid points.841int np_id = least_cost_id;842while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {843if (navigation_polys[np_id].back_navigation_edge != -1) {844int prev = navigation_polys[np_id].back_navigation_edge;845int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->vertices.size();846Vector2 point = (navigation_polys[np_id].poly->vertices[prev] + navigation_polys[np_id].poly->vertices[prev_n]) * 0.5;847848_query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);849} else {850_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);851}852853np_id = navigation_polys[np_id].back_navigation_poly_id;854}855856_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);857}858859void NavMeshQueries2D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask2D &p_query_task) {860Vector2 end_point = p_query_task.end_position;861const Polygon *end_poly = p_query_task.end_polygon;862Vector2 begin_point = p_query_task.begin_position;863const Polygon *begin_poly = p_query_task.begin_polygon;864uint32_t least_cost_id = p_query_task.least_cost_id;865LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;866867_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);868869// Add mid points.870int np_id = least_cost_id;871while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {872_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);873874np_id = navigation_polys[np_id].back_navigation_poly_id;875}876877_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);878}879880Vector2 NavMeshQueries2D::map_iteration_get_closest_point(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {881ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);882return cp.point;883}884885RID NavMeshQueries2D::map_iteration_get_closest_point_owner(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {886ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);887return cp.owner;888}889890ClosestPointQueryResult NavMeshQueries2D::map_iteration_get_closest_point_info(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {891ClosestPointQueryResult result;892real_t closest_point_distance_squared = FLT_MAX;893894// TODO: Check for further 2D improvements.895896const LocalVector<Ref<NavRegionIteration2D>> ®ions = p_map_iteration.region_iterations;897for (const Ref<NavRegionIteration2D> ®ion : regions) {898for (const Polygon &polygon : region->get_navmesh_polygons()) {899real_t cross = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);900Vector2 closest_on_polygon;901real_t closest = FLT_MAX;902bool inside = true;903Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];904for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {905Vector2 edge = polygon.vertices[point_id] - previous;906Vector2 to_point = p_point - previous;907real_t edge_to_point_cross = edge.cross(to_point);908bool clockwise = (edge_to_point_cross * cross) > 0;909// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.910if (!clockwise) {911inside = false;912real_t point_projected_on_edge = edge.dot(to_point);913real_t edge_square = edge.length_squared();914915if (point_projected_on_edge > edge_square) {916real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);917if (distance < closest) {918closest_on_polygon = polygon.vertices[point_id];919closest = distance;920}921} else if (point_projected_on_edge < 0.0) {922real_t distance = previous.distance_squared_to(p_point);923if (distance < closest) {924closest_on_polygon = previous;925closest = distance;926}927} else {928// If we project on this edge, this will be the closest point.929real_t percent = point_projected_on_edge / edge_square;930closest_on_polygon = previous + percent * edge;931break;932}933}934previous = polygon.vertices[point_id];935}936937if (inside) {938closest_point_distance_squared = 0.0;939result.point = p_point;940result.owner = polygon.owner->get_self();941942break;943} else {944real_t distance = closest_on_polygon.distance_squared_to(p_point);945if (distance < closest_point_distance_squared) {946closest_point_distance_squared = distance;947result.point = closest_on_polygon;948result.owner = polygon.owner->get_self();949}950}951}952}953954return result;955}956957Vector2 NavMeshQueries2D::map_iteration_get_random_point(const NavMapIteration2D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {958if (p_map_iteration.region_iterations.is_empty()) {959return Vector2();960}961962LocalVector<uint32_t> accessible_regions;963accessible_regions.reserve(p_map_iteration.region_iterations.size());964965for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {966const Ref<NavRegionIteration2D> ®ion = p_map_iteration.region_iterations[i];967if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {968continue;969}970accessible_regions.push_back(i);971}972973if (accessible_regions.is_empty()) {974// All existing region polygons are disabled.975return Vector2();976}977978if (p_uniformly) {979real_t accumulated_region_surface_area = 0;980RBMap<real_t, uint32_t> accessible_regions_area_map;981982for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {983const Ref<NavRegionIteration2D> ®ion = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];984985real_t region_surface_area = region->surface_area;986987if (region_surface_area == 0.0f) {988continue;989}990991accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;992accumulated_region_surface_area += region_surface_area;993}994if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {995// All faces have no real surface / no area.996return Vector2();997}998999real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);10001001RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);1002ERR_FAIL_COND_V(!E, Vector2());1003uint32_t random_region_index = E->value;1004ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector2());10051006const Ref<NavRegionIteration2D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10071008return NavMeshQueries2D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);10091010} else {1011uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);10121013const Ref<NavRegionIteration2D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10141015return NavMeshQueries2D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);1016}1017}10181019Vector2 NavMeshQueries2D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1020ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1021return cp.point;1022}10231024ClosestPointQueryResult NavMeshQueries2D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1025ClosestPointQueryResult result;1026real_t closest_point_distance_squared = FLT_MAX;10271028// TODO: Check for further 2D improvements.10291030for (const Polygon &polygon : p_polygons) {1031real_t cross = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);1032Vector2 closest_on_polygon;1033real_t closest = FLT_MAX;1034bool inside = true;1035Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];1036for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {1037Vector2 edge = polygon.vertices[point_id] - previous;1038Vector2 to_point = p_point - previous;1039real_t edge_to_point_cross = edge.cross(to_point);1040bool clockwise = (edge_to_point_cross * cross) > 0;1041// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.1042if (!clockwise) {1043inside = false;1044real_t point_projected_on_edge = edge.dot(to_point);1045real_t edge_square = edge.length_squared();10461047if (point_projected_on_edge > edge_square) {1048real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);1049if (distance < closest) {1050closest_on_polygon = polygon.vertices[point_id];1051closest = distance;1052}1053} else if (point_projected_on_edge < 0.0) {1054real_t distance = previous.distance_squared_to(p_point);1055if (distance < closest) {1056closest_on_polygon = previous;1057closest = distance;1058}1059} else {1060// If we project on this edge, this will be the closest point.1061real_t percent = point_projected_on_edge / edge_square;1062closest_on_polygon = previous + percent * edge;1063break;1064}1065}1066previous = polygon.vertices[point_id];1067}10681069if (inside) {1070closest_point_distance_squared = 0.0;1071result.point = p_point;1072result.owner = polygon.owner->get_self();1073break;1074} else {1075real_t distance = closest_on_polygon.distance_squared_to(p_point);1076if (distance < closest_point_distance_squared) {1077closest_point_distance_squared = distance;1078result.point = closest_on_polygon;1079result.owner = polygon.owner->get_self();1080}1081}1082}10831084return result;1085}10861087RID NavMeshQueries2D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {1088ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1089return cp.owner;1090}10911092static 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) {1093Vector2 segment = p_segment_begin - p_segment_end;1094real_t den = p_line_normal.dot(segment);10951096if (Math::is_zero_approx(den)) {1097return false;1098}10991100real_t dist = (p_line_normal.dot(p_segment_begin) - p_line_d) / den;11011102if (dist < (real_t)-CMP_EPSILON || dist > (1.0 + (real_t)CMP_EPSILON)) {1103return false;1104}11051106r_intersection = p_segment_begin - segment * dist;1107return true;1108}11091110void NavMeshQueries2D::_query_task_clip_path(NavMeshPathQueryTask2D &p_query_task, const NavigationPoly *p_from_poly, const Vector2 &p_to_point, const NavigationPoly *p_to_poly) {1111Vector2 from = p_query_task.path_points[p_query_task.path_points.size() - 1];1112const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;11131114if (from.is_equal_approx(p_to_point)) {1115return;1116}11171118// Compute line parameters (equivalent to the Plane case in 3D).1119const Vector2 normal = -(from - p_to_point).orthogonal().normalized();1120const real_t d = normal.dot(from);11211122while (p_from_poly != p_to_poly) {1123Vector2 pathway_start = p_from_poly->back_navigation_edge_pathway_start;1124Vector2 pathway_end = p_from_poly->back_navigation_edge_pathway_end;11251126ERR_FAIL_COND(p_from_poly->back_navigation_poly_id == -1);1127p_from_poly = &p_navigation_polys[p_from_poly->back_navigation_poly_id];11281129if (!pathway_start.is_equal_approx(pathway_end)) {1130Vector2 inters;1131if (_line_intersects_segment(normal, d, pathway_start, pathway_end, inters)) {1132if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {1133_query_task_push_back_point_with_metadata(p_query_task, inters, p_from_poly->poly);1134}1135}1136}1137}1138}11391140bool NavMeshQueries2D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask2D &p_query_task, const NavBaseIteration2D *p_owner) {1141ERR_FAIL_NULL_V(p_owner, false);11421143bool owner_usable = true;11441145if (!p_owner->get_enabled()) {1146owner_usable = false;1147return owner_usable;1148}11491150if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {1151// Not usable. No matching bit between task filter bitmask and owner bitmask.1152owner_usable = false;1153return owner_usable;1154}11551156if (p_query_task.exclude_regions || p_query_task.include_regions) {1157switch (p_owner->get_type()) {1158case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {1159if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {1160// Not usable. Exclude region filter is active and this region is excluded.1161owner_usable = false;1162} else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {1163// Not usable. Include region filter is active and this region is not included.1164owner_usable = false;1165}1166} break;1167case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {1168const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();1169if (link_polygons.size() != 2) {1170// Not usable. Whatever this is, it is not a valid connected link.1171owner_usable = false;1172} else {1173const RID link_start_region = link_polygons[0].owner->get_self();1174const RID link_end_region = link_polygons[1].owner->get_self();1175if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {1176// Not usable. Exclude region filter is active and at least one region of the link is excluded.1177owner_usable = false;1178}1179if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {1180// Not usable. Include region filter is active and not both regions of the links are included.1181owner_usable = false;1182}1183}1184} break;1185}1186}11871188return owner_usable;1189}11901191LocalVector<uint32_t> NavMeshQueries2D::get_simplified_path_indices(const LocalVector<Vector2> &p_path, real_t p_epsilon) {1192p_epsilon = MAX(0.0, p_epsilon);1193real_t squared_epsilon = p_epsilon * p_epsilon;11941195LocalVector<uint32_t> simplified_path_indices;1196simplified_path_indices.reserve(p_path.size());1197simplified_path_indices.push_back(0);1198simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);1199simplified_path_indices.push_back(p_path.size() - 1);12001201return simplified_path_indices;1202}12031204void 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) {1205real_t point_max_distance = 0.0;1206int point_max_index = 0;12071208for (int i = p_start_inx; i < p_end_inx; i++) {1209const Vector2 &checked_point = p_points[i];12101211const Vector2 closest_point = Geometry2D::get_closest_point_to_segment(checked_point, p_points[p_start_inx], p_points[p_end_inx]);1212real_t distance_squared = closest_point.distance_squared_to(checked_point);12131214if (distance_squared > point_max_distance) {1215point_max_index = i;1216point_max_distance = distance_squared;1217}1218}12191220if (point_max_distance > p_epsilon) {1221simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);1222r_simplified_path_indices.push_back(point_max_index);1223simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);1224}1225}122612271228