nav_mesh_queries_3d.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /**************************************************************************/
  2. /* nav_mesh_queries_3d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef _3D_DISABLED
  31. #include "nav_mesh_queries_3d.h"
  32. #include "../nav_base.h"
  33. #include "../nav_map.h"
  34. #include "nav_region_iteration_3d.h"
  35. #include "core/math/geometry_3d.h"
  36. #include "servers/navigation/navigation_utilities.h"
  37. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  38. bool NavMeshQueries3D::emit_callback(const Callable &p_callback) {
  39. ERR_FAIL_COND_V(!p_callback.is_valid(), false);
  40. Callable::CallError ce;
  41. Variant result;
  42. p_callback.callp(nullptr, 0, result, ce);
  43. return ce.error == Callable::CallError::CALL_OK;
  44. }
  45. Vector3 NavMeshQueries3D::polygons_get_random_point(const LocalVector<gd::Polygon> &p_polygons, uint32_t p_navigation_layers, bool p_uniformly) {
  46. const LocalVector<gd::Polygon> &region_polygons = p_polygons;
  47. if (region_polygons.is_empty()) {
  48. return Vector3();
  49. }
  50. if (p_uniformly) {
  51. real_t accumulated_area = 0;
  52. RBMap<real_t, uint32_t> region_area_map;
  53. for (uint32_t rp_index = 0; rp_index < region_polygons.size(); rp_index++) {
  54. const gd::Polygon &region_polygon = region_polygons[rp_index];
  55. real_t polyon_area = region_polygon.surface_area;
  56. if (polyon_area == 0.0) {
  57. continue;
  58. }
  59. region_area_map[accumulated_area] = rp_index;
  60. accumulated_area += polyon_area;
  61. }
  62. if (region_area_map.is_empty() || accumulated_area == 0) {
  63. // All polygons have no real surface / no area.
  64. return Vector3();
  65. }
  66. real_t region_area_map_pos = Math::random(real_t(0), accumulated_area);
  67. RBMap<real_t, uint32_t>::Iterator region_E = region_area_map.find_closest(region_area_map_pos);
  68. ERR_FAIL_COND_V(!region_E, Vector3());
  69. uint32_t rrp_polygon_index = region_E->value;
  70. ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector3());
  71. const gd::Polygon &rr_polygon = region_polygons[rrp_polygon_index];
  72. real_t accumulated_polygon_area = 0;
  73. RBMap<real_t, uint32_t> polygon_area_map;
  74. for (uint32_t rpp_index = 2; rpp_index < rr_polygon.points.size(); rpp_index++) {
  75. real_t face_area = Face3(rr_polygon.points[0].pos, rr_polygon.points[rpp_index - 1].pos, rr_polygon.points[rpp_index].pos).get_area();
  76. if (face_area == 0.0) {
  77. continue;
  78. }
  79. polygon_area_map[accumulated_polygon_area] = rpp_index;
  80. accumulated_polygon_area += face_area;
  81. }
  82. if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {
  83. // All faces have no real surface / no area.
  84. return Vector3();
  85. }
  86. real_t polygon_area_map_pos = Math::random(real_t(0), accumulated_polygon_area);
  87. RBMap<real_t, uint32_t>::Iterator polygon_E = polygon_area_map.find_closest(polygon_area_map_pos);
  88. ERR_FAIL_COND_V(!polygon_E, Vector3());
  89. uint32_t rrp_face_index = polygon_E->value;
  90. ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.points.size(), Vector3());
  91. const Face3 face(rr_polygon.points[0].pos, rr_polygon.points[rrp_face_index - 1].pos, rr_polygon.points[rrp_face_index].pos);
  92. Vector3 face_random_position = face.get_random_point_inside();
  93. return face_random_position;
  94. } else {
  95. uint32_t rrp_polygon_index = Math::random(int(0), region_polygons.size() - 1);
  96. const gd::Polygon &rr_polygon = region_polygons[rrp_polygon_index];
  97. uint32_t rrp_face_index = Math::random(int(2), rr_polygon.points.size() - 1);
  98. const Face3 face(rr_polygon.points[0].pos, rr_polygon.points[rrp_face_index - 1].pos, rr_polygon.points[rrp_face_index].pos);
  99. Vector3 face_random_position = face.get_random_point_inside();
  100. return face_random_position;
  101. }
  102. }
  103. void NavMeshQueries3D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask3D &p_query_task, const Vector3 &p_point, const gd::Polygon *p_point_polygon) {
  104. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  105. p_query_task.path_meta_point_types.push_back(p_point_polygon->owner->get_type());
  106. }
  107. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  108. p_query_task.path_meta_point_rids.push_back(p_point_polygon->owner->get_self());
  109. }
  110. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  111. p_query_task.path_meta_point_owners.push_back(p_point_polygon->owner->get_owner_id());
  112. }
  113. p_query_task.path_points.push_back(p_point);
  114. }
  115. void NavMeshQueries3D::map_query_path(NavMap *map, const Ref<NavigationPathQueryParameters3D> &p_query_parameters, Ref<NavigationPathQueryResult3D> p_query_result, const Callable &p_callback) {
  116. ERR_FAIL_NULL(map);
  117. ERR_FAIL_COND(p_query_parameters.is_null());
  118. ERR_FAIL_COND(p_query_result.is_null());
  119. using namespace NavigationUtilities;
  120. NavMeshQueries3D::NavMeshPathQueryTask3D query_task;
  121. query_task.start_position = p_query_parameters->get_start_position();
  122. query_task.target_position = p_query_parameters->get_target_position();
  123. query_task.navigation_layers = p_query_parameters->get_navigation_layers();
  124. query_task.callback = p_callback;
  125. switch (p_query_parameters->get_pathfinding_algorithm()) {
  126. case NavigationPathQueryParameters3D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR: {
  127. query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
  128. } break;
  129. default: {
  130. WARN_PRINT("No match for used PathfindingAlgorithm - fallback to default");
  131. query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
  132. } break;
  133. }
  134. switch (p_query_parameters->get_path_postprocessing()) {
  135. case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
  136. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
  137. } break;
  138. case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
  139. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;
  140. } break;
  141. case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_NONE: {
  142. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_NONE;
  143. } break;
  144. default: {
  145. WARN_PRINT("No match for used PathPostProcessing - fallback to default");
  146. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
  147. } break;
  148. }
  149. query_task.metadata_flags = (int64_t)p_query_parameters->get_metadata_flags();
  150. query_task.simplify_path = p_query_parameters->get_simplify_path();
  151. query_task.simplify_epsilon = p_query_parameters->get_simplify_epsilon();
  152. query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_STARTED;
  153. map->query_path(query_task);
  154. p_query_result->set_data(
  155. query_task.path_points,
  156. query_task.path_meta_point_types,
  157. query_task.path_meta_point_rids,
  158. query_task.path_meta_point_owners);
  159. if (query_task.callback.is_valid()) {
  160. if (emit_callback(query_task.callback)) {
  161. query_task.status = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_DISPATCHED;
  162. } else {
  163. query_task.status = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_FAILED;
  164. }
  165. }
  166. }
  167. void NavMeshQueries3D::_query_task_find_start_end_positions(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration &p_map_iteration) {
  168. real_t begin_d = FLT_MAX;
  169. real_t end_d = FLT_MAX;
  170. const LocalVector<NavRegionIteration> &regions = p_map_iteration.region_iterations;
  171. for (const NavRegionIteration &region : regions) {
  172. if (!region.get_enabled()) {
  173. continue;
  174. }
  175. // Find the initial poly and the end poly on this map.
  176. for (const gd::Polygon &p : region.get_navmesh_polygons()) {
  177. // Only consider the polygon if it in a region with compatible layers.
  178. if ((p_query_task.navigation_layers & p.owner->get_navigation_layers()) == 0) {
  179. continue;
  180. }
  181. // For each face check the distance between the origin/destination.
  182. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  183. const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  184. Vector3 point = face.get_closest_point_to(p_query_task.start_position);
  185. real_t distance_to_point = point.distance_to(p_query_task.start_position);
  186. if (distance_to_point < begin_d) {
  187. begin_d = distance_to_point;
  188. p_query_task.begin_polygon = &p;
  189. p_query_task.begin_position = point;
  190. }
  191. point = face.get_closest_point_to(p_query_task.target_position);
  192. distance_to_point = point.distance_to(p_query_task.target_position);
  193. if (distance_to_point < end_d) {
  194. end_d = distance_to_point;
  195. p_query_task.end_polygon = &p;
  196. p_query_task.end_position = point;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. void NavMeshQueries3D::_query_task_build_path_corridor(NavMeshPathQueryTask3D &p_query_task) {
  203. const Vector3 p_target_position = p_query_task.target_position;
  204. const uint32_t p_navigation_layers = p_query_task.navigation_layers;
  205. const gd::Polygon *begin_poly = p_query_task.begin_polygon;
  206. const gd::Polygon *end_poly = p_query_task.end_polygon;
  207. Vector3 begin_point = p_query_task.begin_position;
  208. Vector3 end_point = p_query_task.end_position;
  209. // Heap of polygons to travel next.
  210. gd::Heap<gd::NavigationPoly *, gd::NavPolyTravelCostGreaterThan, gd::NavPolyHeapIndexer>
  211. &traversable_polys = p_query_task.path_query_slot->traversable_polys;
  212. traversable_polys.clear();
  213. LocalVector<gd::NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  214. for (gd::NavigationPoly &polygon : navigation_polys) {
  215. polygon.reset();
  216. }
  217. // Initialize the matching navigation polygon.
  218. gd::NavigationPoly &begin_navigation_poly = navigation_polys[begin_poly->id];
  219. begin_navigation_poly.poly = begin_poly;
  220. begin_navigation_poly.entry = begin_point;
  221. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  222. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  223. begin_navigation_poly.traveled_distance = 0.f;
  224. // This is an implementation of the A* algorithm.
  225. uint32_t least_cost_id = begin_poly->id;
  226. bool found_route = false;
  227. const gd::Polygon *reachable_end = nullptr;
  228. real_t distance_to_reachable_end = FLT_MAX;
  229. bool is_reachable = true;
  230. real_t poly_enter_cost = 0.0;
  231. while (true) {
  232. const gd::NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
  233. real_t poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost();
  234. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  235. for (const gd::Edge &edge : least_cost_poly.poly->edges) {
  236. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  237. for (uint32_t connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  238. const gd::Edge::Connection &connection = edge.connections[connection_index];
  239. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  240. const NavBaseIteration *owner = connection.polygon->owner;
  241. if ((p_navigation_layers & owner->get_navigation_layers()) != 0) {
  242. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  243. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly.entry, pathway);
  244. const real_t new_traveled_distance = least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost + poly_enter_cost + least_cost_poly.traveled_distance;
  245. // Check if the neighbor polygon has already been processed.
  246. gd::NavigationPoly &neighbor_poly = navigation_polys[connection.polygon->id];
  247. if (new_traveled_distance < neighbor_poly.traveled_distance) {
  248. // Add the polygon to the heap of polygons to traverse next.
  249. neighbor_poly.back_navigation_poly_id = least_cost_id;
  250. neighbor_poly.back_navigation_edge = connection.edge;
  251. neighbor_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  252. neighbor_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  253. neighbor_poly.traveled_distance = new_traveled_distance;
  254. neighbor_poly.distance_to_destination =
  255. new_entry.distance_to(end_point) *
  256. owner->get_travel_cost();
  257. neighbor_poly.entry = new_entry;
  258. if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {
  259. traversable_polys.shift(neighbor_poly.traversable_poly_index);
  260. } else {
  261. neighbor_poly.poly = connection.polygon;
  262. traversable_polys.push(&neighbor_poly);
  263. }
  264. }
  265. }
  266. }
  267. }
  268. poly_enter_cost = 0;
  269. // When the heap of traversable polygons is empty at this point it means the end polygon is
  270. // unreachable.
  271. if (traversable_polys.is_empty()) {
  272. // Thus use the further reachable polygon
  273. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  274. is_reachable = false;
  275. if (reachable_end == nullptr) {
  276. // The path is not found and there is not a way out.
  277. break;
  278. }
  279. // Set as end point the furthest reachable point.
  280. end_poly = reachable_end;
  281. real_t end_d = FLT_MAX;
  282. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  283. Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  284. Vector3 spoint = f.get_closest_point_to(p_target_position);
  285. real_t dpoint = spoint.distance_squared_to(p_target_position);
  286. if (dpoint < end_d) {
  287. end_point = spoint;
  288. end_d = dpoint;
  289. }
  290. }
  291. // Search all faces of start polygon as well.
  292. bool closest_point_on_start_poly = false;
  293. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  294. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  295. Vector3 spoint = f.get_closest_point_to(p_target_position);
  296. real_t dpoint = spoint.distance_squared_to(p_target_position);
  297. if (dpoint < end_d) {
  298. end_point = spoint;
  299. end_d = dpoint;
  300. closest_point_on_start_poly = true;
  301. }
  302. }
  303. if (closest_point_on_start_poly) {
  304. // No point to run PostProcessing when start and end convex polygon is the same.
  305. p_query_task.path_clear();
  306. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  307. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  308. p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
  309. return;
  310. }
  311. for (gd::NavigationPoly &nav_poly : navigation_polys) {
  312. nav_poly.poly = nullptr;
  313. nav_poly.traveled_distance = FLT_MAX;
  314. }
  315. navigation_polys[begin_poly->id].poly = begin_poly;
  316. navigation_polys[begin_poly->id].traveled_distance = 0;
  317. least_cost_id = begin_poly->id;
  318. reachable_end = nullptr;
  319. } else {
  320. // Pop the polygon with the lowest travel cost from the heap of traversable polygons.
  321. least_cost_id = traversable_polys.pop()->poly->id;
  322. // Store the farthest reachable end polygon in case our goal is not reachable.
  323. if (is_reachable) {
  324. real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);
  325. if (distance_to_reachable_end > distance) {
  326. distance_to_reachable_end = distance;
  327. reachable_end = navigation_polys[least_cost_id].poly;
  328. }
  329. }
  330. // Check if we reached the end
  331. if (navigation_polys[least_cost_id].poly == end_poly) {
  332. found_route = true;
  333. break;
  334. }
  335. if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {
  336. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  337. }
  338. }
  339. }
  340. // We did not find a route but we have both a start polygon and an end polygon at this point.
  341. // 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.
  342. if (!found_route) {
  343. real_t end_d = FLT_MAX;
  344. // Search all faces of the start polygon for the closest point to our target position.
  345. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  346. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  347. Vector3 spoint = f.get_closest_point_to(p_target_position);
  348. real_t dpoint = spoint.distance_squared_to(p_target_position);
  349. if (dpoint < end_d) {
  350. end_point = spoint;
  351. end_d = dpoint;
  352. }
  353. }
  354. p_query_task.path_clear();
  355. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  356. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  357. p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
  358. } else {
  359. p_query_task.end_position = end_point;
  360. p_query_task.end_polygon = end_poly;
  361. p_query_task.begin_position = begin_point;
  362. p_query_task.begin_polygon = begin_poly;
  363. p_query_task.least_cost_id = least_cost_id;
  364. }
  365. }
  366. void NavMeshQueries3D::query_task_map_iteration_get_path(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration &p_map_iteration) {
  367. p_query_task.path_clear();
  368. _query_task_find_start_end_positions(p_query_task, p_map_iteration);
  369. // Check for trivial cases.
  370. if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {
  371. p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
  372. return;
  373. }
  374. if (p_query_task.begin_polygon == p_query_task.end_polygon) {
  375. p_query_task.path_clear();
  376. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);
  377. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);
  378. p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
  379. return;
  380. }
  381. _query_task_build_path_corridor(p_query_task);
  382. if (p_query_task.status == NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask3D::TaskStatus::QUERY_FAILED) {
  383. return;
  384. }
  385. // Post-Process path.
  386. switch (p_query_task.path_postprocessing) {
  387. case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
  388. _query_task_post_process_corridorfunnel(p_query_task);
  389. } break;
  390. case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
  391. _query_task_post_process_edgecentered(p_query_task);
  392. } break;
  393. case PathPostProcessing::PATH_POSTPROCESSING_NONE: {
  394. _query_task_post_process_nopostprocessing(p_query_task);
  395. } break;
  396. default: {
  397. WARN_PRINT("No match for used PathPostProcessing - fallback to default");
  398. _query_task_post_process_corridorfunnel(p_query_task);
  399. } break;
  400. }
  401. p_query_task.path_reverse();
  402. if (p_query_task.simplify_path) {
  403. _query_task_simplified_path_points(p_query_task);
  404. }
  405. #ifdef DEBUG_ENABLED
  406. // Ensure post conditions as path meta arrays if used MUST match in array size with the path points.
  407. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  408. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());
  409. }
  410. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  411. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());
  412. }
  413. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  414. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());
  415. }
  416. #endif // DEBUG_ENABLED
  417. p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
  418. }
  419. void NavMeshQueries3D::_query_task_simplified_path_points(NavMeshPathQueryTask3D &p_query_task) {
  420. if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {
  421. return;
  422. }
  423. const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries3D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);
  424. uint32_t index_count = simplified_path_indices.size();
  425. {
  426. Vector3 *points_ptr = p_query_task.path_points.ptr();
  427. for (uint32_t i = 0; i < index_count; i++) {
  428. points_ptr[i] = points_ptr[simplified_path_indices[i]];
  429. }
  430. p_query_task.path_points.resize(index_count);
  431. }
  432. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  433. int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();
  434. for (uint32_t i = 0; i < index_count; i++) {
  435. types_ptr[i] = types_ptr[simplified_path_indices[i]];
  436. }
  437. p_query_task.path_meta_point_types.resize(index_count);
  438. }
  439. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  440. RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();
  441. for (uint32_t i = 0; i < index_count; i++) {
  442. rids_ptr[i] = rids_ptr[simplified_path_indices[i]];
  443. }
  444. p_query_task.path_meta_point_rids.resize(index_count);
  445. }
  446. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  447. int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();
  448. for (uint32_t i = 0; i < index_count; i++) {
  449. owners_ptr[i] = owners_ptr[simplified_path_indices[i]];
  450. }
  451. p_query_task.path_meta_point_owners.resize(index_count);
  452. }
  453. }
  454. void NavMeshQueries3D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask3D &p_query_task) {
  455. Vector3 end_point = p_query_task.end_position;
  456. const gd::Polygon *end_poly = p_query_task.end_polygon;
  457. Vector3 begin_point = p_query_task.begin_position;
  458. const gd::Polygon *begin_poly = p_query_task.begin_polygon;
  459. uint32_t least_cost_id = p_query_task.least_cost_id;
  460. LocalVector<gd::NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  461. Vector3 p_map_up = p_query_task.map_up;
  462. // Set the apex poly/point to the end point
  463. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  464. Vector3 back_pathway[2] = { apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end };
  465. const Vector3 back_edge_closest_point = Geometry3D::get_closest_point_to_segment(end_point, back_pathway);
  466. if (end_point.is_equal_approx(back_edge_closest_point)) {
  467. // The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
  468. // At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
  469. if (apex_poly->back_navigation_poly_id != -1) {
  470. apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
  471. }
  472. }
  473. Vector3 apex_point = end_point;
  474. gd::NavigationPoly *left_poly = apex_poly;
  475. Vector3 left_portal = apex_point;
  476. gd::NavigationPoly *right_poly = apex_poly;
  477. Vector3 right_portal = apex_point;
  478. gd::NavigationPoly *p = apex_poly;
  479. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  480. while (p) {
  481. // Set left and right points of the pathway between polygons.
  482. Vector3 left = p->back_navigation_edge_pathway_start;
  483. Vector3 right = p->back_navigation_edge_pathway_end;
  484. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(p_map_up) < 0) {
  485. SWAP(left, right);
  486. }
  487. bool skip = false;
  488. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(p_map_up) >= 0) {
  489. //process
  490. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(p_map_up) > 0) {
  491. left_poly = p;
  492. left_portal = left;
  493. } else {
  494. _query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);
  495. apex_point = right_portal;
  496. p = right_poly;
  497. left_poly = p;
  498. apex_poly = p;
  499. left_portal = apex_point;
  500. right_portal = apex_point;
  501. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  502. skip = true;
  503. }
  504. }
  505. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(p_map_up) <= 0) {
  506. //process
  507. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(p_map_up) < 0) {
  508. right_poly = p;
  509. right_portal = right;
  510. } else {
  511. _query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);
  512. apex_point = left_portal;
  513. p = left_poly;
  514. right_poly = p;
  515. apex_poly = p;
  516. right_portal = apex_point;
  517. left_portal = apex_point;
  518. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  519. }
  520. }
  521. // Go to the previous polygon.
  522. if (p->back_navigation_poly_id != -1) {
  523. p = &navigation_polys[p->back_navigation_poly_id];
  524. } else {
  525. // The end
  526. p = nullptr;
  527. }
  528. }
  529. // If the last point is not the begin point, add it to the list.
  530. if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {
  531. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  532. }
  533. }
  534. void NavMeshQueries3D::_query_task_post_process_edgecentered(NavMeshPathQueryTask3D &p_query_task) {
  535. Vector3 end_point = p_query_task.end_position;
  536. const gd::Polygon *end_poly = p_query_task.end_polygon;
  537. Vector3 begin_point = p_query_task.begin_position;
  538. const gd::Polygon *begin_poly = p_query_task.begin_polygon;
  539. uint32_t least_cost_id = p_query_task.least_cost_id;
  540. LocalVector<gd::NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  541. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  542. // Add mid points
  543. int np_id = least_cost_id;
  544. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  545. if (navigation_polys[np_id].back_navigation_edge != -1) {
  546. int prev = navigation_polys[np_id].back_navigation_edge;
  547. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  548. Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  549. _query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);
  550. } else {
  551. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  552. }
  553. np_id = navigation_polys[np_id].back_navigation_poly_id;
  554. }
  555. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  556. }
  557. void NavMeshQueries3D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask3D &p_query_task) {
  558. Vector3 end_point = p_query_task.end_position;
  559. const gd::Polygon *end_poly = p_query_task.end_polygon;
  560. Vector3 begin_point = p_query_task.begin_position;
  561. const gd::Polygon *begin_poly = p_query_task.begin_polygon;
  562. uint32_t least_cost_id = p_query_task.least_cost_id;
  563. LocalVector<gd::NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  564. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  565. // Add mid points
  566. int np_id = least_cost_id;
  567. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  568. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  569. np_id = navigation_polys[np_id].back_navigation_poly_id;
  570. }
  571. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  572. }
  573. Vector3 NavMeshQueries3D::map_iteration_get_closest_point_to_segment(const NavMapIteration &p_map_iteration, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {
  574. bool use_collision = p_use_collision;
  575. Vector3 closest_point;
  576. real_t closest_point_distance = FLT_MAX;
  577. const LocalVector<NavRegionIteration> &regions = p_map_iteration.region_iterations;
  578. for (const NavRegionIteration &region : regions) {
  579. for (const gd::Polygon &polygon : region.get_navmesh_polygons()) {
  580. // For each face check the distance to the segment.
  581. for (size_t point_id = 2; point_id < polygon.points.size(); point_id += 1) {
  582. const Face3 face(polygon.points[0].pos, polygon.points[point_id - 1].pos, polygon.points[point_id].pos);
  583. Vector3 intersection_point;
  584. if (face.intersects_segment(p_from, p_to, &intersection_point)) {
  585. const real_t d = p_from.distance_to(intersection_point);
  586. if (!use_collision) {
  587. closest_point = intersection_point;
  588. use_collision = true;
  589. closest_point_distance = d;
  590. } else if (closest_point_distance > d) {
  591. closest_point = intersection_point;
  592. closest_point_distance = d;
  593. }
  594. }
  595. // If segment does not itersect face, check the distance from segment's endpoints.
  596. else if (!use_collision) {
  597. const Vector3 p_from_closest = face.get_closest_point_to(p_from);
  598. const real_t d_p_from = p_from.distance_to(p_from_closest);
  599. if (closest_point_distance > d_p_from) {
  600. closest_point = p_from_closest;
  601. closest_point_distance = d_p_from;
  602. }
  603. const Vector3 p_to_closest = face.get_closest_point_to(p_to);
  604. const real_t d_p_to = p_to.distance_to(p_to_closest);
  605. if (closest_point_distance > d_p_to) {
  606. closest_point = p_to_closest;
  607. closest_point_distance = d_p_to;
  608. }
  609. }
  610. }
  611. // 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.
  612. if (!use_collision) {
  613. for (size_t point_id = 0; point_id < polygon.points.size(); point_id += 1) {
  614. Vector3 a, b;
  615. Geometry3D::get_closest_points_between_segments(
  616. p_from,
  617. p_to,
  618. polygon.points[point_id].pos,
  619. polygon.points[(point_id + 1) % polygon.points.size()].pos,
  620. a,
  621. b);
  622. const real_t d = a.distance_to(b);
  623. if (d < closest_point_distance) {
  624. closest_point_distance = d;
  625. closest_point = b;
  626. }
  627. }
  628. }
  629. }
  630. }
  631. return closest_point;
  632. }
  633. Vector3 NavMeshQueries3D::map_iteration_get_closest_point(const NavMapIteration &p_map_iteration, const Vector3 &p_point) {
  634. gd::ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  635. return cp.point;
  636. }
  637. Vector3 NavMeshQueries3D::map_iteration_get_closest_point_normal(const NavMapIteration &p_map_iteration, const Vector3 &p_point) {
  638. gd::ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  639. return cp.normal;
  640. }
  641. RID NavMeshQueries3D::map_iteration_get_closest_point_owner(const NavMapIteration &p_map_iteration, const Vector3 &p_point) {
  642. gd::ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  643. return cp.owner;
  644. }
  645. gd::ClosestPointQueryResult NavMeshQueries3D::map_iteration_get_closest_point_info(const NavMapIteration &p_map_iteration, const Vector3 &p_point) {
  646. gd::ClosestPointQueryResult result;
  647. real_t closest_point_distance_squared = FLT_MAX;
  648. const LocalVector<NavRegionIteration> &regions = p_map_iteration.region_iterations;
  649. for (const NavRegionIteration &region : regions) {
  650. for (const gd::Polygon &polygon : region.get_navmesh_polygons()) {
  651. Vector3 plane_normal = (polygon.points[1].pos - polygon.points[0].pos).cross(polygon.points[2].pos - polygon.points[0].pos);
  652. Vector3 closest_on_polygon;
  653. real_t closest = FLT_MAX;
  654. bool inside = true;
  655. Vector3 previous = polygon.points[polygon.points.size() - 1].pos;
  656. for (size_t point_id = 0; point_id < polygon.points.size(); ++point_id) {
  657. Vector3 edge = polygon.points[point_id].pos - previous;
  658. Vector3 to_point = p_point - previous;
  659. Vector3 edge_to_point_pormal = edge.cross(to_point);
  660. bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;
  661. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  662. if (!clockwise) {
  663. inside = false;
  664. real_t point_projected_on_edge = edge.dot(to_point);
  665. real_t edge_square = edge.length_squared();
  666. if (point_projected_on_edge > edge_square) {
  667. real_t distance = polygon.points[point_id].pos.distance_squared_to(p_point);
  668. if (distance < closest) {
  669. closest_on_polygon = polygon.points[point_id].pos;
  670. closest = distance;
  671. }
  672. } else if (point_projected_on_edge < 0.f) {
  673. real_t distance = previous.distance_squared_to(p_point);
  674. if (distance < closest) {
  675. closest_on_polygon = previous;
  676. closest = distance;
  677. }
  678. } else {
  679. // If we project on this edge, this will be the closest point.
  680. real_t percent = point_projected_on_edge / edge_square;
  681. closest_on_polygon = previous + percent * edge;
  682. break;
  683. }
  684. }
  685. previous = polygon.points[point_id].pos;
  686. }
  687. if (inside) {
  688. Vector3 plane_normalized = plane_normal.normalized();
  689. real_t distance = plane_normalized.dot(p_point - polygon.points[0].pos);
  690. real_t distance_squared = distance * distance;
  691. if (distance_squared < closest_point_distance_squared) {
  692. closest_point_distance_squared = distance_squared;
  693. result.point = p_point - plane_normalized * distance;
  694. result.normal = plane_normal;
  695. result.owner = polygon.owner->get_self();
  696. if (Math::is_zero_approx(distance)) {
  697. break;
  698. }
  699. }
  700. } else {
  701. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  702. if (distance < closest_point_distance_squared) {
  703. closest_point_distance_squared = distance;
  704. result.point = closest_on_polygon;
  705. result.normal = plane_normal;
  706. result.owner = polygon.owner->get_self();
  707. }
  708. }
  709. }
  710. }
  711. return result;
  712. }
  713. Vector3 NavMeshQueries3D::map_iteration_get_random_point(const NavMapIteration &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {
  714. if (p_map_iteration.region_iterations.is_empty()) {
  715. return Vector3();
  716. }
  717. LocalVector<uint32_t> accessible_regions;
  718. accessible_regions.reserve(p_map_iteration.region_iterations.size());
  719. for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {
  720. const NavRegionIteration &region = p_map_iteration.region_iterations[i];
  721. if (!region.enabled || (p_navigation_layers & region.navigation_layers) == 0) {
  722. continue;
  723. }
  724. accessible_regions.push_back(i);
  725. }
  726. if (accessible_regions.is_empty()) {
  727. // All existing region polygons are disabled.
  728. return Vector3();
  729. }
  730. if (p_uniformly) {
  731. real_t accumulated_region_surface_area = 0;
  732. RBMap<real_t, uint32_t> accessible_regions_area_map;
  733. for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
  734. const NavRegionIteration &region = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];
  735. real_t region_surface_area = region.surface_area;
  736. if (region_surface_area == 0.0f) {
  737. continue;
  738. }
  739. accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
  740. accumulated_region_surface_area += region_surface_area;
  741. }
  742. if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
  743. // All faces have no real surface / no area.
  744. return Vector3();
  745. }
  746. real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
  747. RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
  748. ERR_FAIL_COND_V(!E, Vector3());
  749. uint32_t random_region_index = E->value;
  750. ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector3());
  751. const NavRegionIteration &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  752. return NavMeshQueries3D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  753. } else {
  754. uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
  755. const NavRegionIteration &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  756. return NavMeshQueries3D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  757. }
  758. }
  759. Vector3 NavMeshQueries3D::polygons_get_closest_point_to_segment(const LocalVector<gd::Polygon> &p_polygons, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {
  760. bool use_collision = p_use_collision;
  761. Vector3 closest_point;
  762. real_t closest_point_distance = FLT_MAX;
  763. for (const gd::Polygon &polygon : p_polygons) {
  764. // For each face check the distance to the segment.
  765. for (size_t point_id = 2; point_id < polygon.points.size(); point_id += 1) {
  766. const Face3 face(polygon.points[0].pos, polygon.points[point_id - 1].pos, polygon.points[point_id].pos);
  767. Vector3 intersection_point;
  768. if (face.intersects_segment(p_from, p_to, &intersection_point)) {
  769. const real_t d = p_from.distance_to(intersection_point);
  770. if (!use_collision) {
  771. closest_point = intersection_point;
  772. use_collision = true;
  773. closest_point_distance = d;
  774. } else if (closest_point_distance > d) {
  775. closest_point = intersection_point;
  776. closest_point_distance = d;
  777. }
  778. }
  779. // If segment does not itersect face, check the distance from segment's endpoints.
  780. else if (!use_collision) {
  781. const Vector3 p_from_closest = face.get_closest_point_to(p_from);
  782. const real_t d_p_from = p_from.distance_to(p_from_closest);
  783. if (closest_point_distance > d_p_from) {
  784. closest_point = p_from_closest;
  785. closest_point_distance = d_p_from;
  786. }
  787. const Vector3 p_to_closest = face.get_closest_point_to(p_to);
  788. const real_t d_p_to = p_to.distance_to(p_to_closest);
  789. if (closest_point_distance > d_p_to) {
  790. closest_point = p_to_closest;
  791. closest_point_distance = d_p_to;
  792. }
  793. }
  794. }
  795. // 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.
  796. if (!use_collision) {
  797. for (size_t point_id = 0; point_id < polygon.points.size(); point_id += 1) {
  798. Vector3 a, b;
  799. Geometry3D::get_closest_points_between_segments(
  800. p_from,
  801. p_to,
  802. polygon.points[point_id].pos,
  803. polygon.points[(point_id + 1) % polygon.points.size()].pos,
  804. a,
  805. b);
  806. const real_t d = a.distance_to(b);
  807. if (d < closest_point_distance) {
  808. closest_point_distance = d;
  809. closest_point = b;
  810. }
  811. }
  812. }
  813. }
  814. return closest_point;
  815. }
  816. Vector3 NavMeshQueries3D::polygons_get_closest_point(const LocalVector<gd::Polygon> &p_polygons, const Vector3 &p_point) {
  817. gd::ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  818. return cp.point;
  819. }
  820. Vector3 NavMeshQueries3D::polygons_get_closest_point_normal(const LocalVector<gd::Polygon> &p_polygons, const Vector3 &p_point) {
  821. gd::ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  822. return cp.normal;
  823. }
  824. gd::ClosestPointQueryResult NavMeshQueries3D::polygons_get_closest_point_info(const LocalVector<gd::Polygon> &p_polygons, const Vector3 &p_point) {
  825. gd::ClosestPointQueryResult result;
  826. real_t closest_point_distance_squared = FLT_MAX;
  827. for (const gd::Polygon &polygon : p_polygons) {
  828. Vector3 plane_normal = (polygon.points[1].pos - polygon.points[0].pos).cross(polygon.points[2].pos - polygon.points[0].pos);
  829. Vector3 closest_on_polygon;
  830. real_t closest = FLT_MAX;
  831. bool inside = true;
  832. Vector3 previous = polygon.points[polygon.points.size() - 1].pos;
  833. for (size_t point_id = 0; point_id < polygon.points.size(); ++point_id) {
  834. Vector3 edge = polygon.points[point_id].pos - previous;
  835. Vector3 to_point = p_point - previous;
  836. Vector3 edge_to_point_pormal = edge.cross(to_point);
  837. bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;
  838. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  839. if (!clockwise) {
  840. inside = false;
  841. real_t point_projected_on_edge = edge.dot(to_point);
  842. real_t edge_square = edge.length_squared();
  843. if (point_projected_on_edge > edge_square) {
  844. real_t distance = polygon.points[point_id].pos.distance_squared_to(p_point);
  845. if (distance < closest) {
  846. closest_on_polygon = polygon.points[point_id].pos;
  847. closest = distance;
  848. }
  849. } else if (point_projected_on_edge < 0.f) {
  850. real_t distance = previous.distance_squared_to(p_point);
  851. if (distance < closest) {
  852. closest_on_polygon = previous;
  853. closest = distance;
  854. }
  855. } else {
  856. // If we project on this edge, this will be the closest point.
  857. real_t percent = point_projected_on_edge / edge_square;
  858. closest_on_polygon = previous + percent * edge;
  859. break;
  860. }
  861. }
  862. previous = polygon.points[point_id].pos;
  863. }
  864. if (inside) {
  865. Vector3 plane_normalized = plane_normal.normalized();
  866. real_t distance = plane_normalized.dot(p_point - polygon.points[0].pos);
  867. real_t distance_squared = distance * distance;
  868. if (distance_squared < closest_point_distance_squared) {
  869. closest_point_distance_squared = distance_squared;
  870. result.point = p_point - plane_normalized * distance;
  871. result.normal = plane_normal;
  872. result.owner = polygon.owner->get_self();
  873. if (Math::is_zero_approx(distance)) {
  874. break;
  875. }
  876. }
  877. } else {
  878. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  879. if (distance < closest_point_distance_squared) {
  880. closest_point_distance_squared = distance;
  881. result.point = closest_on_polygon;
  882. result.normal = plane_normal;
  883. result.owner = polygon.owner->get_self();
  884. }
  885. }
  886. }
  887. return result;
  888. }
  889. RID NavMeshQueries3D::polygons_get_closest_point_owner(const LocalVector<gd::Polygon> &p_polygons, const Vector3 &p_point) {
  890. gd::ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  891. return cp.owner;
  892. }
  893. void NavMeshQueries3D::_query_task_clip_path(NavMeshPathQueryTask3D &p_query_task, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly) {
  894. Vector3 from = p_query_task.path_points[p_query_task.path_points.size() - 1];
  895. const LocalVector<gd::NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;
  896. const Vector3 p_map_up = p_query_task.map_up;
  897. if (from.is_equal_approx(p_to_point)) {
  898. return;
  899. }
  900. Plane cut_plane;
  901. cut_plane.normal = (from - p_to_point).cross(p_map_up);
  902. if (cut_plane.normal == Vector3()) {
  903. return;
  904. }
  905. cut_plane.normal.normalize();
  906. cut_plane.d = cut_plane.normal.dot(from);
  907. while (from_poly != p_to_poly) {
  908. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  909. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  910. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  911. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  912. if (!pathway_start.is_equal_approx(pathway_end)) {
  913. Vector3 inters;
  914. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  915. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {
  916. _query_task_push_back_point_with_metadata(p_query_task, inters, from_poly->poly);
  917. }
  918. }
  919. }
  920. }
  921. }
  922. LocalVector<uint32_t> NavMeshQueries3D::get_simplified_path_indices(const LocalVector<Vector3> &p_path, real_t p_epsilon) {
  923. p_epsilon = MAX(0.0, p_epsilon);
  924. real_t squared_epsilon = p_epsilon * p_epsilon;
  925. LocalVector<uint32_t> simplified_path_indices;
  926. simplified_path_indices.reserve(p_path.size());
  927. simplified_path_indices.push_back(0);
  928. simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);
  929. simplified_path_indices.push_back(p_path.size() - 1);
  930. return simplified_path_indices;
  931. }
  932. void 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) {
  933. Vector3 path_segment[2] = { p_points[p_start_inx], p_points[p_end_inx] };
  934. real_t point_max_distance = 0.0;
  935. int point_max_index = 0;
  936. for (int i = p_start_inx; i < p_end_inx; i++) {
  937. const Vector3 &checked_point = p_points[i];
  938. const Vector3 closest_point = Geometry3D::get_closest_point_to_segment(checked_point, path_segment);
  939. real_t distance_squared = closest_point.distance_squared_to(checked_point);
  940. if (distance_squared > point_max_distance) {
  941. point_max_index = i;
  942. point_max_distance = distance_squared;
  943. }
  944. }
  945. if (point_max_distance > p_epsilon) {
  946. simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);
  947. r_simplified_path_indices.push_back(point_max_index);
  948. simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);
  949. }
  950. }
  951. #endif // _3D_DISABLED