nav_mesh_queries_2d.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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.vertices.size(); rpp_index++) {
  76. real_t triangle_area = Triangle2(rr_polygon.vertices[0], rr_polygon.vertices[rpp_index - 1], rr_polygon.vertices[rpp_index]).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.vertices.size(), Vector2());
  92. const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);
  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.vertices.size() - 1);
  99. const Triangle2 triangle(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);
  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 (uint32_t point_id = 2; point_id < p.vertices.size(); point_id++) {
  208. const Triangle2 triangle(p.vertices[0], p.vertices[point_id - 1], p.vertices[point_id]);
  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. const Vector2 new_entry = Geometry2D::get_closest_point_to_segment(least_cost_poly.entry, connection.pathway_start, connection.pathway_end);
  269. 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;
  270. // Check if the neighbor polygon has already been processed.
  271. NavigationPoly &neighbor_poly = navigation_polys[connection.polygon->id];
  272. if (new_traveled_distance < neighbor_poly.traveled_distance) {
  273. // Add the polygon to the heap of polygons to traverse next.
  274. neighbor_poly.back_navigation_poly_id = least_cost_id;
  275. neighbor_poly.back_navigation_edge = connection.edge;
  276. neighbor_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  277. neighbor_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  278. neighbor_poly.traveled_distance = new_traveled_distance;
  279. neighbor_poly.distance_to_destination =
  280. new_entry.distance_to(end_point) *
  281. connection_owner->get_travel_cost();
  282. neighbor_poly.entry = new_entry;
  283. if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {
  284. traversable_polys.shift(neighbor_poly.traversable_poly_index);
  285. } else {
  286. neighbor_poly.poly = connection.polygon;
  287. traversable_polys.push(&neighbor_poly);
  288. }
  289. }
  290. }
  291. }
  292. poly_enter_cost = 0;
  293. // When the heap of traversable polygons is empty at this point it means the end polygon is
  294. // unreachable.
  295. if (traversable_polys.is_empty()) {
  296. // Thus use the further reachable polygon
  297. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  298. is_reachable = false;
  299. if (reachable_end == nullptr) {
  300. // The path is not found and there is not a way out.
  301. break;
  302. }
  303. // Set as end point the furthest reachable point.
  304. end_poly = reachable_end;
  305. real_t end_d = FLT_MAX;
  306. for (uint32_t point_id = 2; point_id < end_poly->vertices.size(); point_id++) {
  307. Triangle2 t(end_poly->vertices[0], end_poly->vertices[point_id - 1], end_poly->vertices[point_id]);
  308. Vector2 spoint = t.get_closest_point_to(p_target_position);
  309. real_t dpoint = spoint.distance_squared_to(p_target_position);
  310. if (dpoint < end_d) {
  311. end_point = spoint;
  312. end_d = dpoint;
  313. }
  314. }
  315. // Search all faces of start polygon as well.
  316. bool closest_point_on_start_poly = false;
  317. for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {
  318. Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);
  319. Vector2 spoint = t.get_closest_point_to(p_target_position);
  320. real_t dpoint = spoint.distance_squared_to(p_target_position);
  321. if (dpoint < end_d) {
  322. end_point = spoint;
  323. end_d = dpoint;
  324. closest_point_on_start_poly = true;
  325. }
  326. }
  327. if (closest_point_on_start_poly) {
  328. // No point to run PostProcessing when start and end convex polygon is the same.
  329. p_query_task.path_clear();
  330. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  331. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  332. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  333. return;
  334. }
  335. for (NavigationPoly &nav_poly : navigation_polys) {
  336. nav_poly.poly = nullptr;
  337. nav_poly.traveled_distance = FLT_MAX;
  338. }
  339. navigation_polys[begin_poly->id].poly = begin_poly;
  340. navigation_polys[begin_poly->id].traveled_distance = 0;
  341. least_cost_id = begin_poly->id;
  342. reachable_end = nullptr;
  343. } else {
  344. // Pop the polygon with the lowest travel cost from the heap of traversable polygons.
  345. least_cost_id = traversable_polys.pop()->poly->id;
  346. // Store the farthest reachable end polygon in case our goal is not reachable.
  347. if (is_reachable) {
  348. real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);
  349. if (distance_to_reachable_end > distance) {
  350. distance_to_reachable_end = distance;
  351. reachable_end = navigation_polys[least_cost_id].poly;
  352. }
  353. }
  354. // Check if we reached the end
  355. if (navigation_polys[least_cost_id].poly == end_poly) {
  356. found_route = true;
  357. break;
  358. }
  359. if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {
  360. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  361. }
  362. }
  363. }
  364. // We did not find a route but we have both a start polygon and an end polygon at this point.
  365. // 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.
  366. if (!found_route) {
  367. real_t end_d = FLT_MAX;
  368. // Search all faces of the start polygon for the closest point to our target position.
  369. for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {
  370. Triangle2 t(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);
  371. Vector2 spoint = t.get_closest_point_to(p_target_position);
  372. real_t dpoint = spoint.distance_squared_to(p_target_position);
  373. if (dpoint < end_d) {
  374. end_point = spoint;
  375. end_d = dpoint;
  376. }
  377. }
  378. p_query_task.path_clear();
  379. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  380. _query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
  381. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  382. } else {
  383. p_query_task.end_position = end_point;
  384. p_query_task.end_polygon = end_poly;
  385. p_query_task.begin_position = begin_point;
  386. p_query_task.begin_polygon = begin_poly;
  387. p_query_task.least_cost_id = least_cost_id;
  388. }
  389. }
  390. void NavMeshQueries2D::query_task_map_iteration_get_path(NavMeshPathQueryTask2D &p_query_task, const NavMapIteration2D &p_map_iteration) {
  391. p_query_task.path_clear();
  392. _query_task_find_start_end_positions(p_query_task, p_map_iteration);
  393. // Check for trivial cases.
  394. if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {
  395. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  396. return;
  397. }
  398. if (p_query_task.begin_polygon == p_query_task.end_polygon) {
  399. p_query_task.path_clear();
  400. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);
  401. _query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);
  402. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  403. return;
  404. }
  405. _query_task_build_path_corridor(p_query_task);
  406. if (p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask2D::TaskStatus::QUERY_FAILED) {
  407. return;
  408. }
  409. // Post-Process path.
  410. switch (p_query_task.path_postprocessing) {
  411. case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
  412. _query_task_post_process_corridorfunnel(p_query_task);
  413. } break;
  414. case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
  415. _query_task_post_process_edgecentered(p_query_task);
  416. } break;
  417. case PathPostProcessing::PATH_POSTPROCESSING_NONE: {
  418. _query_task_post_process_nopostprocessing(p_query_task);
  419. } break;
  420. default: {
  421. WARN_PRINT("No match for used PathPostProcessing - fallback to default");
  422. _query_task_post_process_corridorfunnel(p_query_task);
  423. } break;
  424. }
  425. p_query_task.path_reverse();
  426. if (p_query_task.simplify_path) {
  427. _query_task_simplified_path_points(p_query_task);
  428. }
  429. #ifdef DEBUG_ENABLED
  430. // Ensure post conditions as path meta arrays if used MUST match in array size with the path points.
  431. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  432. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());
  433. }
  434. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  435. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());
  436. }
  437. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  438. DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());
  439. }
  440. #endif // DEBUG_ENABLED
  441. p_query_task.status = NavMeshPathQueryTask2D::TaskStatus::QUERY_FINISHED;
  442. }
  443. void NavMeshQueries2D::_query_task_simplified_path_points(NavMeshPathQueryTask2D &p_query_task) {
  444. if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {
  445. return;
  446. }
  447. const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries2D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);
  448. uint32_t index_count = simplified_path_indices.size();
  449. {
  450. Vector2 *points_ptr = p_query_task.path_points.ptr();
  451. for (uint32_t i = 0; i < index_count; i++) {
  452. points_ptr[i] = points_ptr[simplified_path_indices[i]];
  453. }
  454. p_query_task.path_points.resize(index_count);
  455. }
  456. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
  457. int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();
  458. for (uint32_t i = 0; i < index_count; i++) {
  459. types_ptr[i] = types_ptr[simplified_path_indices[i]];
  460. }
  461. p_query_task.path_meta_point_types.resize(index_count);
  462. }
  463. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
  464. RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();
  465. for (uint32_t i = 0; i < index_count; i++) {
  466. rids_ptr[i] = rids_ptr[simplified_path_indices[i]];
  467. }
  468. p_query_task.path_meta_point_rids.resize(index_count);
  469. }
  470. if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
  471. int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();
  472. for (uint32_t i = 0; i < index_count; i++) {
  473. owners_ptr[i] = owners_ptr[simplified_path_indices[i]];
  474. }
  475. p_query_task.path_meta_point_owners.resize(index_count);
  476. }
  477. }
  478. void NavMeshQueries2D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask2D &p_query_task) {
  479. Vector2 end_point = p_query_task.end_position;
  480. const Polygon *end_poly = p_query_task.end_polygon;
  481. Vector2 begin_point = p_query_task.begin_position;
  482. const Polygon *begin_poly = p_query_task.begin_polygon;
  483. uint32_t least_cost_id = p_query_task.least_cost_id;
  484. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  485. // Set the apex poly/point to the end point.
  486. NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  487. const Vector2 back_edge_closest_point = Geometry2D::get_closest_point_to_segment(end_point, apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end);
  488. if (end_point.is_equal_approx(back_edge_closest_point)) {
  489. // The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
  490. // At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
  491. if (apex_poly->back_navigation_poly_id != -1) {
  492. apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
  493. }
  494. }
  495. Vector2 apex_point = end_point;
  496. NavigationPoly *left_poly = apex_poly;
  497. Vector2 left_portal = apex_point;
  498. NavigationPoly *right_poly = apex_poly;
  499. Vector2 right_portal = apex_point;
  500. NavigationPoly *p = apex_poly;
  501. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  502. while (p) {
  503. // Set left and right points of the pathway between polygons.
  504. Vector2 left = p->back_navigation_edge_pathway_start;
  505. Vector2 right = p->back_navigation_edge_pathway_end;
  506. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right) < 0) {
  507. SWAP(left, right);
  508. }
  509. bool skip = false;
  510. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left) >= 0) {
  511. // Process.
  512. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal) > 0) {
  513. left_poly = p;
  514. left_portal = left;
  515. } else {
  516. _query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);
  517. apex_point = right_portal;
  518. p = right_poly;
  519. left_poly = p;
  520. apex_poly = p;
  521. left_portal = apex_point;
  522. right_portal = apex_point;
  523. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  524. skip = true;
  525. }
  526. }
  527. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right) <= 0) {
  528. // Process.
  529. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal) < 0) {
  530. right_poly = p;
  531. right_portal = right;
  532. } else {
  533. _query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);
  534. apex_point = left_portal;
  535. p = left_poly;
  536. right_poly = p;
  537. apex_poly = p;
  538. right_portal = apex_point;
  539. left_portal = apex_point;
  540. _query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
  541. }
  542. }
  543. // Go to the previous polygon.
  544. if (p->back_navigation_poly_id != -1) {
  545. p = &navigation_polys[p->back_navigation_poly_id];
  546. } else {
  547. // The end
  548. p = nullptr;
  549. }
  550. }
  551. // If the last point is not the begin point, add it to the list.
  552. if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {
  553. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  554. }
  555. }
  556. void NavMeshQueries2D::_query_task_post_process_edgecentered(NavMeshPathQueryTask2D &p_query_task) {
  557. Vector2 end_point = p_query_task.end_position;
  558. const Polygon *end_poly = p_query_task.end_polygon;
  559. Vector2 begin_point = p_query_task.begin_position;
  560. const Polygon *begin_poly = p_query_task.begin_polygon;
  561. uint32_t least_cost_id = p_query_task.least_cost_id;
  562. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  563. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  564. // Add mid points.
  565. int np_id = least_cost_id;
  566. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  567. if (navigation_polys[np_id].back_navigation_edge != -1) {
  568. int prev = navigation_polys[np_id].back_navigation_edge;
  569. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->vertices.size();
  570. Vector2 point = (navigation_polys[np_id].poly->vertices[prev] + navigation_polys[np_id].poly->vertices[prev_n]) * 0.5;
  571. _query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);
  572. } else {
  573. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  574. }
  575. np_id = navigation_polys[np_id].back_navigation_poly_id;
  576. }
  577. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  578. }
  579. void NavMeshQueries2D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask2D &p_query_task) {
  580. Vector2 end_point = p_query_task.end_position;
  581. const Polygon *end_poly = p_query_task.end_polygon;
  582. Vector2 begin_point = p_query_task.begin_position;
  583. const Polygon *begin_poly = p_query_task.begin_polygon;
  584. uint32_t least_cost_id = p_query_task.least_cost_id;
  585. LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
  586. _query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
  587. // Add mid points.
  588. int np_id = least_cost_id;
  589. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  590. _query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
  591. np_id = navigation_polys[np_id].back_navigation_poly_id;
  592. }
  593. _query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
  594. }
  595. Vector2 NavMeshQueries2D::map_iteration_get_closest_point(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  596. ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  597. return cp.point;
  598. }
  599. RID NavMeshQueries2D::map_iteration_get_closest_point_owner(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  600. ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
  601. return cp.owner;
  602. }
  603. ClosestPointQueryResult NavMeshQueries2D::map_iteration_get_closest_point_info(const NavMapIteration2D &p_map_iteration, const Vector2 &p_point) {
  604. ClosestPointQueryResult result;
  605. real_t closest_point_distance_squared = FLT_MAX;
  606. // TODO: Check for further 2D improvements.
  607. const LocalVector<NavRegionIteration2D> &regions = p_map_iteration.region_iterations;
  608. for (const NavRegionIteration2D &region : regions) {
  609. for (const Polygon &polygon : region.get_navmesh_polygons()) {
  610. real_t cross = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);
  611. Vector2 closest_on_polygon;
  612. real_t closest = FLT_MAX;
  613. bool inside = true;
  614. Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];
  615. for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {
  616. Vector2 edge = polygon.vertices[point_id] - previous;
  617. Vector2 to_point = p_point - previous;
  618. real_t edge_to_point_cross = edge.cross(to_point);
  619. bool clockwise = (edge_to_point_cross * cross) > 0;
  620. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  621. if (!clockwise) {
  622. inside = false;
  623. real_t point_projected_on_edge = edge.dot(to_point);
  624. real_t edge_square = edge.length_squared();
  625. if (point_projected_on_edge > edge_square) {
  626. real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);
  627. if (distance < closest) {
  628. closest_on_polygon = polygon.vertices[point_id];
  629. closest = distance;
  630. }
  631. } else if (point_projected_on_edge < 0.0) {
  632. real_t distance = previous.distance_squared_to(p_point);
  633. if (distance < closest) {
  634. closest_on_polygon = previous;
  635. closest = distance;
  636. }
  637. } else {
  638. // If we project on this edge, this will be the closest point.
  639. real_t percent = point_projected_on_edge / edge_square;
  640. closest_on_polygon = previous + percent * edge;
  641. break;
  642. }
  643. }
  644. previous = polygon.vertices[point_id];
  645. }
  646. if (inside) {
  647. closest_point_distance_squared = 0.0;
  648. result.point = p_point;
  649. result.owner = polygon.owner->get_self();
  650. break;
  651. } else {
  652. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  653. if (distance < closest_point_distance_squared) {
  654. closest_point_distance_squared = distance;
  655. result.point = closest_on_polygon;
  656. result.owner = polygon.owner->get_self();
  657. }
  658. }
  659. }
  660. }
  661. return result;
  662. }
  663. Vector2 NavMeshQueries2D::map_iteration_get_random_point(const NavMapIteration2D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {
  664. if (p_map_iteration.region_iterations.is_empty()) {
  665. return Vector2();
  666. }
  667. LocalVector<uint32_t> accessible_regions;
  668. accessible_regions.reserve(p_map_iteration.region_iterations.size());
  669. for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {
  670. const NavRegionIteration2D &region = p_map_iteration.region_iterations[i];
  671. if (!region.enabled || (p_navigation_layers & region.navigation_layers) == 0) {
  672. continue;
  673. }
  674. accessible_regions.push_back(i);
  675. }
  676. if (accessible_regions.is_empty()) {
  677. // All existing region polygons are disabled.
  678. return Vector2();
  679. }
  680. if (p_uniformly) {
  681. real_t accumulated_region_surface_area = 0;
  682. RBMap<real_t, uint32_t> accessible_regions_area_map;
  683. for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
  684. const NavRegionIteration2D &region = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];
  685. real_t region_surface_area = region.surface_area;
  686. if (region_surface_area == 0.0f) {
  687. continue;
  688. }
  689. accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
  690. accumulated_region_surface_area += region_surface_area;
  691. }
  692. if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
  693. // All faces have no real surface / no area.
  694. return Vector2();
  695. }
  696. real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
  697. RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
  698. ERR_FAIL_COND_V(!E, Vector2());
  699. uint32_t random_region_index = E->value;
  700. ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector2());
  701. const NavRegionIteration2D &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  702. return NavMeshQueries2D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  703. } else {
  704. uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
  705. const NavRegionIteration2D &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
  706. return NavMeshQueries2D::polygons_get_random_point(random_region.navmesh_polygons, p_navigation_layers, p_uniformly);
  707. }
  708. }
  709. Vector2 NavMeshQueries2D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  710. ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  711. return cp.point;
  712. }
  713. ClosestPointQueryResult NavMeshQueries2D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  714. ClosestPointQueryResult result;
  715. real_t closest_point_distance_squared = FLT_MAX;
  716. // TODO: Check for further 2D improvements.
  717. for (const Polygon &polygon : p_polygons) {
  718. real_t cross = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);
  719. Vector2 closest_on_polygon;
  720. real_t closest = FLT_MAX;
  721. bool inside = true;
  722. Vector2 previous = polygon.vertices[polygon.vertices.size() - 1];
  723. for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {
  724. Vector2 edge = polygon.vertices[point_id] - previous;
  725. Vector2 to_point = p_point - previous;
  726. real_t edge_to_point_cross = edge.cross(to_point);
  727. bool clockwise = (edge_to_point_cross * cross) > 0;
  728. // If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
  729. if (!clockwise) {
  730. inside = false;
  731. real_t point_projected_on_edge = edge.dot(to_point);
  732. real_t edge_square = edge.length_squared();
  733. if (point_projected_on_edge > edge_square) {
  734. real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);
  735. if (distance < closest) {
  736. closest_on_polygon = polygon.vertices[point_id];
  737. closest = distance;
  738. }
  739. } else if (point_projected_on_edge < 0.0) {
  740. real_t distance = previous.distance_squared_to(p_point);
  741. if (distance < closest) {
  742. closest_on_polygon = previous;
  743. closest = distance;
  744. }
  745. } else {
  746. // If we project on this edge, this will be the closest point.
  747. real_t percent = point_projected_on_edge / edge_square;
  748. closest_on_polygon = previous + percent * edge;
  749. break;
  750. }
  751. }
  752. previous = polygon.vertices[point_id];
  753. }
  754. if (inside) {
  755. closest_point_distance_squared = 0.0;
  756. result.point = p_point;
  757. result.owner = polygon.owner->get_self();
  758. break;
  759. } else {
  760. real_t distance = closest_on_polygon.distance_squared_to(p_point);
  761. if (distance < closest_point_distance_squared) {
  762. closest_point_distance_squared = distance;
  763. result.point = closest_on_polygon;
  764. result.owner = polygon.owner->get_self();
  765. }
  766. }
  767. }
  768. return result;
  769. }
  770. RID NavMeshQueries2D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector2 &p_point) {
  771. ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
  772. return cp.owner;
  773. }
  774. 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) {
  775. Vector2 segment = p_segment_begin - p_segment_end;
  776. real_t den = p_line_normal.dot(segment);
  777. if (Math::is_zero_approx(den)) {
  778. return false;
  779. }
  780. real_t dist = (p_line_normal.dot(p_segment_begin) - p_line_d) / den;
  781. if (dist < (real_t)-CMP_EPSILON || dist > (1.0 + (real_t)CMP_EPSILON)) {
  782. return false;
  783. }
  784. r_intersection = p_segment_begin - segment * dist;
  785. return true;
  786. }
  787. 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) {
  788. Vector2 from = p_query_task.path_points[p_query_task.path_points.size() - 1];
  789. const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;
  790. if (from.is_equal_approx(p_to_point)) {
  791. return;
  792. }
  793. // Compute line parameters (equivalent to the Plane case in 3D).
  794. const Vector2 normal = -(from - p_to_point).orthogonal().normalized();
  795. const real_t d = normal.dot(from);
  796. while (p_from_poly != p_to_poly) {
  797. Vector2 pathway_start = p_from_poly->back_navigation_edge_pathway_start;
  798. Vector2 pathway_end = p_from_poly->back_navigation_edge_pathway_end;
  799. ERR_FAIL_COND(p_from_poly->back_navigation_poly_id == -1);
  800. p_from_poly = &p_navigation_polys[p_from_poly->back_navigation_poly_id];
  801. if (!pathway_start.is_equal_approx(pathway_end)) {
  802. Vector2 inters;
  803. if (_line_intersects_segment(normal, d, pathway_start, pathway_end, inters)) {
  804. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {
  805. _query_task_push_back_point_with_metadata(p_query_task, inters, p_from_poly->poly);
  806. }
  807. }
  808. }
  809. }
  810. }
  811. bool NavMeshQueries2D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask2D &p_query_task, const NavBaseIteration2D *p_owner) {
  812. bool owner_usable = true;
  813. if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {
  814. // Not usable. No matching bit between task filter bitmask and owner bitmask.
  815. owner_usable = false;
  816. return owner_usable;
  817. }
  818. if (p_query_task.exclude_regions || p_query_task.include_regions) {
  819. switch (p_owner->get_type()) {
  820. case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {
  821. if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {
  822. // Not usable. Exclude region filter is active and this region is excluded.
  823. owner_usable = false;
  824. } else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {
  825. // Not usable. Include region filter is active and this region is not included.
  826. owner_usable = false;
  827. }
  828. } break;
  829. case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {
  830. const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();
  831. if (link_polygons.size() != 2) {
  832. // Not usable. Whatever this is, it is not a valid connected link.
  833. owner_usable = false;
  834. } else {
  835. const RID link_start_region = link_polygons[0].owner->get_self();
  836. const RID link_end_region = link_polygons[1].owner->get_self();
  837. if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {
  838. // Not usable. Exclude region filter is active and at least one region of the link is excluded.
  839. owner_usable = false;
  840. }
  841. if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {
  842. // Not usable. Include region filter is active and not both regions of the links are included.
  843. owner_usable = false;
  844. }
  845. }
  846. } break;
  847. }
  848. }
  849. return owner_usable;
  850. }
  851. LocalVector<uint32_t> NavMeshQueries2D::get_simplified_path_indices(const LocalVector<Vector2> &p_path, real_t p_epsilon) {
  852. p_epsilon = MAX(0.0, p_epsilon);
  853. real_t squared_epsilon = p_epsilon * p_epsilon;
  854. LocalVector<uint32_t> simplified_path_indices;
  855. simplified_path_indices.reserve(p_path.size());
  856. simplified_path_indices.push_back(0);
  857. simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);
  858. simplified_path_indices.push_back(p_path.size() - 1);
  859. return simplified_path_indices;
  860. }
  861. 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) {
  862. real_t point_max_distance = 0.0;
  863. int point_max_index = 0;
  864. for (int i = p_start_inx; i < p_end_inx; i++) {
  865. const Vector2 &checked_point = p_points[i];
  866. const Vector2 closest_point = Geometry2D::get_closest_point_to_segment(checked_point, p_points[p_start_inx], p_points[p_end_inx]);
  867. real_t distance_squared = closest_point.distance_squared_to(checked_point);
  868. if (distance_squared > point_max_distance) {
  869. point_max_index = i;
  870. point_max_distance = distance_squared;
  871. }
  872. }
  873. if (point_max_distance > p_epsilon) {
  874. simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);
  875. r_simplified_path_indices.push_back(point_max_index);
  876. simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);
  877. }
  878. }