Path: blob/master/modules/navigation_3d/3d/nav_mesh_queries_3d.cpp
11353 views
/**************************************************************************/1/* nav_mesh_queries_3d.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_3d.h"3132#include "../nav_base_3d.h"33#include "../nav_map_3d.h"34#include "nav_region_iteration_3d.h"3536#include "core/math/geometry_2d.h"37#include "core/math/geometry_3d.h"3839using namespace Nav3D;4041#define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))4243bool NavMeshQueries3D::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}5253Vector3 NavMeshQueries3D::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 Vector3();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 Vector3();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, Vector3());83uint32_t rrp_polygon_index = region_E->value;84ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector3());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 face_area = Face3(rr_polygon.vertices[0], rr_polygon.vertices[rpp_index - 1], rr_polygon.vertices[rpp_index]).get_area();9394if (face_area == 0.0) {95continue;96}97polygon_area_map[accumulated_polygon_area] = rpp_index;98accumulated_polygon_area += face_area;99}100if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {101// All faces have no real surface / no area.102return Vector3();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, Vector3());109uint32_t rrp_face_index = polygon_E->value;110ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.vertices.size(), Vector3());111112const Face3 face(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);113114Vector3 face_random_position = face.get_random_point_inside();115return face_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 Face3 face(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);125126Vector3 face_random_position = face.get_random_point_inside();127return face_random_position;128}129}130131void NavMeshQueries3D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask3D &p_query_task, const Vector3 &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 NavMeshQueries3D::map_query_path(NavMap3D *map, const Ref<NavigationPathQueryParameters3D> &p_query_parameters, Ref<NavigationPathQueryResult3D> p_query_result, const Callable &p_callback) {148ERR_FAIL_NULL(map);149ERR_FAIL_COND(p_query_parameters.is_null());150ERR_FAIL_COND(p_query_result.is_null());151152using namespace NavigationDefaults3D;153154NavMeshQueries3D::NavMeshPathQueryTask3D 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 NavigationPathQueryParameters3D::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 NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {195query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;196} break;197case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {198query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;199} break;200case NavigationPathQueryParameters3D::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 = NavMeshPathQueryTask3D::TaskStatus::QUERY_STARTED;217218map->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 = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_DISPATCHED;230} else {231query_task.status = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_FAILED;232}233}234}235236void NavMeshQueries3D::_query_task_find_start_end_positions(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &p_map_iteration) {237real_t begin_d = FLT_MAX;238real_t end_d = FLT_MAX;239240const LocalVector<Ref<NavRegionIteration3D>> ®ions = p_map_iteration.region_iterations;241242for (const Ref<NavRegionIteration3D> ®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 face check the distance between the origin/destination.255for (uint32_t point_id = 2; point_id < p.vertices.size(); point_id++) {256const Face3 face(p.vertices[0], p.vertices[point_id - 1], p.vertices[point_id]);257258Vector3 point = face.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 = face.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 NavMeshQueries3D::_query_task_search_polygon_connections(NavMeshPathQueryTask3D &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 Vector3 &p_end_point) {279const NavBaseIteration3D *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();291292Vector3 new_entry = Geometry3D::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 NavMeshQueries3D::_query_task_build_path_corridor(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &p_map_iteration) {319const Vector3 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;322Vector3 begin_point = p_query_task.begin_position;323Vector3 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 NavBaseIteration3D *, LocalVector<LocalVector<Nav3D::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 NavBaseIteration3D *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++) {415Face3 f(end_poly->vertices[0], end_poly->vertices[point_id - 1], end_poly->vertices[point_id]);416Vector3 spoint = f.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++) {428Face3 f(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);429Vector3 spoint = f.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 = NavMeshPathQueryTask3D::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++) {490Face3 f(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);491Vector3 spoint = f.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 = NavMeshPathQueryTask3D::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 NavMeshQueries3D::query_task_map_iteration_get_path(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &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 = NavMeshPathQueryTask3D::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 = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;529return;530}531532_query_task_build_path_corridor(p_query_task, p_map_iteration);533534if (p_query_task.status == NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask3D::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 = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;580}581582float NavMeshQueries3D::_calculate_path_length(const LocalVector<Vector3> &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 Vector3 *path_ptr = p_path.ptr();593594float path_length = 0.0;595596for (uint32_t i = p_start_index; i < p_end_index; i++) {597const Vector3 &vertex1 = path_ptr[i];598const Vector3 &vertex2 = path_ptr[i + 1];599float edge_length = vertex1.distance_to(vertex2);600path_length += edge_length;601}602603return path_length;604}605606void NavMeshQueries3D::_query_task_process_path_result_limits(NavMeshPathQueryTask3D &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<Vector3> &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 Vector3 &start_pos = path[0];626627float accumulated_path_length = 0.0;628629Vector3 *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 Vector3 &vertex1 = path_ptrw[i];637Vector3 &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.643Vector3 intersect_positon, intersect_normal;644bool intersected = Geometry3D::segment_intersects_sphere(vertex2, vertex1, start_pos, max_radius, &intersect_positon, &intersect_normal);645if (intersected) {646edge_length = (intersect_positon - vertex1).length();647648path_ptrw[next_index] = intersect_positon;649path_max_size = next_index + 1;650path_max_reached = true;651}652}653654if (check_max_length && accumulated_path_length + edge_length > max_length) {655// Path point segment goes over max length, clip it.656edge_length = max_length - accumulated_path_length;657Vector3 edge_direction = vertex1.direction_to(vertex2);658659path_ptrw[next_index] = vertex1 + (edge_direction * edge_length);660path_max_size = next_index + 1;661662p_query_task.path_length = accumulated_path_length + edge_length;663path_max_reached = true;664}665666accumulated_path_length += edge_length;667668if (path_max_reached) {669break;670}671}672673p_query_task.path_length = accumulated_path_length;674675if (path_max_size < path.size()) {676p_query_task.path_points.resize(path_max_size);677678if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {679p_query_task.path_meta_point_types.resize(path_max_size);680}681682if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {683p_query_task.path_meta_point_rids.resize(path_max_size);684}685686if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {687p_query_task.path_meta_point_owners.resize(path_max_size);688}689}690}691692void NavMeshQueries3D::_query_task_simplified_path_points(NavMeshPathQueryTask3D &p_query_task) {693if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {694return;695}696697const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries3D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);698699uint32_t index_count = simplified_path_indices.size();700701{702Vector3 *points_ptr = p_query_task.path_points.ptr();703for (uint32_t i = 0; i < index_count; i++) {704points_ptr[i] = points_ptr[simplified_path_indices[i]];705}706p_query_task.path_points.resize(index_count);707}708709if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {710int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();711for (uint32_t i = 0; i < index_count; i++) {712types_ptr[i] = types_ptr[simplified_path_indices[i]];713}714p_query_task.path_meta_point_types.resize(index_count);715}716717if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {718RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();719for (uint32_t i = 0; i < index_count; i++) {720rids_ptr[i] = rids_ptr[simplified_path_indices[i]];721}722p_query_task.path_meta_point_rids.resize(index_count);723}724725if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {726int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();727for (uint32_t i = 0; i < index_count; i++) {728owners_ptr[i] = owners_ptr[simplified_path_indices[i]];729}730p_query_task.path_meta_point_owners.resize(index_count);731}732}733734void NavMeshQueries3D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask3D &p_query_task) {735Vector3 end_point = p_query_task.end_position;736const Polygon *end_poly = p_query_task.end_polygon;737Vector3 begin_point = p_query_task.begin_position;738const Polygon *begin_poly = p_query_task.begin_polygon;739uint32_t least_cost_id = p_query_task.least_cost_id;740LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;741Vector3 p_map_up = p_query_task.map_up;742743// Set the apex poly/point to the end point744NavigationPoly *apex_poly = &navigation_polys[least_cost_id];745746const Vector3 back_edge_closest_point = Geometry3D::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}754755Vector3 apex_point = end_point;756757NavigationPoly *left_poly = apex_poly;758Vector3 left_portal = apex_point;759NavigationPoly *right_poly = apex_poly;760Vector3 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.768Vector3 left = p->back_navigation_edge_pathway_start;769Vector3 right = p->back_navigation_edge_pathway_end;770if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(p_map_up) < 0) {771SWAP(left, right);772}773774bool skip = false;775if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(p_map_up) >= 0) {776//process777if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(p_map_up) > 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).dot(p_map_up) <= 0) {796//process797if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(p_map_up) < 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 NavMeshQueries3D::_query_task_post_process_edgecentered(NavMeshPathQueryTask3D &p_query_task) {830Vector3 end_point = p_query_task.end_position;831const Polygon *end_poly = p_query_task.end_polygon;832Vector3 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 points840int 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();845Vector3 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 NavMeshQueries3D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask3D &p_query_task) {859Vector3 end_point = p_query_task.end_position;860const Polygon *end_poly = p_query_task.end_polygon;861Vector3 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 points869int 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}878879Vector3 NavMeshQueries3D::map_iteration_get_closest_point_to_segment(const NavMapIteration3D &p_map_iteration, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {880bool use_collision = p_use_collision;881Vector3 closest_point;882real_t closest_point_distance = FLT_MAX;883884const LocalVector<Ref<NavRegionIteration3D>> ®ions = p_map_iteration.region_iterations;885for (const Ref<NavRegionIteration3D> ®ion : regions) {886for (const Polygon &polygon : region->get_navmesh_polygons()) {887// For each face check the distance to the segment.888for (uint32_t point_id = 2; point_id < polygon.vertices.size(); point_id += 1) {889const Face3 face(polygon.vertices[0], polygon.vertices[point_id - 1], polygon.vertices[point_id]);890Vector3 intersection_point;891if (face.intersects_segment(p_from, p_to, &intersection_point)) {892const real_t d = p_from.distance_to(intersection_point);893if (!use_collision) {894closest_point = intersection_point;895use_collision = true;896closest_point_distance = d;897} else if (closest_point_distance > d) {898closest_point = intersection_point;899closest_point_distance = d;900}901}902// If segment does not itersect face, check the distance from segment's endpoints.903else if (!use_collision) {904const Vector3 p_from_closest = face.get_closest_point_to(p_from);905const real_t d_p_from = p_from.distance_to(p_from_closest);906if (closest_point_distance > d_p_from) {907closest_point = p_from_closest;908closest_point_distance = d_p_from;909}910911const Vector3 p_to_closest = face.get_closest_point_to(p_to);912const real_t d_p_to = p_to.distance_to(p_to_closest);913if (closest_point_distance > d_p_to) {914closest_point = p_to_closest;915closest_point_distance = d_p_to;916}917}918}919// Finally, check for a case when shortest distance is between some point located on a face's edge and some point located on a line segment.920if (!use_collision) {921for (uint32_t point_id = 0; point_id < polygon.vertices.size(); point_id += 1) {922Vector3 a, b;923924Geometry3D::get_closest_points_between_segments(925p_from,926p_to,927polygon.vertices[point_id],928polygon.vertices[(point_id + 1) % polygon.vertices.size()],929a,930b);931932const real_t d = a.distance_to(b);933if (d < closest_point_distance) {934closest_point_distance = d;935closest_point = b;936}937}938}939}940}941942return closest_point;943}944945Vector3 NavMeshQueries3D::map_iteration_get_closest_point(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {946ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);947return cp.point;948}949950Vector3 NavMeshQueries3D::map_iteration_get_closest_point_normal(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {951ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);952return cp.normal;953}954955RID NavMeshQueries3D::map_iteration_get_closest_point_owner(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {956ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);957return cp.owner;958}959960ClosestPointQueryResult NavMeshQueries3D::map_iteration_get_closest_point_info(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {961ClosestPointQueryResult result;962real_t closest_point_distance_squared = FLT_MAX;963964const LocalVector<Ref<NavRegionIteration3D>> ®ions = p_map_iteration.region_iterations;965for (const Ref<NavRegionIteration3D> ®ion : regions) {966for (const Polygon &polygon : region->get_navmesh_polygons()) {967Vector3 plane_normal = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);968Vector3 closest_on_polygon;969real_t closest = FLT_MAX;970bool inside = true;971Vector3 previous = polygon.vertices[polygon.vertices.size() - 1];972for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {973Vector3 edge = polygon.vertices[point_id] - previous;974Vector3 to_point = p_point - previous;975Vector3 edge_to_point_pormal = edge.cross(to_point);976bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;977// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.978if (!clockwise) {979inside = false;980real_t point_projected_on_edge = edge.dot(to_point);981real_t edge_square = edge.length_squared();982983if (point_projected_on_edge > edge_square) {984real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);985if (distance < closest) {986closest_on_polygon = polygon.vertices[point_id];987closest = distance;988}989} else if (point_projected_on_edge < 0.f) {990real_t distance = previous.distance_squared_to(p_point);991if (distance < closest) {992closest_on_polygon = previous;993closest = distance;994}995} else {996// If we project on this edge, this will be the closest point.997real_t percent = point_projected_on_edge / edge_square;998closest_on_polygon = previous + percent * edge;999break;1000}1001}1002previous = polygon.vertices[point_id];1003}10041005if (inside) {1006Vector3 plane_normalized = plane_normal.normalized();1007real_t distance = plane_normalized.dot(p_point - polygon.vertices[0]);1008real_t distance_squared = distance * distance;1009if (distance_squared < closest_point_distance_squared) {1010closest_point_distance_squared = distance_squared;1011result.point = p_point - plane_normalized * distance;1012result.normal = plane_normal;1013result.owner = polygon.owner->get_self();10141015if (Math::is_zero_approx(distance)) {1016break;1017}1018}1019} else {1020real_t distance = closest_on_polygon.distance_squared_to(p_point);1021if (distance < closest_point_distance_squared) {1022closest_point_distance_squared = distance;1023result.point = closest_on_polygon;1024result.normal = plane_normal;1025result.owner = polygon.owner->get_self();1026}1027}1028}1029}10301031return result;1032}10331034Vector3 NavMeshQueries3D::map_iteration_get_random_point(const NavMapIteration3D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {1035if (p_map_iteration.region_iterations.is_empty()) {1036return Vector3();1037}10381039LocalVector<uint32_t> accessible_regions;1040accessible_regions.reserve(p_map_iteration.region_iterations.size());10411042for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {1043const Ref<NavRegionIteration3D> ®ion = p_map_iteration.region_iterations[i];1044if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {1045continue;1046}1047accessible_regions.push_back(i);1048}10491050if (accessible_regions.is_empty()) {1051// All existing region polygons are disabled.1052return Vector3();1053}10541055if (p_uniformly) {1056real_t accumulated_region_surface_area = 0;1057RBMap<real_t, uint32_t> accessible_regions_area_map;10581059for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {1060const Ref<NavRegionIteration3D> ®ion = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];10611062real_t region_surface_area = region->surface_area;10631064if (region_surface_area == 0.0f) {1065continue;1066}10671068accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;1069accumulated_region_surface_area += region_surface_area;1070}1071if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {1072// All faces have no real surface / no area.1073return Vector3();1074}10751076real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);10771078RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);1079ERR_FAIL_COND_V(!E, Vector3());1080uint32_t random_region_index = E->value;1081ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector3());10821083const Ref<NavRegionIteration3D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10841085return NavMeshQueries3D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);10861087} else {1088uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);10891090const Ref<NavRegionIteration3D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];10911092return NavMeshQueries3D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);1093}1094}10951096Vector3 NavMeshQueries3D::polygons_get_closest_point_to_segment(const LocalVector<Polygon> &p_polygons, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {1097bool use_collision = p_use_collision;1098Vector3 closest_point;1099real_t closest_point_distance = FLT_MAX;11001101for (const Polygon &polygon : p_polygons) {1102// For each face check the distance to the segment.1103for (uint32_t point_id = 2; point_id < polygon.vertices.size(); point_id += 1) {1104const Face3 face(polygon.vertices[0], polygon.vertices[point_id - 1], polygon.vertices[point_id]);1105Vector3 intersection_point;1106if (face.intersects_segment(p_from, p_to, &intersection_point)) {1107const real_t d = p_from.distance_to(intersection_point);1108if (!use_collision) {1109closest_point = intersection_point;1110use_collision = true;1111closest_point_distance = d;1112} else if (closest_point_distance > d) {1113closest_point = intersection_point;1114closest_point_distance = d;1115}1116}1117// If segment does not itersect face, check the distance from segment's endpoints.1118else if (!use_collision) {1119const Vector3 p_from_closest = face.get_closest_point_to(p_from);1120const real_t d_p_from = p_from.distance_to(p_from_closest);1121if (closest_point_distance > d_p_from) {1122closest_point = p_from_closest;1123closest_point_distance = d_p_from;1124}11251126const Vector3 p_to_closest = face.get_closest_point_to(p_to);1127const real_t d_p_to = p_to.distance_to(p_to_closest);1128if (closest_point_distance > d_p_to) {1129closest_point = p_to_closest;1130closest_point_distance = d_p_to;1131}1132}1133}1134// Finally, check for a case when shortest distance is between some point located on a face's edge and some point located on a line segment.1135if (!use_collision) {1136for (uint32_t point_id = 0; point_id < polygon.vertices.size(); point_id += 1) {1137Vector3 a, b;11381139Geometry3D::get_closest_points_between_segments(1140p_from,1141p_to,1142polygon.vertices[point_id],1143polygon.vertices[(point_id + 1) % polygon.vertices.size()],1144a,1145b);11461147const real_t d = a.distance_to(b);1148if (d < closest_point_distance) {1149closest_point_distance = d;1150closest_point = b;1151}1152}1153}1154}11551156return closest_point;1157}11581159Vector3 NavMeshQueries3D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {1160ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1161return cp.point;1162}11631164Vector3 NavMeshQueries3D::polygons_get_closest_point_normal(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {1165ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1166return cp.normal;1167}11681169ClosestPointQueryResult NavMeshQueries3D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {1170ClosestPointQueryResult result;1171real_t closest_point_distance_squared = FLT_MAX;11721173for (const Polygon &polygon : p_polygons) {1174Vector3 plane_normal = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);1175Vector3 closest_on_polygon;1176real_t closest = FLT_MAX;1177bool inside = true;1178Vector3 previous = polygon.vertices[polygon.vertices.size() - 1];1179for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {1180Vector3 edge = polygon.vertices[point_id] - previous;1181Vector3 to_point = p_point - previous;1182Vector3 edge_to_point_pormal = edge.cross(to_point);1183bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;1184// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.1185if (!clockwise) {1186inside = false;1187real_t point_projected_on_edge = edge.dot(to_point);1188real_t edge_square = edge.length_squared();11891190if (point_projected_on_edge > edge_square) {1191real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);1192if (distance < closest) {1193closest_on_polygon = polygon.vertices[point_id];1194closest = distance;1195}1196} else if (point_projected_on_edge < 0.f) {1197real_t distance = previous.distance_squared_to(p_point);1198if (distance < closest) {1199closest_on_polygon = previous;1200closest = distance;1201}1202} else {1203// If we project on this edge, this will be the closest point.1204real_t percent = point_projected_on_edge / edge_square;1205closest_on_polygon = previous + percent * edge;1206break;1207}1208}1209previous = polygon.vertices[point_id];1210}12111212if (inside) {1213Vector3 plane_normalized = plane_normal.normalized();1214real_t distance = plane_normalized.dot(p_point - polygon.vertices[0]);1215real_t distance_squared = distance * distance;1216if (distance_squared < closest_point_distance_squared) {1217closest_point_distance_squared = distance_squared;1218result.point = p_point - plane_normalized * distance;1219result.normal = plane_normal;1220result.owner = polygon.owner->get_self();12211222if (Math::is_zero_approx(distance)) {1223break;1224}1225}1226} else {1227real_t distance = closest_on_polygon.distance_squared_to(p_point);1228if (distance < closest_point_distance_squared) {1229closest_point_distance_squared = distance;1230result.point = closest_on_polygon;1231result.normal = plane_normal;1232result.owner = polygon.owner->get_self();1233}1234}1235}12361237return result;1238}12391240RID NavMeshQueries3D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {1241ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);1242return cp.owner;1243}12441245void NavMeshQueries3D::_query_task_clip_path(NavMeshPathQueryTask3D &p_query_task, const NavigationPoly *from_poly, const Vector3 &p_to_point, const NavigationPoly *p_to_poly) {1246Vector3 from = p_query_task.path_points[p_query_task.path_points.size() - 1];1247const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;1248const Vector3 p_map_up = p_query_task.map_up;12491250if (from.is_equal_approx(p_to_point)) {1251return;1252}12531254Plane cut_plane;1255cut_plane.normal = (from - p_to_point).cross(p_map_up);1256if (cut_plane.normal == Vector3()) {1257return;1258}1259cut_plane.normal.normalize();1260cut_plane.d = cut_plane.normal.dot(from);12611262while (from_poly != p_to_poly) {1263Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;1264Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;12651266ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);1267from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];12681269if (!pathway_start.is_equal_approx(pathway_end)) {1270Vector3 inters;1271if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {1272if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {1273_query_task_push_back_point_with_metadata(p_query_task, inters, from_poly->poly);1274}1275}1276}1277}1278}12791280bool NavMeshQueries3D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask3D &p_query_task, const NavBaseIteration3D *p_owner) {1281ERR_FAIL_NULL_V(p_owner, false);12821283bool owner_usable = true;12841285if (!p_owner->get_enabled()) {1286owner_usable = false;1287return owner_usable;1288}12891290if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {1291// Not usable. No matching bit between task filter bitmask and owner bitmask.1292owner_usable = false;1293return owner_usable;1294}12951296if (p_query_task.exclude_regions || p_query_task.include_regions) {1297switch (p_owner->get_type()) {1298case NavigationEnums3D::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {1299if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {1300// Not usable. Exclude region filter is active and this region is excluded.1301owner_usable = false;1302} else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {1303// Not usable. Include region filter is active and this region is not included.1304owner_usable = false;1305}1306} break;1307case NavigationEnums3D::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {1308const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();1309if (link_polygons.size() != 2) {1310// Not usable. Whatever this is, it is not a valid connected link.1311owner_usable = false;1312} else {1313const RID link_start_region = link_polygons[0].owner->get_self();1314const RID link_end_region = link_polygons[1].owner->get_self();1315if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {1316// Not usable. Exclude region filter is active and at least one region of the link is excluded.1317owner_usable = false;1318}1319if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {1320// Not usable. Include region filter is active and not both regions of the links are included.1321owner_usable = false;1322}1323}1324} break;1325}1326}13271328return owner_usable;1329}13301331LocalVector<uint32_t> NavMeshQueries3D::get_simplified_path_indices(const LocalVector<Vector3> &p_path, real_t p_epsilon) {1332p_epsilon = MAX(0.0, p_epsilon);1333real_t squared_epsilon = p_epsilon * p_epsilon;13341335LocalVector<uint32_t> simplified_path_indices;1336simplified_path_indices.reserve(p_path.size());1337simplified_path_indices.push_back(0);1338simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);1339simplified_path_indices.push_back(p_path.size() - 1);13401341return simplified_path_indices;1342}13431344void NavMeshQueries3D::simplify_path_segment(int p_start_inx, int p_end_inx, const LocalVector<Vector3> &p_points, real_t p_epsilon, LocalVector<uint32_t> &r_simplified_path_indices) {1345const Vector3 path_segment_a = p_points[p_start_inx];1346const Vector3 path_segment_b = p_points[p_end_inx];13471348real_t point_max_distance = 0.0;1349int point_max_index = 0;13501351for (int i = p_start_inx; i < p_end_inx; i++) {1352const Vector3 &checked_point = p_points[i];13531354const Vector3 closest_point = Geometry3D::get_closest_point_to_segment(checked_point, path_segment_a, path_segment_b);1355real_t distance_squared = closest_point.distance_squared_to(checked_point);13561357if (distance_squared > point_max_distance) {1358point_max_index = i;1359point_max_distance = distance_squared;1360}1361}13621363if (point_max_distance > p_epsilon) {1364simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);1365r_simplified_path_indices.push_back(point_max_index);1366simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);1367}1368}136913701371