nav_mesh_queries_2d.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. /**************************************************************************/
  2. /* nav_mesh_queries_2d.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. #include "nav_mesh_queries_2d.h"
  31. #include "../nav_base_2d.h"
  32. #include "../nav_map_2d.h"
  33. #include "../triangle2.h"
  34. #include "nav_region_iteration_2d.h"
  35. #include "core/math/geometry_2d.h"
  36. #include "servers/navigation/navigation_utilities.h"
  37. using namespace nav_2d;
  38. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  39. bool NavMeshQueries2D::emit_callback(const Callable &p_callback) {
  40. ERR_FAIL_COND_V(!p_callback.is_valid(), false);
  41. Callable::CallError ce;
  42. Variant result;
  43. p_callback.callp(nullptr, 0, result, ce);
  44. return ce.error == Callable::CallError::CALL_OK;
  45. }
  46. Vector2 NavMeshQueries2D::polygons_get_random_point(const LocalVector<Polygon> &p_polygons, uint32_t p_navigation_layers, bool p_uniformly) {
  47. const LocalVector<Polygon> &region_polygons = p_polygons;
  48. if (region_polygons.is_empty()) {
  49. return Vector2();
  50. }
  51. if (p_uniformly) {
  52. real_t accumulated_area = 0;
  53. RBMap<real_t, uint32_t> region_area_map;
  54. for (uint32_t rp_index = 0; rp_index < region_polygons.size(); rp_index++) {
  55. const Polygon &region_polygon = region_polygons[rp_index];
  56. real_t polyon_area = region_polygon.surface_area;
  57. if (polyon_area == 0.0) {
  58. continue;
  59. }
  60. region_area_map[accumulated_area] = rp_index;
  61. accumulated_area += polyon_area;
  62. }
  63. if (region_area_map.is_empty() || accumulated_area == 0) {
  64. // All polygons have no real surface / no area.
  65. return Vector2();
  66. }
  67. real_t region_area_map_pos = Math::random(real_t(0), accumulated_area);
  68. RBMap<real_t, uint32_t>::Iterator region_E = region_area_map.find_closest(region_area_map_pos);
  69. ERR_FAIL_COND_V(!region_E, Vector2());
  70. uint32_t rrp_polygon_index = region_E->value;
  71. ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector2());
  72. const Polygon &rr_polygon = region_polygons[rrp_polygon_index];
  73. real_t accumulated_polygon_area = 0;
  74. RBMap<real_t, uint32_t> polygon_area_map;
  75. for (uint32_t rpp_index = 2; rpp_index < rr_polygon.points.size(); rpp_index++) {
  76. real_t triangle_area = Triangle2(rr_polygon.points[0].pos, rr_polygon.points[rpp_index - 1].pos, rr_polygon.points[rpp_index].pos).get_area();
  77. if (triangle_area == 0.0) {
  78. continue;
  79. }
  80. polygon_area_map[accumulated_polygon_area] = rpp_index;
  81. accumulated_polygon_area += triangle_area;
  82. }
  83. if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {
  84. // All faces have no real surface / no area.
  85. return Vector2();
  86. }
  87. real_t polygon_area_map_pos = Math::random(real_t(0), accumulated_polygon_area);
  88. RBMap<real_t, uint32_t>::Iterator polygon_E = polygon_area_map.find_closest(polygon_area_map_pos);
  89. ERR_FAIL_COND_V(!polygon_E, Vector2());
  90. uint32_t rrp_face_index = polygon_E->value;
  91. ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.points.size(), Vector2());
  92. const Triangle2 triangle(rr_polygon.points[0].pos, rr_polygon.points[rrp_face_index - 1].pos, rr_polygon.points[rrp_face_index].pos);
  93. Vector2 triangle_random_position = triangle.get_random_point_inside();
  94. return triangle_random_position;
  95. } else {
  96. uint32_t rrp_polygon_index = Math::random(int(0), region_polygons.size() - 1);
  97. const Polygon &rr_polygon = region_polygons[rrp_polygon_index];
  98. uint32_t rrp_face_index = Math::random(int(2), rr_polygon.points.size() - 1);
  99. const Triangle2 triangle(rr_polygon.points[0].pos, rr_polygon.points[rrp_face_index - 1].pos, rr_polygon.points[rrp_face_index].pos);
  100. Vector2 triangle_random_position = triangle.get_random_point_inside();
  101. return triangle_random_position;
  102. }
  103. }
  104. void NavMeshQueries2D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask2D &p_query_task, const Vector2 &p_point, const Polygon *p_point_polygon) {
  105. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  106. p_query_task.path_meta_point_types.push_back(p_point_polygon->owner->get_type());
  107. }
  108. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  109. p_query_task.path_meta_point_rids.push_back(p_point_polygon->owner->get_self());
  110. }
  111. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  112. p_query_task.path_meta_point_owners.push_back(p_point_polygon->owner->get_owner_id());
  113. }
  114. p_query_task.path_points.push_back(p_point);
  115. }
  116. void NavMeshQueries2D::map_query_path(NavMap2D *p_map, const Ref<NavigationPathQueryParameters2D> &p_query_parameters, Ref<NavigationPathQueryResult2D> p_query_result, const Callable &p_callback) {
  117. ERR_FAIL_NULL(p_map);
  118. ERR_FAIL_COND(p_query_parameters.is_null());
  119. ERR_FAIL_COND(p_query_result.is_null());
  120. using namespace NavigationUtilities;
  121. NavMeshQueries2D::NavMeshPathQueryTask2D query_task;
  122. query_task.start_position = p_query_parameters->get_start_position();
  123. query_task.target_position = p_query_parameters->get_target_position();
  124. query_task.navigation_layers = p_query_parameters->get_navigation_layers();
  125. query_task.callback = p_callback;
  126. const TypedArray<RID> &_excluded_regions = p_query_parameters->get_excluded_regions();
  127. const TypedArray<RID> &_included_regions = p_query_parameters->get_included_regions();
  128. uint32_t _excluded_region_count = _excluded_regions.size();
  129. uint32_t _included_region_count = _included_regions.size();
  130. query_task.exclude_regions = _excluded_region_count > 0;
  131. query_task.include_regions = _included_region_count > 0;
  132. if (query_task.exclude_regions) {
  133. query_task.excluded_regions.resize(_excluded_region_count);
  134. for (uint32_t i = 0; i < _excluded_region_count; i++) {
  135. query_task.excluded_regions[i] = _excluded_regions[i];
  136. }
  137. }
  138. if (query_task.include_regions) {
  139. query_task.included_regions.resize(_included_region_count);
  140. for (uint32_t i = 0; i < _included_region_count; i++) {
  141. query_task.included_regions[i] = _included_regions[i];
  142. }
  143. }
  144. switch (p_query_parameters->get_pathfinding_algorithm()) {
  145. case NavigationPathQueryParameters2D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR: {
  146. query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
  147. } break;
  148. default: {
  149. WARN_PRINT("No match for used PathfindingAlgorithm - fallback to default");
  150. query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
  151. } break;
  152. }
  153. switch (p_query_parameters->get_path_postprocessing()) {
  154. case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
  155. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
  156. } break;
  157. case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
  158. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;
  159. } break;
  160. case NavigationPathQueryParameters2D::PathPostProcessing::PATH_POSTPROCESSING_NONE: {
  161. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_NONE;
  162. } break;
  163. default: {
  164. WARN_PRINT("No match for used PathPostProcessing - fallback to default");
  165. query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
  166. } break;
  167. }
  168. query_task.metadata_flags = (int64_t)p_query_parameters->get_metadata_flags();
  169. query_task.simplify_path = p_query_parameters->get_simplify_path();
  170. query_task.simplify_epsilon = p_query_parameters->get_simplify_epsilon();
  171. query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_STARTED;
  172. p_map->query_path(query_task);
  173. p_query_result->set_data(
  174. query_task.path_points,
  175. query_task.path_meta_point_types,
  176. query_task.path_meta_point_rids,
  177. query_task.path_meta_point_owners);
  178. if (query_task.callback.is_valid()) {
  179. if (emit_callback(query_task.callback)) {
  180. query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_DISPATCHED;
  181. } else {
  182. query_task.status = NavMeshPathQueryTask2D::TaskStatus::CALLBACK_FAILED;
  183. }
  184. }
  185. }
  186. void NavMeshQueries2D::_query_task_find_start_end_positions(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {
  187. real_t begin_d = FLT_MAX;
  188. real_t end_d = FLT_MAX;
  189. const LocalVector<NavRegionIteration2D> &regions = p_map_iteration.region_iterations;
  190. for (const NavRegionIteration2D &region : regions) {
  191. if (!region.get_enabled()) {
  192. continue;
  193. }
  194. if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(region.get_self())) {
  195. continue;
  196. }
  197. if (p_query_task.include_regions && !p_query_task.included_regions.has(region.get_self())) {
  198. continue;
  199. }
  200. // Find the initial poly and the end poly on this map.
  201. for (const Polygon &p : region.get_navmesh_polygons()) {
  202. // Only consider the polygon if it in a region with compatible layers.
  203. if ((p_query_task.navigation_layers & p.owner->get_navigation_layers()) == 0) {
  204. continue;
  205. }
  206. // For each triangle check the distance between the origin/destination.
  207. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  208. const Triangle2 triangle(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  209. Vector2 point = triangle.get_closest_point_to(p_query_task.start_position);
  210. real_t distance_to_point = point.distance_to(p_query_task.start_position);
  211. if (distance_to_point < begin_d) {
  212. begin_d = distance_to_point;
  213. p_query_task.begin_polygon = &p;
  214. p_query_task.begin_position = point;
  215. }
  216. point = triangle.get_closest_point_to(p_query_task.target_position);
  217. distance_to_point = point.distance_to(p_query_task.target_position);
  218. if (distance_to_point < end_d) {
  219. end_d = distance_to_point;
  220. p_query_task.end_polygon = &p;
  221. p_query_task.end_position = point;
  222. }
  223. }
  224. }
  225. }
  226. }
  227. void NavMeshQueries2D::_query_task_build_path_corridor(NavMeshPathQueryTask2D &p_query_task) {
  228. const Vector2 p_target_position = p_query_task.target_position;
  229. const Polygon *begin_poly = p_query_task.begin_polygon;
  230. const Polygon *end_poly = p_query_task.end_polygon;
  231. Vector2 begin_point = p_query_task.begin_position;
  232. Vector2 end_point = p_query_task.end_position;
  233. // Heap of polygons to travel next.
  234. Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>
  235. &traversable_polys = p_query_task.path_query_slot->traversable_polys;
  236. traversable_polys.clear();
  237. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  238. for (NavigationPoly &polygon : navigation_polys) {
  239. polygon.reset();
  240. }
  241. // Initialize the matching navigation polygon.
  242. NavigationPoly &begin_navigation_poly = navigation_polys[begin_poly->id];
  243. begin_navigation_poly.poly = begin_poly;
  244. begin_navigation_poly.entry = begin_point;
  245. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  246. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  247. begin_navigation_poly.traveled_distance = 0.0;
  248. // This is an implementation of the A* algorithm.
  249. uint32_t least_cost_id = begin_poly->id;
  250. bool found_route = false;
  251. const Polygon *reachable_end = nullptr;
  252. real_t distance_to_reachable_end = FLT_MAX;
  253. bool is_reachable = true;
  254. real_t poly_enter_cost = 0.0;
  255. while (true) {
  256. const NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
  257. real_t poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost();
  258. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  259. for (const Edge &edge : least_cost_poly.poly->edges) {
  260. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  261. for (uint32_t connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  262. const Edge::Connection &connection = edge.connections[connection_index];
  263. const NavBaseIteration2D *connection_owner = connection.polygon->owner;
  264. const bool owner_is_usable = _query_task_is_connection_owner_usable(p_query_task, connection_owner);
  265. if (!owner_is_usable) {
  266. continue;
  267. }
  268. Vector2 pathway[2] = { connection.pathway_start, connection.pathway_end };
  269. const Vector2 new_entry = Geometry2D::get_closest_point_to_segment(least_cost_poly.entry, pathway);
  270. 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;
  271. // Check if the neighbor polygon has already been processed.
  272. NavigationPoly &neighbor_poly = navigation_polys[connection.polygon->id];
  273. if (new_traveled_distance < neighbor_poly.traveled_distance) {
  274. // Add the polygon to the heap of polygons to traverse next.
  275. neighbor_poly.back_navigation_poly_id = least_cost_id;
  276. neighbor_poly.back_navigation_edge = connection.edge;
  277. neighbor_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  278. neighbor_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  279. neighbor_poly.traveled_distance = new_traveled_distance;
  280. neighbor_poly.distance_to_destination =
  281. new_entry.distance_to(end_point) *
  282. connection_owner->get_travel_cost();
  283. neighbor_poly.entry = new_entry;
  284. if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {
  285. traversable_polys.shift(neighbor_poly.traversable_poly_index);
  286. } else {
  287. neighbor_poly.poly = connection.polygon;
  288. traversable_polys.push(&neighbor_poly);
  289. }
  290. }
  291. }
  292. }
  293. poly_enter_cost = 0;
  294. // When the heap of traversable polygons is empty at this point it means the end polygon is
  295. // unreachable.
  296. if (traversable_polys.is_empty()) {
  297. // Thus use the further reachable polygon
  298. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  299. is_reachable = false;
  300. if (reachable_end == nullptr) {
  301. // The path is not found and there is not a way out.
  302. break;
  303. }
  304. // Set as end point the furthest reachable point.
  305. end_poly = reachable_end;
  306. real_t end_d = FLT_MAX;
  307. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  308. Triangle2 t(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  309. Vector2 spoint = t.get_closest_point_to(p_target_position);
  310. real_t dpoint = spoint.distance_squared_to(p_target_position);
  311. if (dpoint < end_d) {
  312. end_point = spoint;
  313. end_d = dpoint;
  314. }
  315. }
  316. // Search all faces of start polygon as well.
  317. bool closest_point_on_start_poly = false;
  318. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  319. Triangle2 t(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  320. Vector2 spoint = t.get_closest_point_to(p_target_position);
  321. real_t dpoint = spoint.distance_squared_to(p_target_position);
  322. if (dpoint < end_d) {
  323. end_point = spoint;
  324. end_d = dpoint;
  325. closest_point_on_start_poly = true;
  326. }
  327. }
  328. if (closest_point_on_start_poly) {
  329. // No point to run PostProcessing when start and end convex polygon is the same.
  330. p_query_task.path_clear();
  331. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  332. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  333. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  334. return;
  335. }
  336. for (NavigationPoly &nav_poly : navigation_polys) {
  337. nav_poly.poly = nullptr;
  338. nav_poly.traveled_distance = FLT_MAX;
  339. }
  340. navigation_polys[begin_poly->id].poly = begin_poly;
  341. navigation_polys[begin_poly->id].traveled_distance = 0;
  342. least_cost_id = begin_poly->id;
  343. reachable_end = nullptr;
  344. } else {
  345. // Pop the polygon with the lowest travel cost from the heap of traversable polygons.
  346. least_cost_id = traversable_polys.pop()->poly->id;
  347. // Store the farthest reachable end polygon in case our goal is not reachable.
  348. if (is_reachable) {
  349. real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);
  350. if (distance_to_reachable_end > distance) {
  351. distance_to_reachable_end = distance;
  352. reachable_end = navigation_polys[least_cost_id].poly;
  353. }
  354. }
  355. // Check if we reached the end
  356. if (navigation_polys[least_cost_id].poly == end_poly) {
  357. found_route = true;
  358. break;
  359. }
  360. if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {
  361. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  362. }
  363. }
  364. }
  365. // We did not find a route but we have both a start polygon and an end polygon at this point.
  366. // 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.
  367. if (!found_route) {
  368. real_t end_d = FLT_MAX;
  369. // Search all faces of the start polygon for the closest point to our target position.
  370. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  371. Triangle2 t(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  372. Vector2 spoint = t.get_closest_point_to(p_target_position);
  373. real_t dpoint = spoint.distance_squared_to(p_target_position);
  374. if (dpoint < end_d) {
  375. end_point = spoint;
  376. end_d = dpoint;
  377. }
  378. }
  379. p_query_task.path_clear();
  380. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  381. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  382. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  383. } else {
  384. p_query_task.end_position = end_point;
  385. p_query_task.end_polygon = end_poly;
  386. p_query_task.begin_position = begin_point;
  387. p_query_task.begin_polygon = begin_poly;
  388. p_query_task.least_cost_id = least_cost_id;
  389. }
  390. }
  391. void NavMeshQueries2D::query_task_map_iteration_get_path(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {
  392. p_query_task.path_clear();
  393. _query_task_find_start_end_positions(p_query_task, p_map_iteration);
  394. // Check for trivial cases.
  395. if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {
  396. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  397. return;
  398. }
  399. if (p_query_task.begin_polygon == p_query_task.end_polygon) {
  400. p_query_task.path_clear();
  401. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);
  402. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);
  403. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  404. return;
  405. }
  406. _query_task_build_path_corridor(p_query_task);
  407. if (p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FAILED) {
  408. return;
  409. }
  410. // Post-Process path.
  411. switch (p_query_task.path_postprocessing) {
  412. case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
  413. _query_task_post_process_corridorfunnel(p_query_task);
  414. } break;
  415. case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
  416. _query_task_post_process_edgecentered(p_query_task);
  417. } break;
  418. case PathPostProcessing::PATH_POSTPROCESSING_NONE: {
  419. _query_task_post_process_nopostprocessing(p_query_task);
  420. } break;
  421. default: {
  422. WARN_PRINT("No match for used PathPostProcessing - fallback to default");
  423. _query_task_post_process_corridorfunnel(p_query_task);
  424. } break;
  425. }
  426. p_query_task.path_reverse();
  427. if (p_query_task.simplify_path) {
  428. _query_task_simplified_path_points(p_query_task);
  429. }
  430. #ifdef DEBUG_ENABLED
  431. // Ensure post conditions as path meta arrays if used MUST match in array size with the path points.
  432. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  433. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());
  434. }
  435. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  436. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());
  437. }
  438. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  439. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());
  440. }
  441. #endif // DEBUG_ENABLED
  442. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  443. }
  444. void NavMeshQueries2D::_query_task_simplified_path_points(NavMeshPathQueryTask2D &p_query_task) {
  445. if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {
  446. return;
  447. }
  448. const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries2D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);
  449. uint32_t index_count = simplified_path_indices.size();
  450. {
  451. Vector2 *points_ptr = p_query_task.path_points.ptr();
  452. for (uint32_t i = 0; i < index_count; i++) {
  453. points_ptr[i] = points_ptr[simplified_path_indices[i]];
  454. }
  455. p_query_task.path_points.resize(index_count);
  456. }
  457. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  458. int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();
  459. for (uint32_t i = 0; i < index_count; i++) {
  460. types_ptr[i] = types_ptr[simplified_path_indices[i]];
  461. }
  462. p_query_task.path_meta_point_types.resize(index_count);
  463. }
  464. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  465. RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();
  466. for (uint32_t i = 0; i < index_count; i++) {
  467. rids_ptr[i] = rids_ptr[simplified_path_indices[i]];
  468. }
  469. p_query_task.path_meta_point_rids.resize(index_count);
  470. }
  471. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  472. int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();
  473. for (uint32_t i = 0; i < index_count; i++) {
  474. owners_ptr[i] = owners_ptr[simplified_path_indices[i]];
  475. }
  476. p_query_task.path_meta_point_owners.resize(index_count);
  477. }
  478. }
  479. void NavMeshQueries2D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask2D &p_query_task) {
  480. Vector2 end_point = p_query_task.end_position;
  481. const Polygon *end_poly = p_query_task.end_polygon;
  482. Vector2 begin_point = p_query_task.begin_position;
  483. const Polygon *begin_poly = p_query_task.begin_polygon;
  484. uint32_t least_cost_id = p_query_task.least_cost_id;
  485. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  486. // Set the apex poly/point to the end point.
  487. NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  488. Vector2 back_pathway[2] = { apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end };
  489. const Vector2 back_edge_closest_point = Geometry2D::get_closest_point_to_segment(end_point, back_pathway);
  490. if (end_point.is_equal_approx(back_edge_closest_point)) {
  491. // The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
  492. // At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
  493. if (apex_poly->back_navigation_poly_id != -1) {
  494. apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
  495. }
  496. }
  497. Vector2 apex_point = end_point;
  498. NavigationPoly *left_poly = apex_poly;
  499. Vector2 left_portal = apex_point;
  500. NavigationPoly *right_poly = apex_poly;
  501. Vector2 right_portal = apex_point;
  502. NavigationPoly *p = apex_poly;
  503. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  504. while (p) {
  505. // Set left and right points of the pathway between polygons.
  506. Vector2 left = p->back_navigation_edge_pathway_start;
  507. Vector2 right = p->back_navigation_edge_pathway_end;
  508. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right) < 0) {
  509. SWAP(left, right);
  510. }
  511. bool skip = false;
  512. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left) >= 0) {
  513. // Process.
  514. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal) > 0) {
  515. left_poly = p;
  516. left_portal = left;
  517. } else {
  518. _query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);
  519. apex_point = right_portal;
  520. p = right_poly;
  521. left_poly = p;
  522. apex_poly = p;
  523. left_portal = apex_point;
  524. right_portal = apex_point;
  525. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  526. skip = true;
  527. }
  528. }
  529. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right) <= 0) {
  530. // Process.
  531. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal) < 0) {
  532. right_poly = p;
  533. right_portal = right;
  534. } else {
  535. _query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);
  536. apex_point = left_portal;
  537. p = left_poly;
  538. right_poly = p;
  539. apex_poly = p;
  540. right_portal = apex_point;
  541. left_portal = apex_point;
  542. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  543. }
  544. }
  545. // Go to the previous polygon.
  546. if (p->back_navigation_poly_id != -1) {
  547. p = &navigation_polys[p->back_navigation_poly_id];
  548. } else {
  549. // The end
  550. p = nullptr;
  551. }
  552. }
  553. // If the last point is not the begin point, add it to the list.
  554. if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {
  555. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  556. }
  557. }
  558. void NavMeshQueries2D::_query_task_post_process_edgecentered(NavMeshPathQueryTask2D &p_query_task) {
  559. Vector2 end_point = p_query_task.end_position;
  560. const Polygon *end_poly = p_query_task.end_polygon;
  561. Vector2 begin_point = p_query_task.begin_position;
  562. const Polygon *begin_poly = p_query_task.begin_polygon;
  563. uint32_t least_cost_id = p_query_task.least_cost_id;
  564. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  565. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  566. // Add mid points.
  567. int np_id = least_cost_id;
  568. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  569. if (navigation_polys[np_id].back_navigation_edge != -1) {
  570. int prev = navigation_polys[np_id].back_navigation_edge;
  571. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  572. Vector2 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  573. _query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);
  574. } else {
  575. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  576. }
  577. np_id = navigation_polys[np_id].back_navigation_poly_id;
  578. }
  579. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  580. }
  581. void NavMeshQueries2D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask2D &p_query_task) {
  582. Vector2 end_point = p_query_task.end_position;
  583. const Polygon *end_poly = p_query_task.end_polygon;
  584. Vector2 begin_point = p_query_task.begin_position;
  585. const Polygon *begin_poly = p_query_task.begin_polygon;
  586. uint32_t least_cost_id = p_query_task.least_cost_id;
  587. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  588. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  589. // Add mid points.
  590. int np_id = least_cost_id;
  591. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  592. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  593. np_id = navigation_polys[np_id].back_navigation_poly_id;
  594. }
  595. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  596. }
  597. Vector2 NavMeshQueries2D::map_iteration_get_closest_point(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  598. ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  599. return cp.point;
  600. }
  601. RID NavMeshQueries2D::map_iteration_get_closest_point_owner(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  602. ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  603. return cp.owner;
  604. }
  605. ClosestPointQueryResult NavMeshQueries2D::map_iteration_get_closest_point_info(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  606. ClosestPointQueryResult result;
  607. real_t closest_point_distance_squared = FLT_MAX;
  608. // TODO: Check for further 2D improvements.
  609. const LocalVector<NavRegionIteration2D> &regions = p_map_iteration.region_iterations;
  610. for (const NavRegionIteration2D &region : regions) {
  611. for (const Polygon &polygon : region.get_navmesh_polygons()) {
  612. real_t cross = (polygon.points[1].pos - polygon.points[0].pos).cross(polygon.points[2].pos - polygon.points[0].pos);
  613. Vector2 closest_on_polygon;
  614. real_t closest = FLT_MAX;
  615. bool inside = true;
  616. Vector2 previous = polygon.points[polygon.points.size() - 1].pos;
  617. for (size_t point_id = 0; point_id < polygon.points.size(); ++point_id) {
  618. Vector2 edge = polygon.points[point_id].pos - previous;
  619. Vector2 to_point = p_point - previous;
  620. real_t edge_to_point_cross = edge.cross(to_point);
  621. bool clockwise = (edge_to_point_cross * cross) > 0;
  622. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  623. if (!clockwise) {
  624. inside = false;
  625. real_t point_projected_on_edge = edge.dot(to_point);
  626. real_t edge_square = edge.length_squared();
  627. if (point_projected_on_edge > edge_square) {
  628. real_t distance = polygon.points[point_id].pos.distance_squared_to(p_point);
  629. if (distance < closest) {
  630. closest_on_polygon = polygon.points[point_id].pos;
  631. closest = distance;
  632. }
  633. } else if (point_projected_on_edge < 0.0) {
  634. real_t distance = previous.distance_squared_to(p_point);
  635. if (distance < closest) {
  636. closest_on_polygon = previous;
  637. closest = distance;
  638. }
  639. } else {
  640. // If we project on this edge, this will be the closest point.
  641. real_t percent = point_projected_on_edge / edge_square;
  642. closest_on_polygon = previous + percent * edge;
  643. break;
  644. }
  645. }
  646. previous = polygon.points[point_id].pos;
  647. }
  648. if (inside) {
  649. closest_point_distance_squared = 0.0;
  650. result.point = p_point;
  651. result.owner = polygon.owner->get_self();
  652. break;
  653. } else {
  654. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  655. if (distance < closest_point_distance_squared) {
  656. closest_point_distance_squared = distance;
  657. result.point = closest_on_polygon;
  658. result.owner = polygon.owner->get_self();
  659. }
  660. }
  661. }
  662. }
  663. return result;
  664. }
  665. Vector2 NavMeshQueries2D::map_iteration_get_random_point(const NavMapIteration2D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {
  666. if (p_map_iteration.region_iterations.is_empty()) {
  667. return Vector2();
  668. }
  669. LocalVector<uint32_t> accessible_regions;
  670. accessible_regions.reserve(p_map_iteration.region_iterations.size());
  671. for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {
  672. const NavRegionIteration2D &region = p_map_iteration.region_iterations[i];
  673. if (!region.enabled || (p_navigation_layers & region.navigation_layers) == 0) {
  674. continue;
  675. }
  676. accessible_regions.push_back(i);
  677. }
  678. if (accessible_regions.is_empty()) {
  679. // All existing region polygons are disabled.
  680. return Vector2();
  681. }
  682. if (p_uniformly) {
  683. real_t accumulated_region_surface_area = 0;
  684. RBMap<real_t, uint32_t> accessible_regions_area_map;
  685. for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
  686. const NavRegionIteration2D &region = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];
  687. real_t region_surface_area = region.surface_area;
  688. if (region_surface_area == 0.0f) {
  689. continue;
  690. }
  691. accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
  692. accumulated_region_surface_area += region_surface_area;
  693. }
  694. if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
  695. // All faces have no real surface / no area.
  696. return Vector2();
  697. }
  698. real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
  699. RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
  700. ERR_FAIL_COND_V(!E, Vector2());
  701. uint32_t random_region_index = E->value;
  702. ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector2());
  703. const NavRegionIteration2D &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  704. return NavMeshQueries2D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  705. } else {
  706. uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
  707. const NavRegionIteration2D &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  708. return NavMeshQueries2D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  709. }
  710. }
  711. Vector2 NavMeshQueries2D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  712. ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  713. return cp.point;
  714. }
  715. ClosestPointQueryResult NavMeshQueries2D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  716. ClosestPointQueryResult result;
  717. real_t closest_point_distance_squared = FLT_MAX;
  718. // TODO: Check for further 2D improvements.
  719. for (const Polygon &polygon : p_polygons) {
  720. real_t cross = (polygon.points[1].pos - polygon.points[0].pos).cross(polygon.points[2].pos - polygon.points[0].pos);
  721. Vector2 closest_on_polygon;
  722. real_t closest = FLT_MAX;
  723. bool inside = true;
  724. Vector2 previous = polygon.points[polygon.points.size() - 1].pos;
  725. for (size_t point_id = 0; point_id < polygon.points.size(); ++point_id) {
  726. Vector2 edge = polygon.points[point_id].pos - previous;
  727. Vector2 to_point = p_point - previous;
  728. real_t edge_to_point_cross = edge.cross(to_point);
  729. bool clockwise = (edge_to_point_cross * cross) > 0;
  730. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  731. if (!clockwise) {
  732. inside = false;
  733. real_t point_projected_on_edge = edge.dot(to_point);
  734. real_t edge_square = edge.length_squared();
  735. if (point_projected_on_edge > edge_square) {
  736. real_t distance = polygon.points[point_id].pos.distance_squared_to(p_point);
  737. if (distance < closest) {
  738. closest_on_polygon = polygon.points[point_id].pos;
  739. closest = distance;
  740. }
  741. } else if (point_projected_on_edge < 0.0) {
  742. real_t distance = previous.distance_squared_to(p_point);
  743. if (distance < closest) {
  744. closest_on_polygon = previous;
  745. closest = distance;
  746. }
  747. } else {
  748. // If we project on this edge, this will be the closest point.
  749. real_t percent = point_projected_on_edge / edge_square;
  750. closest_on_polygon = previous + percent * edge;
  751. break;
  752. }
  753. }
  754. previous = polygon.points[point_id].pos;
  755. }
  756. if (inside) {
  757. closest_point_distance_squared = 0.0;
  758. result.point = p_point;
  759. result.owner = polygon.owner->get_self();
  760. break;
  761. } else {
  762. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  763. if (distance < closest_point_distance_squared) {
  764. closest_point_distance_squared = distance;
  765. result.point = closest_on_polygon;
  766. result.owner = polygon.owner->get_self();
  767. }
  768. }
  769. }
  770. return result;
  771. }
  772. RID NavMeshQueries2D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  773. ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  774. return cp.owner;
  775. }
  776. static bool _line_intersects_segment(const Vector2 &p_line_normal, real_t p_line_d, const Vector2 &p_segment_begin, const Vector2 &p_segment_end, Vector2 &r_intersection) {
  777. Vector2 segment = p_segment_begin - p_segment_end;
  778. real_t den = p_line_normal.dot(segment);
  779. if (Math::is_zero_approx(den)) {
  780. return false;
  781. }
  782. real_t dist = (p_line_normal.dot(p_segment_begin) - p_line_d) / den;
  783. if (dist < (real_t)-CMP_EPSILON || dist > (1.0 + (real_t)CMP_EPSILON)) {
  784. return false;
  785. }
  786. r_intersection = p_segment_begin - segment * dist;
  787. return true;
  788. }
  789. void NavMeshQueries2D::_query_task_clip_path(NavMeshPathQueryTask2D &p_query_task, const NavigationPoly *p_from_poly, const Vector2 &p_to_point, const NavigationPoly *p_to_poly) {
  790. Vector2 from = p_query_task.path_points[p_query_task.path_points.size() - 1];
  791. const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;
  792. if (from.is_equal_approx(p_to_point)) {
  793. return;
  794. }
  795. // Compute line parameters (equivalent to the Plane case in 3D).
  796. const Vector2 normal = -(from - p_to_point).orthogonal().normalized();
  797. const real_t d = normal.dot(from);
  798. while (p_from_poly != p_to_poly) {
  799. Vector2 pathway_start = p_from_poly->back_navigation_edge_pathway_start;
  800. Vector2 pathway_end = p_from_poly->back_navigation_edge_pathway_end;
  801. ERR_FAIL_COND(p_from_poly->back_navigation_poly_id == -1);
  802. p_from_poly = &p_navigation_polys[p_from_poly->back_navigation_poly_id];
  803. if (!pathway_start.is_equal_approx(pathway_end)) {
  804. Vector2 inters;
  805. if (_line_intersects_segment(normal, d, pathway_start, pathway_end, inters)) {
  806. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {
  807. _query_task_push_back_point_with_metadata(p_query_task, inters, p_from_poly->poly);
  808. }
  809. }
  810. }
  811. }
  812. }
  813. bool NavMeshQueries2D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask2D &p_query_task, const NavBaseIteration2D *p_owner) {
  814. bool owner_usable = true;
  815. if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {
  816. // Not usable. No matching bit between task filter bitmask and owner bitmask.
  817. owner_usable = false;
  818. return owner_usable;
  819. }
  820. if (p_query_task.exclude_regions || p_query_task.include_regions) {
  821. switch (p_owner->get_type()) {
  822. case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {
  823. if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {
  824. // Not usable. Exclude region filter is active and this region is excluded.
  825. owner_usable = false;
  826. } else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {
  827. // Not usable. Include region filter is active and this region is not included.
  828. owner_usable = false;
  829. }
  830. } break;
  831. case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {
  832. const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();
  833. if (link_polygons.size() != 2) {
  834. // Not usable. Whatever this is, it is not a valid connected link.
  835. owner_usable = false;
  836. } else {
  837. const RID link_start_region = link_polygons[0].owner->get_self();
  838. const RID link_end_region = link_polygons[1].owner->get_self();
  839. if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {
  840. // Not usable. Exclude region filter is active and at least one region of the link is excluded.
  841. owner_usable = false;
  842. }
  843. if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {
  844. // Not usable. Include region filter is active and not both regions of the links are included.
  845. owner_usable = false;
  846. }
  847. }
  848. } break;
  849. }
  850. }
  851. return owner_usable;
  852. }
  853. LocalVector<uint32_t> NavMeshQueries2D::get_simplified_path_indices(const LocalVector<Vector2> &p_path, real_t p_epsilon) {
  854. p_epsilon = MAX(0.0, p_epsilon);
  855. real_t squared_epsilon = p_epsilon * p_epsilon;
  856. LocalVector<uint32_t> simplified_path_indices;
  857. simplified_path_indices.reserve(p_path.size());
  858. simplified_path_indices.push_back(0);
  859. simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);
  860. simplified_path_indices.push_back(p_path.size() - 1);
  861. return simplified_path_indices;
  862. }
  863. void NavMeshQueries2D::simplify_path_segment(int p_start_inx, int p_end_inx, const LocalVector<Vector2> &p_points, real_t p_epsilon, LocalVector<uint32_t> &r_simplified_path_indices) {
  864. Vector2 path_segment[2] = { p_points[p_start_inx], p_points[p_end_inx] };
  865. real_t point_max_distance = 0.0;
  866. int point_max_index = 0;
  867. for (int i = p_start_inx; i < p_end_inx; i++) {
  868. const Vector2 &checked_point = p_points[i];
  869. const Vector2 closest_point = Geometry2D::get_closest_point_to_segment(checked_point, path_segment);
  870. real_t distance_squared = closest_point.distance_squared_to(checked_point);
  871. if (distance_squared > point_max_distance) {
  872. point_max_index = i;
  873. point_max_distance = distance_squared;
  874. }
  875. }
  876. if (point_max_distance > p_epsilon) {
  877. simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);
  878. r_simplified_path_indices.push_back(point_max_index);
  879. simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);
  880. }
  881. }