nav_map.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /**************************************************************************/
  2. /* nav_map.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_map.h"
  31. #include "nav_agent.h"
  32. #include "nav_link.h"
  33. #include "nav_obstacle.h"
  34. #include "nav_region.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/object/worker_thread_pool.h"
  37. #include <Obstacle2d.h>
  38. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  39. // Helper macro
  40. #define APPEND_METADATA(poly) \
  41. if (r_path_types) { \
  42. r_path_types->push_back(poly->owner->get_type()); \
  43. } \
  44. if (r_path_rids) { \
  45. r_path_rids->push_back(poly->owner->get_self()); \
  46. } \
  47. if (r_path_owners) { \
  48. r_path_owners->push_back(poly->owner->get_owner_id()); \
  49. }
  50. #ifdef DEBUG_ENABLED
  51. #define NAVMAP_ITERATION_ZERO_ERROR_MSG() \
  52. ERR_PRINT_ONCE("NavigationServer navigation map query failed because it was made before first map synchronization.\n\
  53. NavigationServer 'map_changed' signal can be used to receive update notifications.\n\
  54. NavigationServer 'map_get_iteration_id()' can be used to check if a map has finished its newest iteration.");
  55. #else
  56. #define NAVMAP_ITERATION_ZERO_ERROR_MSG()
  57. #endif // DEBUG_ENABLED
  58. void NavMap::set_up(Vector3 p_up) {
  59. if (up == p_up) {
  60. return;
  61. }
  62. up = p_up;
  63. regenerate_polygons = true;
  64. }
  65. void NavMap::set_cell_size(real_t p_cell_size) {
  66. if (cell_size == p_cell_size) {
  67. return;
  68. }
  69. cell_size = p_cell_size;
  70. _update_merge_rasterizer_cell_dimensions();
  71. regenerate_polygons = true;
  72. }
  73. void NavMap::set_cell_height(real_t p_cell_height) {
  74. if (cell_height == p_cell_height) {
  75. return;
  76. }
  77. cell_height = p_cell_height;
  78. _update_merge_rasterizer_cell_dimensions();
  79. regenerate_polygons = true;
  80. }
  81. void NavMap::set_merge_rasterizer_cell_scale(float p_value) {
  82. if (merge_rasterizer_cell_scale == p_value) {
  83. return;
  84. }
  85. merge_rasterizer_cell_scale = p_value;
  86. _update_merge_rasterizer_cell_dimensions();
  87. regenerate_polygons = true;
  88. }
  89. void NavMap::set_use_edge_connections(bool p_enabled) {
  90. if (use_edge_connections == p_enabled) {
  91. return;
  92. }
  93. use_edge_connections = p_enabled;
  94. regenerate_links = true;
  95. }
  96. void NavMap::set_edge_connection_margin(real_t p_edge_connection_margin) {
  97. if (edge_connection_margin == p_edge_connection_margin) {
  98. return;
  99. }
  100. edge_connection_margin = p_edge_connection_margin;
  101. regenerate_links = true;
  102. }
  103. void NavMap::set_link_connection_radius(real_t p_link_connection_radius) {
  104. if (link_connection_radius == p_link_connection_radius) {
  105. return;
  106. }
  107. link_connection_radius = p_link_connection_radius;
  108. regenerate_links = true;
  109. }
  110. gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
  111. const int x = static_cast<int>(Math::floor(p_pos.x / merge_rasterizer_cell_size));
  112. const int y = static_cast<int>(Math::floor(p_pos.y / merge_rasterizer_cell_height));
  113. const int z = static_cast<int>(Math::floor(p_pos.z / merge_rasterizer_cell_size));
  114. gd::PointKey p;
  115. p.key = 0;
  116. p.x = x;
  117. p.y = y;
  118. p.z = z;
  119. return p;
  120. }
  121. Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_navigation_layers, Vector<int32_t> *r_path_types, TypedArray<RID> *r_path_rids, Vector<int64_t> *r_path_owners) const {
  122. RWLockRead read_lock(map_rwlock);
  123. if (iteration_id == 0) {
  124. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  125. return Vector<Vector3>();
  126. }
  127. // Clear metadata outputs.
  128. if (r_path_types) {
  129. r_path_types->clear();
  130. }
  131. if (r_path_rids) {
  132. r_path_rids->clear();
  133. }
  134. if (r_path_owners) {
  135. r_path_owners->clear();
  136. }
  137. // Find the start poly and the end poly on this map.
  138. const gd::Polygon *begin_poly = nullptr;
  139. const gd::Polygon *end_poly = nullptr;
  140. Vector3 begin_point;
  141. Vector3 end_point;
  142. real_t begin_d = FLT_MAX;
  143. real_t end_d = FLT_MAX;
  144. // Find the initial poly and the end poly on this map.
  145. for (const gd::Polygon &p : polygons) {
  146. // Only consider the polygon if it in a region with compatible layers.
  147. if ((p_navigation_layers & p.owner->get_navigation_layers()) == 0) {
  148. continue;
  149. }
  150. // For each face check the distance between the origin/destination
  151. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  152. const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  153. Vector3 point = face.get_closest_point_to(p_origin);
  154. real_t distance_to_point = point.distance_to(p_origin);
  155. if (distance_to_point < begin_d) {
  156. begin_d = distance_to_point;
  157. begin_poly = &p;
  158. begin_point = point;
  159. }
  160. point = face.get_closest_point_to(p_destination);
  161. distance_to_point = point.distance_to(p_destination);
  162. if (distance_to_point < end_d) {
  163. end_d = distance_to_point;
  164. end_poly = &p;
  165. end_point = point;
  166. }
  167. }
  168. }
  169. // Check for trivial cases
  170. if (!begin_poly || !end_poly) {
  171. return Vector<Vector3>();
  172. }
  173. if (begin_poly == end_poly) {
  174. if (r_path_types) {
  175. r_path_types->resize(2);
  176. r_path_types->write[0] = begin_poly->owner->get_type();
  177. r_path_types->write[1] = end_poly->owner->get_type();
  178. }
  179. if (r_path_rids) {
  180. r_path_rids->resize(2);
  181. (*r_path_rids)[0] = begin_poly->owner->get_self();
  182. (*r_path_rids)[1] = end_poly->owner->get_self();
  183. }
  184. if (r_path_owners) {
  185. r_path_owners->resize(2);
  186. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  187. r_path_owners->write[1] = end_poly->owner->get_owner_id();
  188. }
  189. Vector<Vector3> path;
  190. path.resize(2);
  191. path.write[0] = begin_point;
  192. path.write[1] = end_point;
  193. return path;
  194. }
  195. // List of all reachable navigation polys.
  196. LocalVector<gd::NavigationPoly> navigation_polys;
  197. navigation_polys.reserve(polygons.size() * 0.75);
  198. // Add the start polygon to the reachable navigation polygons.
  199. gd::NavigationPoly begin_navigation_poly = gd::NavigationPoly(begin_poly);
  200. begin_navigation_poly.self_id = 0;
  201. begin_navigation_poly.entry = begin_point;
  202. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  203. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  204. navigation_polys.push_back(begin_navigation_poly);
  205. // List of polygon IDs to visit.
  206. List<uint32_t> to_visit;
  207. to_visit.push_back(0);
  208. // This is an implementation of the A* algorithm.
  209. int least_cost_id = 0;
  210. int prev_least_cost_id = -1;
  211. bool found_route = false;
  212. const gd::Polygon *reachable_end = nullptr;
  213. real_t reachable_d = FLT_MAX;
  214. bool is_reachable = true;
  215. while (true) {
  216. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  217. for (const gd::Edge &edge : navigation_polys[least_cost_id].poly->edges) {
  218. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  219. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  220. const gd::Edge::Connection &connection = edge.connections[connection_index];
  221. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  222. if ((p_navigation_layers & connection.polygon->owner->get_navigation_layers()) == 0) {
  223. continue;
  224. }
  225. const gd::NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
  226. real_t poly_enter_cost = 0.0;
  227. real_t poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost();
  228. if (prev_least_cost_id != -1 && (navigation_polys[prev_least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self())) {
  229. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  230. }
  231. prev_least_cost_id = least_cost_id;
  232. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  233. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly.entry, pathway);
  234. const real_t new_distance = (least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost) + poly_enter_cost + least_cost_poly.traveled_distance;
  235. int64_t already_visited_polygon_index = navigation_polys.find(gd::NavigationPoly(connection.polygon));
  236. if (already_visited_polygon_index != -1) {
  237. // Polygon already visited, check if we can reduce the travel cost.
  238. gd::NavigationPoly &avp = navigation_polys[already_visited_polygon_index];
  239. if (new_distance < avp.traveled_distance) {
  240. avp.back_navigation_poly_id = least_cost_id;
  241. avp.back_navigation_edge = connection.edge;
  242. avp.back_navigation_edge_pathway_start = connection.pathway_start;
  243. avp.back_navigation_edge_pathway_end = connection.pathway_end;
  244. avp.traveled_distance = new_distance;
  245. avp.entry = new_entry;
  246. }
  247. } else {
  248. // Add the neighbor polygon to the reachable ones.
  249. gd::NavigationPoly new_navigation_poly = gd::NavigationPoly(connection.polygon);
  250. new_navigation_poly.self_id = navigation_polys.size();
  251. new_navigation_poly.back_navigation_poly_id = least_cost_id;
  252. new_navigation_poly.back_navigation_edge = connection.edge;
  253. new_navigation_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  254. new_navigation_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  255. new_navigation_poly.traveled_distance = new_distance;
  256. new_navigation_poly.entry = new_entry;
  257. navigation_polys.push_back(new_navigation_poly);
  258. // Add the neighbor polygon to the polygons to visit.
  259. to_visit.push_back(navigation_polys.size() - 1);
  260. }
  261. }
  262. }
  263. // Removes the least cost polygon from the list of polygons to visit so we can advance.
  264. to_visit.erase(least_cost_id);
  265. // When the list of polygons to visit is empty at this point it means the End Polygon is not reachable
  266. if (to_visit.size() == 0) {
  267. // Thus use the further reachable polygon
  268. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  269. is_reachable = false;
  270. if (reachable_end == nullptr) {
  271. // The path is not found and there is not a way out.
  272. break;
  273. }
  274. // Set as end point the furthest reachable point.
  275. end_poly = reachable_end;
  276. end_d = FLT_MAX;
  277. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  278. Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  279. Vector3 spoint = f.get_closest_point_to(p_destination);
  280. real_t dpoint = spoint.distance_to(p_destination);
  281. if (dpoint < end_d) {
  282. end_point = spoint;
  283. end_d = dpoint;
  284. }
  285. }
  286. // Search all faces of start polygon as well.
  287. bool closest_point_on_start_poly = false;
  288. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  289. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  290. Vector3 spoint = f.get_closest_point_to(p_destination);
  291. real_t dpoint = spoint.distance_to(p_destination);
  292. if (dpoint < end_d) {
  293. end_point = spoint;
  294. end_d = dpoint;
  295. closest_point_on_start_poly = true;
  296. }
  297. }
  298. if (closest_point_on_start_poly) {
  299. // No point to run PostProcessing when start and end convex polygon is the same.
  300. if (r_path_types) {
  301. r_path_types->resize(2);
  302. r_path_types->write[0] = begin_poly->owner->get_type();
  303. r_path_types->write[1] = begin_poly->owner->get_type();
  304. }
  305. if (r_path_rids) {
  306. r_path_rids->resize(2);
  307. (*r_path_rids)[0] = begin_poly->owner->get_self();
  308. (*r_path_rids)[1] = begin_poly->owner->get_self();
  309. }
  310. if (r_path_owners) {
  311. r_path_owners->resize(2);
  312. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  313. r_path_owners->write[1] = begin_poly->owner->get_owner_id();
  314. }
  315. Vector<Vector3> path;
  316. path.resize(2);
  317. path.write[0] = begin_point;
  318. path.write[1] = end_point;
  319. return path;
  320. }
  321. // Reset open and navigation_polys
  322. gd::NavigationPoly np = navigation_polys[0];
  323. navigation_polys.clear();
  324. navigation_polys.push_back(np);
  325. to_visit.clear();
  326. to_visit.push_back(0);
  327. least_cost_id = 0;
  328. prev_least_cost_id = -1;
  329. reachable_end = nullptr;
  330. continue;
  331. }
  332. // Find the polygon with the minimum cost from the list of polygons to visit.
  333. least_cost_id = -1;
  334. real_t least_cost = FLT_MAX;
  335. for (List<uint32_t>::Element *element = to_visit.front(); element != nullptr; element = element->next()) {
  336. gd::NavigationPoly *np = &navigation_polys[element->get()];
  337. real_t cost = np->traveled_distance;
  338. cost += (np->entry.distance_to(end_point) * np->poly->owner->get_travel_cost());
  339. if (cost < least_cost) {
  340. least_cost_id = np->self_id;
  341. least_cost = cost;
  342. }
  343. }
  344. ERR_BREAK(least_cost_id == -1);
  345. // Stores the further reachable end polygon, in case our goal is not reachable.
  346. if (is_reachable) {
  347. real_t d = navigation_polys[least_cost_id].entry.distance_to(p_destination);
  348. if (reachable_d > d) {
  349. reachable_d = d;
  350. reachable_end = navigation_polys[least_cost_id].poly;
  351. }
  352. }
  353. // Check if we reached the end
  354. if (navigation_polys[least_cost_id].poly == end_poly) {
  355. found_route = true;
  356. break;
  357. }
  358. }
  359. // We did not find a route but we have both a start polygon and an end polygon at this point.
  360. // 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.
  361. if (!found_route) {
  362. end_d = FLT_MAX;
  363. // Search all faces of the start polygon for the closest point to our target position.
  364. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  365. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  366. Vector3 spoint = f.get_closest_point_to(p_destination);
  367. real_t dpoint = spoint.distance_to(p_destination);
  368. if (dpoint < end_d) {
  369. end_point = spoint;
  370. end_d = dpoint;
  371. }
  372. }
  373. if (r_path_types) {
  374. r_path_types->resize(2);
  375. r_path_types->write[0] = begin_poly->owner->get_type();
  376. r_path_types->write[1] = begin_poly->owner->get_type();
  377. }
  378. if (r_path_rids) {
  379. r_path_rids->resize(2);
  380. (*r_path_rids)[0] = begin_poly->owner->get_self();
  381. (*r_path_rids)[1] = begin_poly->owner->get_self();
  382. }
  383. if (r_path_owners) {
  384. r_path_owners->resize(2);
  385. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  386. r_path_owners->write[1] = begin_poly->owner->get_owner_id();
  387. }
  388. Vector<Vector3> path;
  389. path.resize(2);
  390. path.write[0] = begin_point;
  391. path.write[1] = end_point;
  392. return path;
  393. }
  394. Vector<Vector3> path;
  395. // Optimize the path.
  396. if (p_optimize) {
  397. // Set the apex poly/point to the end point
  398. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  399. Vector3 back_pathway[2] = { apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end };
  400. const Vector3 back_edge_closest_point = Geometry3D::get_closest_point_to_segment(end_point, back_pathway);
  401. if (end_point.is_equal_approx(back_edge_closest_point)) {
  402. // The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
  403. // At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
  404. if (apex_poly->back_navigation_poly_id != -1) {
  405. apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
  406. }
  407. }
  408. Vector3 apex_point = end_point;
  409. gd::NavigationPoly *left_poly = apex_poly;
  410. Vector3 left_portal = apex_point;
  411. gd::NavigationPoly *right_poly = apex_poly;
  412. Vector3 right_portal = apex_point;
  413. gd::NavigationPoly *p = apex_poly;
  414. path.push_back(end_point);
  415. APPEND_METADATA(end_poly);
  416. while (p) {
  417. // Set left and right points of the pathway between polygons.
  418. Vector3 left = p->back_navigation_edge_pathway_start;
  419. Vector3 right = p->back_navigation_edge_pathway_end;
  420. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(up) < 0) {
  421. SWAP(left, right);
  422. }
  423. bool skip = false;
  424. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(up) >= 0) {
  425. //process
  426. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(up) > 0) {
  427. left_poly = p;
  428. left_portal = left;
  429. } else {
  430. clip_path(navigation_polys, path, apex_poly, right_portal, right_poly, r_path_types, r_path_rids, r_path_owners);
  431. apex_point = right_portal;
  432. p = right_poly;
  433. left_poly = p;
  434. apex_poly = p;
  435. left_portal = apex_point;
  436. right_portal = apex_point;
  437. path.push_back(apex_point);
  438. APPEND_METADATA(apex_poly->poly);
  439. skip = true;
  440. }
  441. }
  442. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(up) <= 0) {
  443. //process
  444. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(up) < 0) {
  445. right_poly = p;
  446. right_portal = right;
  447. } else {
  448. clip_path(navigation_polys, path, apex_poly, left_portal, left_poly, r_path_types, r_path_rids, r_path_owners);
  449. apex_point = left_portal;
  450. p = left_poly;
  451. right_poly = p;
  452. apex_poly = p;
  453. right_portal = apex_point;
  454. left_portal = apex_point;
  455. path.push_back(apex_point);
  456. APPEND_METADATA(apex_poly->poly);
  457. }
  458. }
  459. // Go to the previous polygon.
  460. if (p->back_navigation_poly_id != -1) {
  461. p = &navigation_polys[p->back_navigation_poly_id];
  462. } else {
  463. // The end
  464. p = nullptr;
  465. }
  466. }
  467. // If the last point is not the begin point, add it to the list.
  468. if (path[path.size() - 1] != begin_point) {
  469. path.push_back(begin_point);
  470. APPEND_METADATA(begin_poly);
  471. }
  472. path.reverse();
  473. if (r_path_types) {
  474. r_path_types->reverse();
  475. }
  476. if (r_path_rids) {
  477. r_path_rids->reverse();
  478. }
  479. if (r_path_owners) {
  480. r_path_owners->reverse();
  481. }
  482. } else {
  483. path.push_back(end_point);
  484. APPEND_METADATA(end_poly);
  485. // Add mid points
  486. int np_id = least_cost_id;
  487. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  488. if (navigation_polys[np_id].back_navigation_edge != -1) {
  489. int prev = navigation_polys[np_id].back_navigation_edge;
  490. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  491. Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  492. path.push_back(point);
  493. APPEND_METADATA(navigation_polys[np_id].poly);
  494. } else {
  495. path.push_back(navigation_polys[np_id].entry);
  496. APPEND_METADATA(navigation_polys[np_id].poly);
  497. }
  498. np_id = navigation_polys[np_id].back_navigation_poly_id;
  499. }
  500. path.push_back(begin_point);
  501. APPEND_METADATA(begin_poly);
  502. path.reverse();
  503. if (r_path_types) {
  504. r_path_types->reverse();
  505. }
  506. if (r_path_rids) {
  507. r_path_rids->reverse();
  508. }
  509. if (r_path_owners) {
  510. r_path_owners->reverse();
  511. }
  512. }
  513. // Ensure post conditions (path arrays MUST match in size).
  514. CRASH_COND(r_path_types && path.size() != r_path_types->size());
  515. CRASH_COND(r_path_rids && path.size() != r_path_rids->size());
  516. CRASH_COND(r_path_owners && path.size() != r_path_owners->size());
  517. return path;
  518. }
  519. Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
  520. RWLockRead read_lock(map_rwlock);
  521. if (iteration_id == 0) {
  522. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  523. return Vector3();
  524. }
  525. bool use_collision = p_use_collision;
  526. Vector3 closest_point;
  527. real_t closest_point_d = FLT_MAX;
  528. for (const gd::Polygon &p : polygons) {
  529. // For each face check the distance to the segment
  530. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  531. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  532. Vector3 inters;
  533. if (f.intersects_segment(p_from, p_to, &inters)) {
  534. const real_t d = closest_point_d = p_from.distance_to(inters);
  535. if (use_collision == false) {
  536. closest_point = inters;
  537. use_collision = true;
  538. closest_point_d = d;
  539. } else if (closest_point_d > d) {
  540. closest_point = inters;
  541. closest_point_d = d;
  542. }
  543. }
  544. }
  545. if (use_collision == false) {
  546. for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
  547. Vector3 a, b;
  548. Geometry3D::get_closest_points_between_segments(
  549. p_from,
  550. p_to,
  551. p.points[point_id].pos,
  552. p.points[(point_id + 1) % p.points.size()].pos,
  553. a,
  554. b);
  555. const real_t d = a.distance_to(b);
  556. if (d < closest_point_d) {
  557. closest_point_d = d;
  558. closest_point = b;
  559. }
  560. }
  561. }
  562. }
  563. return closest_point;
  564. }
  565. Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
  566. RWLockRead read_lock(map_rwlock);
  567. if (iteration_id == 0) {
  568. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  569. return Vector3();
  570. }
  571. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  572. return cp.point;
  573. }
  574. Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
  575. RWLockRead read_lock(map_rwlock);
  576. if (iteration_id == 0) {
  577. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  578. return Vector3();
  579. }
  580. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  581. return cp.normal;
  582. }
  583. RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
  584. RWLockRead read_lock(map_rwlock);
  585. if (iteration_id == 0) {
  586. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  587. return RID();
  588. }
  589. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  590. return cp.owner;
  591. }
  592. gd::ClosestPointQueryResult NavMap::get_closest_point_info(const Vector3 &p_point) const {
  593. RWLockRead read_lock(map_rwlock);
  594. gd::ClosestPointQueryResult result;
  595. real_t closest_point_ds = FLT_MAX;
  596. for (const gd::Polygon &p : polygons) {
  597. // For each face check the distance to the point
  598. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  599. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  600. const Vector3 inters = f.get_closest_point_to(p_point);
  601. const real_t ds = inters.distance_squared_to(p_point);
  602. if (ds < closest_point_ds) {
  603. result.point = inters;
  604. result.normal = f.get_plane().normal;
  605. result.owner = p.owner->get_self();
  606. closest_point_ds = ds;
  607. }
  608. }
  609. }
  610. return result;
  611. }
  612. void NavMap::add_region(NavRegion *p_region) {
  613. regions.push_back(p_region);
  614. regenerate_links = true;
  615. }
  616. void NavMap::remove_region(NavRegion *p_region) {
  617. int64_t region_index = regions.find(p_region);
  618. if (region_index >= 0) {
  619. regions.remove_at_unordered(region_index);
  620. regenerate_links = true;
  621. }
  622. }
  623. void NavMap::add_link(NavLink *p_link) {
  624. links.push_back(p_link);
  625. regenerate_links = true;
  626. }
  627. void NavMap::remove_link(NavLink *p_link) {
  628. int64_t link_index = links.find(p_link);
  629. if (link_index >= 0) {
  630. links.remove_at_unordered(link_index);
  631. regenerate_links = true;
  632. }
  633. }
  634. bool NavMap::has_agent(NavAgent *agent) const {
  635. return (agents.find(agent) >= 0);
  636. }
  637. void NavMap::add_agent(NavAgent *agent) {
  638. if (!has_agent(agent)) {
  639. agents.push_back(agent);
  640. agents_dirty = true;
  641. }
  642. }
  643. void NavMap::remove_agent(NavAgent *agent) {
  644. remove_agent_as_controlled(agent);
  645. int64_t agent_index = agents.find(agent);
  646. if (agent_index >= 0) {
  647. agents.remove_at_unordered(agent_index);
  648. agents_dirty = true;
  649. }
  650. }
  651. bool NavMap::has_obstacle(NavObstacle *obstacle) const {
  652. return (obstacles.find(obstacle) >= 0);
  653. }
  654. void NavMap::add_obstacle(NavObstacle *obstacle) {
  655. if (obstacle->get_paused()) {
  656. // No point in adding a paused obstacle, it will add itself when unpaused again.
  657. return;
  658. }
  659. if (!has_obstacle(obstacle)) {
  660. obstacles.push_back(obstacle);
  661. obstacles_dirty = true;
  662. }
  663. }
  664. void NavMap::remove_obstacle(NavObstacle *obstacle) {
  665. int64_t obstacle_index = obstacles.find(obstacle);
  666. if (obstacle_index >= 0) {
  667. obstacles.remove_at_unordered(obstacle_index);
  668. obstacles_dirty = true;
  669. }
  670. }
  671. void NavMap::set_agent_as_controlled(NavAgent *agent) {
  672. remove_agent_as_controlled(agent);
  673. if (agent->get_paused()) {
  674. // No point in adding a paused agent, it will add itself when unpaused again.
  675. return;
  676. }
  677. if (agent->get_use_3d_avoidance()) {
  678. int64_t agent_3d_index = active_3d_avoidance_agents.find(agent);
  679. if (agent_3d_index < 0) {
  680. active_3d_avoidance_agents.push_back(agent);
  681. agents_dirty = true;
  682. }
  683. } else {
  684. int64_t agent_2d_index = active_2d_avoidance_agents.find(agent);
  685. if (agent_2d_index < 0) {
  686. active_2d_avoidance_agents.push_back(agent);
  687. agents_dirty = true;
  688. }
  689. }
  690. }
  691. void NavMap::remove_agent_as_controlled(NavAgent *agent) {
  692. int64_t agent_3d_index = active_3d_avoidance_agents.find(agent);
  693. if (agent_3d_index >= 0) {
  694. active_3d_avoidance_agents.remove_at_unordered(agent_3d_index);
  695. agents_dirty = true;
  696. }
  697. int64_t agent_2d_index = active_2d_avoidance_agents.find(agent);
  698. if (agent_2d_index >= 0) {
  699. active_2d_avoidance_agents.remove_at_unordered(agent_2d_index);
  700. agents_dirty = true;
  701. }
  702. }
  703. Vector3 NavMap::get_random_point(uint32_t p_navigation_layers, bool p_uniformly) const {
  704. RWLockRead read_lock(map_rwlock);
  705. const LocalVector<NavRegion *> map_regions = get_regions();
  706. if (map_regions.is_empty()) {
  707. return Vector3();
  708. }
  709. LocalVector<const NavRegion *> accessible_regions;
  710. for (const NavRegion *region : map_regions) {
  711. if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {
  712. continue;
  713. }
  714. accessible_regions.push_back(region);
  715. }
  716. if (accessible_regions.is_empty()) {
  717. // All existing region polygons are disabled.
  718. return Vector3();
  719. }
  720. if (p_uniformly) {
  721. real_t accumulated_region_surface_area = 0;
  722. RBMap<real_t, uint32_t> accessible_regions_area_map;
  723. for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
  724. const NavRegion *region = accessible_regions[accessible_region_index];
  725. real_t region_surface_area = region->get_surface_area();
  726. if (region_surface_area == 0.0f) {
  727. continue;
  728. }
  729. accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
  730. accumulated_region_surface_area += region_surface_area;
  731. }
  732. if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
  733. // All faces have no real surface / no area.
  734. return Vector3();
  735. }
  736. real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
  737. RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
  738. ERR_FAIL_COND_V(!E, Vector3());
  739. uint32_t random_region_index = E->value;
  740. ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector3());
  741. const NavRegion *random_region = accessible_regions[random_region_index];
  742. ERR_FAIL_NULL_V(random_region, Vector3());
  743. return random_region->get_random_point(p_navigation_layers, p_uniformly);
  744. } else {
  745. uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
  746. const NavRegion *random_region = accessible_regions[random_region_index];
  747. ERR_FAIL_NULL_V(random_region, Vector3());
  748. return random_region->get_random_point(p_navigation_layers, p_uniformly);
  749. }
  750. }
  751. void NavMap::sync() {
  752. RWLockWrite write_lock(map_rwlock);
  753. // Performance Monitor
  754. int _new_pm_region_count = regions.size();
  755. int _new_pm_agent_count = agents.size();
  756. int _new_pm_link_count = links.size();
  757. int _new_pm_polygon_count = pm_polygon_count;
  758. int _new_pm_edge_count = pm_edge_count;
  759. int _new_pm_edge_merge_count = pm_edge_merge_count;
  760. int _new_pm_edge_connection_count = pm_edge_connection_count;
  761. int _new_pm_edge_free_count = pm_edge_free_count;
  762. // Check if we need to update the links.
  763. if (regenerate_polygons) {
  764. for (NavRegion *region : regions) {
  765. region->scratch_polygons();
  766. }
  767. regenerate_links = true;
  768. }
  769. for (NavRegion *region : regions) {
  770. if (region->sync()) {
  771. regenerate_links = true;
  772. }
  773. }
  774. for (NavLink *link : links) {
  775. if (link->check_dirty()) {
  776. regenerate_links = true;
  777. }
  778. }
  779. if (regenerate_links) {
  780. _new_pm_polygon_count = 0;
  781. _new_pm_edge_count = 0;
  782. _new_pm_edge_merge_count = 0;
  783. _new_pm_edge_connection_count = 0;
  784. _new_pm_edge_free_count = 0;
  785. // Remove regions connections.
  786. for (NavRegion *region : regions) {
  787. region->get_connections().clear();
  788. }
  789. // Resize the polygon count.
  790. int count = 0;
  791. for (const NavRegion *region : regions) {
  792. if (!region->get_enabled()) {
  793. continue;
  794. }
  795. count += region->get_polygons().size();
  796. }
  797. polygons.resize(count);
  798. // Copy all region polygons in the map.
  799. count = 0;
  800. for (const NavRegion *region : regions) {
  801. if (!region->get_enabled()) {
  802. continue;
  803. }
  804. const LocalVector<gd::Polygon> &polygons_source = region->get_polygons();
  805. for (uint32_t n = 0; n < polygons_source.size(); n++) {
  806. polygons[count + n] = polygons_source[n];
  807. }
  808. count += region->get_polygons().size();
  809. }
  810. _new_pm_polygon_count = polygons.size();
  811. // Group all edges per key.
  812. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections;
  813. for (gd::Polygon &poly : polygons) {
  814. for (uint32_t p = 0; p < poly.points.size(); p++) {
  815. int next_point = (p + 1) % poly.points.size();
  816. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  817. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek);
  818. if (!connection) {
  819. connections[ek] = Vector<gd::Edge::Connection>();
  820. _new_pm_edge_count += 1;
  821. }
  822. if (connections[ek].size() <= 1) {
  823. // Add the polygon/edge tuple to this key.
  824. gd::Edge::Connection new_connection;
  825. new_connection.polygon = &poly;
  826. new_connection.edge = p;
  827. new_connection.pathway_start = poly.points[p].pos;
  828. new_connection.pathway_end = poly.points[next_point].pos;
  829. connections[ek].push_back(new_connection);
  830. } else {
  831. // The edge is already connected with another edge, skip.
  832. ERR_PRINT_ONCE("Navigation map synchronization error. Attempted to merge a navigation mesh polygon edge with another already-merged edge. This is usually caused by crossing edges, overlapping polygons, or a mismatch of the NavigationMesh / NavigationPolygon baked 'cell_size' and navigation map 'cell_size'. If you're certain none of above is the case, change 'navigation/3d/merge_rasterizer_cell_scale' to 0.001.");
  833. }
  834. }
  835. }
  836. Vector<gd::Edge::Connection> free_edges;
  837. for (KeyValue<gd::EdgeKey, Vector<gd::Edge::Connection>> &E : connections) {
  838. if (E.value.size() == 2) {
  839. // Connect edge that are shared in different polygons.
  840. gd::Edge::Connection &c1 = E.value.write[0];
  841. gd::Edge::Connection &c2 = E.value.write[1];
  842. c1.polygon->edges[c1.edge].connections.push_back(c2);
  843. c2.polygon->edges[c2.edge].connections.push_back(c1);
  844. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  845. _new_pm_edge_merge_count += 1;
  846. } else {
  847. CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size()));
  848. if (use_edge_connections && E.value[0].polygon->owner->get_use_edge_connections()) {
  849. free_edges.push_back(E.value[0]);
  850. }
  851. }
  852. }
  853. // Find the compatible near edges.
  854. //
  855. // Note:
  856. // Considering that the edges must be compatible (for obvious reasons)
  857. // to be connected, create new polygons to remove that small gap is
  858. // not really useful and would result in wasteful computation during
  859. // connection, integration and path finding.
  860. _new_pm_edge_free_count = free_edges.size();
  861. for (int i = 0; i < free_edges.size(); i++) {
  862. const gd::Edge::Connection &free_edge = free_edges[i];
  863. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  864. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  865. for (int j = 0; j < free_edges.size(); j++) {
  866. const gd::Edge::Connection &other_edge = free_edges[j];
  867. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  868. continue;
  869. }
  870. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  871. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  872. // Compute the projection of the opposite edge on the current one
  873. Vector3 edge_vector = edge_p2 - edge_p1;
  874. real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  875. real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  876. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  877. continue;
  878. }
  879. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  880. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  881. Vector3 other1;
  882. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  883. other1 = other_edge_p1;
  884. } else {
  885. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  886. }
  887. if (other1.distance_to(self1) > edge_connection_margin) {
  888. continue;
  889. }
  890. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  891. Vector3 other2;
  892. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  893. other2 = other_edge_p2;
  894. } else {
  895. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  896. }
  897. if (other2.distance_to(self2) > edge_connection_margin) {
  898. continue;
  899. }
  900. // The edges can now be connected.
  901. gd::Edge::Connection new_connection = other_edge;
  902. new_connection.pathway_start = (self1 + other1) / 2.0;
  903. new_connection.pathway_end = (self2 + other2) / 2.0;
  904. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  905. // Add the connection to the region_connection map.
  906. ((NavRegion *)free_edge.polygon->owner)->get_connections().push_back(new_connection);
  907. _new_pm_edge_connection_count += 1;
  908. }
  909. }
  910. uint32_t link_poly_idx = 0;
  911. link_polygons.resize(links.size());
  912. // Search for polygons within range of a nav link.
  913. for (const NavLink *link : links) {
  914. if (!link->get_enabled()) {
  915. continue;
  916. }
  917. const Vector3 start = link->get_start_position();
  918. const Vector3 end = link->get_end_position();
  919. gd::Polygon *closest_start_polygon = nullptr;
  920. real_t closest_start_distance = link_connection_radius;
  921. Vector3 closest_start_point;
  922. gd::Polygon *closest_end_polygon = nullptr;
  923. real_t closest_end_distance = link_connection_radius;
  924. Vector3 closest_end_point;
  925. // Create link to any polygons within the search radius of the start point.
  926. for (uint32_t start_index = 0; start_index < polygons.size(); start_index++) {
  927. gd::Polygon &start_poly = polygons[start_index];
  928. // For each face check the distance to the start
  929. for (uint32_t start_point_id = 2; start_point_id < start_poly.points.size(); start_point_id += 1) {
  930. const Face3 start_face(start_poly.points[0].pos, start_poly.points[start_point_id - 1].pos, start_poly.points[start_point_id].pos);
  931. const Vector3 start_point = start_face.get_closest_point_to(start);
  932. const real_t start_distance = start_point.distance_to(start);
  933. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  934. if (start_distance <= link_connection_radius && start_distance < closest_start_distance) {
  935. closest_start_distance = start_distance;
  936. closest_start_point = start_point;
  937. closest_start_polygon = &start_poly;
  938. }
  939. }
  940. }
  941. // Find any polygons within the search radius of the end point.
  942. for (gd::Polygon &end_poly : polygons) {
  943. // For each face check the distance to the end
  944. for (uint32_t end_point_id = 2; end_point_id < end_poly.points.size(); end_point_id += 1) {
  945. const Face3 end_face(end_poly.points[0].pos, end_poly.points[end_point_id - 1].pos, end_poly.points[end_point_id].pos);
  946. const Vector3 end_point = end_face.get_closest_point_to(end);
  947. const real_t end_distance = end_point.distance_to(end);
  948. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  949. if (end_distance <= link_connection_radius && end_distance < closest_end_distance) {
  950. closest_end_distance = end_distance;
  951. closest_end_point = end_point;
  952. closest_end_polygon = &end_poly;
  953. }
  954. }
  955. }
  956. // If we have both a start and end point, then create a synthetic polygon to route through.
  957. if (closest_start_polygon && closest_end_polygon) {
  958. gd::Polygon &new_polygon = link_polygons[link_poly_idx++];
  959. new_polygon.owner = link;
  960. new_polygon.edges.clear();
  961. new_polygon.edges.resize(4);
  962. new_polygon.points.clear();
  963. new_polygon.points.reserve(4);
  964. // Build a set of vertices that create a thin polygon going from the start to the end point.
  965. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  966. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  967. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  968. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  969. Vector3 center;
  970. for (int p = 0; p < 4; ++p) {
  971. center += new_polygon.points[p].pos;
  972. }
  973. new_polygon.center = center / real_t(new_polygon.points.size());
  974. new_polygon.clockwise = true;
  975. // Setup connections to go forward in the link.
  976. {
  977. gd::Edge::Connection entry_connection;
  978. entry_connection.polygon = &new_polygon;
  979. entry_connection.edge = -1;
  980. entry_connection.pathway_start = new_polygon.points[0].pos;
  981. entry_connection.pathway_end = new_polygon.points[1].pos;
  982. closest_start_polygon->edges[0].connections.push_back(entry_connection);
  983. gd::Edge::Connection exit_connection;
  984. exit_connection.polygon = closest_end_polygon;
  985. exit_connection.edge = -1;
  986. exit_connection.pathway_start = new_polygon.points[2].pos;
  987. exit_connection.pathway_end = new_polygon.points[3].pos;
  988. new_polygon.edges[2].connections.push_back(exit_connection);
  989. }
  990. // If the link is bi-directional, create connections from the end to the start.
  991. if (link->is_bidirectional()) {
  992. gd::Edge::Connection entry_connection;
  993. entry_connection.polygon = &new_polygon;
  994. entry_connection.edge = -1;
  995. entry_connection.pathway_start = new_polygon.points[2].pos;
  996. entry_connection.pathway_end = new_polygon.points[3].pos;
  997. closest_end_polygon->edges[0].connections.push_back(entry_connection);
  998. gd::Edge::Connection exit_connection;
  999. exit_connection.polygon = closest_start_polygon;
  1000. exit_connection.edge = -1;
  1001. exit_connection.pathway_start = new_polygon.points[0].pos;
  1002. exit_connection.pathway_end = new_polygon.points[1].pos;
  1003. new_polygon.edges[0].connections.push_back(exit_connection);
  1004. }
  1005. }
  1006. }
  1007. // Some code treats 0 as a failure case, so we avoid returning 0 and modulo wrap UINT32_MAX manually.
  1008. iteration_id = iteration_id % UINT32_MAX + 1;
  1009. }
  1010. // Do we have modified obstacle positions?
  1011. for (NavObstacle *obstacle : obstacles) {
  1012. if (obstacle->check_dirty()) {
  1013. obstacles_dirty = true;
  1014. }
  1015. }
  1016. // Do we have modified agent arrays?
  1017. for (NavAgent *agent : agents) {
  1018. if (agent->check_dirty()) {
  1019. agents_dirty = true;
  1020. }
  1021. }
  1022. // Update avoidance worlds.
  1023. if (obstacles_dirty || agents_dirty) {
  1024. _update_rvo_simulation();
  1025. }
  1026. regenerate_polygons = false;
  1027. regenerate_links = false;
  1028. obstacles_dirty = false;
  1029. agents_dirty = false;
  1030. // Performance Monitor.
  1031. pm_region_count = _new_pm_region_count;
  1032. pm_agent_count = _new_pm_agent_count;
  1033. pm_link_count = _new_pm_link_count;
  1034. pm_polygon_count = _new_pm_polygon_count;
  1035. pm_edge_count = _new_pm_edge_count;
  1036. pm_edge_merge_count = _new_pm_edge_merge_count;
  1037. pm_edge_connection_count = _new_pm_edge_connection_count;
  1038. pm_edge_free_count = _new_pm_edge_free_count;
  1039. }
  1040. void NavMap::_update_rvo_obstacles_tree_2d() {
  1041. int obstacle_vertex_count = 0;
  1042. for (NavObstacle *obstacle : obstacles) {
  1043. obstacle_vertex_count += obstacle->get_vertices().size();
  1044. }
  1045. // Cleaning old obstacles.
  1046. for (size_t i = 0; i < rvo_simulation_2d.obstacles_.size(); ++i) {
  1047. delete rvo_simulation_2d.obstacles_[i];
  1048. }
  1049. rvo_simulation_2d.obstacles_.clear();
  1050. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree
  1051. std::vector<RVO2D::Obstacle2D *> &raw_obstacles = rvo_simulation_2d.obstacles_;
  1052. raw_obstacles.reserve(obstacle_vertex_count);
  1053. // The following block is modified copy from RVO2D::AddObstacle()
  1054. // Obstacles are linked and depend on all other obstacles.
  1055. for (NavObstacle *obstacle : obstacles) {
  1056. const Vector3 &_obstacle_position = obstacle->get_position();
  1057. const Vector<Vector3> &_obstacle_vertices = obstacle->get_vertices();
  1058. if (_obstacle_vertices.size() < 2) {
  1059. continue;
  1060. }
  1061. std::vector<RVO2D::Vector2> rvo_2d_vertices;
  1062. rvo_2d_vertices.reserve(_obstacle_vertices.size());
  1063. uint32_t _obstacle_avoidance_layers = obstacle->get_avoidance_layers();
  1064. real_t _obstacle_height = obstacle->get_height();
  1065. for (const Vector3 &_obstacle_vertex : _obstacle_vertices) {
  1066. #ifdef TOOLS_ENABLED
  1067. if (_obstacle_vertex.y != 0) {
  1068. WARN_PRINT_ONCE("Y coordinates of static obstacle vertices are ignored. Please use obstacle position Y to change elevation of obstacle.");
  1069. }
  1070. #endif
  1071. rvo_2d_vertices.push_back(RVO2D::Vector2(_obstacle_vertex.x + _obstacle_position.x, _obstacle_vertex.z + _obstacle_position.z));
  1072. }
  1073. const size_t obstacleNo = raw_obstacles.size();
  1074. for (size_t i = 0; i < rvo_2d_vertices.size(); i++) {
  1075. RVO2D::Obstacle2D *rvo_2d_obstacle = new RVO2D::Obstacle2D();
  1076. rvo_2d_obstacle->point_ = rvo_2d_vertices[i];
  1077. rvo_2d_obstacle->height_ = _obstacle_height;
  1078. rvo_2d_obstacle->elevation_ = _obstacle_position.y;
  1079. rvo_2d_obstacle->avoidance_layers_ = _obstacle_avoidance_layers;
  1080. if (i != 0) {
  1081. rvo_2d_obstacle->prevObstacle_ = raw_obstacles.back();
  1082. rvo_2d_obstacle->prevObstacle_->nextObstacle_ = rvo_2d_obstacle;
  1083. }
  1084. if (i == rvo_2d_vertices.size() - 1) {
  1085. rvo_2d_obstacle->nextObstacle_ = raw_obstacles[obstacleNo];
  1086. rvo_2d_obstacle->nextObstacle_->prevObstacle_ = rvo_2d_obstacle;
  1087. }
  1088. rvo_2d_obstacle->unitDir_ = normalize(rvo_2d_vertices[(i == rvo_2d_vertices.size() - 1 ? 0 : i + 1)] - rvo_2d_vertices[i]);
  1089. if (rvo_2d_vertices.size() == 2) {
  1090. rvo_2d_obstacle->isConvex_ = true;
  1091. } else {
  1092. rvo_2d_obstacle->isConvex_ = (leftOf(rvo_2d_vertices[(i == 0 ? rvo_2d_vertices.size() - 1 : i - 1)], rvo_2d_vertices[i], rvo_2d_vertices[(i == rvo_2d_vertices.size() - 1 ? 0 : i + 1)]) >= 0.0f);
  1093. }
  1094. rvo_2d_obstacle->id_ = raw_obstacles.size();
  1095. raw_obstacles.push_back(rvo_2d_obstacle);
  1096. }
  1097. }
  1098. rvo_simulation_2d.kdTree_->buildObstacleTree(raw_obstacles);
  1099. }
  1100. void NavMap::_update_rvo_agents_tree_2d() {
  1101. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1102. std::vector<RVO2D::Agent2D *> raw_agents;
  1103. raw_agents.reserve(active_2d_avoidance_agents.size());
  1104. for (NavAgent *agent : active_2d_avoidance_agents) {
  1105. raw_agents.push_back(agent->get_rvo_agent_2d());
  1106. }
  1107. rvo_simulation_2d.kdTree_->buildAgentTree(raw_agents);
  1108. }
  1109. void NavMap::_update_rvo_agents_tree_3d() {
  1110. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1111. std::vector<RVO3D::Agent3D *> raw_agents;
  1112. raw_agents.reserve(active_3d_avoidance_agents.size());
  1113. for (NavAgent *agent : active_3d_avoidance_agents) {
  1114. raw_agents.push_back(agent->get_rvo_agent_3d());
  1115. }
  1116. rvo_simulation_3d.kdTree_->buildAgentTree(raw_agents);
  1117. }
  1118. void NavMap::_update_rvo_simulation() {
  1119. if (obstacles_dirty) {
  1120. _update_rvo_obstacles_tree_2d();
  1121. }
  1122. if (agents_dirty) {
  1123. _update_rvo_agents_tree_2d();
  1124. _update_rvo_agents_tree_3d();
  1125. }
  1126. }
  1127. void NavMap::compute_single_avoidance_step_2d(uint32_t index, NavAgent **agent) {
  1128. (*(agent + index))->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1129. (*(agent + index))->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1130. (*(agent + index))->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1131. (*(agent + index))->update();
  1132. }
  1133. void NavMap::compute_single_avoidance_step_3d(uint32_t index, NavAgent **agent) {
  1134. (*(agent + index))->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1135. (*(agent + index))->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1136. (*(agent + index))->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1137. (*(agent + index))->update();
  1138. }
  1139. void NavMap::step(real_t p_deltatime) {
  1140. deltatime = p_deltatime;
  1141. rvo_simulation_2d.setTimeStep(float(deltatime));
  1142. rvo_simulation_3d.setTimeStep(float(deltatime));
  1143. if (active_2d_avoidance_agents.size() > 0) {
  1144. if (use_threads && avoidance_use_multiple_threads) {
  1145. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &NavMap::compute_single_avoidance_step_2d, active_2d_avoidance_agents.ptr(), active_2d_avoidance_agents.size(), -1, true, SNAME("RVOAvoidanceAgents2D"));
  1146. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1147. } else {
  1148. for (NavAgent *agent : active_2d_avoidance_agents) {
  1149. agent->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1150. agent->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1151. agent->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1152. agent->update();
  1153. }
  1154. }
  1155. }
  1156. if (active_3d_avoidance_agents.size() > 0) {
  1157. if (use_threads && avoidance_use_multiple_threads) {
  1158. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &NavMap::compute_single_avoidance_step_3d, active_3d_avoidance_agents.ptr(), active_3d_avoidance_agents.size(), -1, true, SNAME("RVOAvoidanceAgents3D"));
  1159. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1160. } else {
  1161. for (NavAgent *agent : active_3d_avoidance_agents) {
  1162. agent->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1163. agent->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1164. agent->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1165. agent->update();
  1166. }
  1167. }
  1168. }
  1169. }
  1170. void NavMap::dispatch_callbacks() {
  1171. for (NavAgent *agent : active_2d_avoidance_agents) {
  1172. agent->dispatch_avoidance_callback();
  1173. }
  1174. for (NavAgent *agent : active_3d_avoidance_agents) {
  1175. agent->dispatch_avoidance_callback();
  1176. }
  1177. }
  1178. void NavMap::clip_path(const LocalVector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly, Vector<int32_t> *r_path_types, TypedArray<RID> *r_path_rids, Vector<int64_t> *r_path_owners) const {
  1179. Vector3 from = path[path.size() - 1];
  1180. if (from.is_equal_approx(p_to_point)) {
  1181. return;
  1182. }
  1183. Plane cut_plane;
  1184. cut_plane.normal = (from - p_to_point).cross(up);
  1185. if (cut_plane.normal == Vector3()) {
  1186. return;
  1187. }
  1188. cut_plane.normal.normalize();
  1189. cut_plane.d = cut_plane.normal.dot(from);
  1190. while (from_poly != p_to_poly) {
  1191. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  1192. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  1193. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  1194. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  1195. if (!pathway_start.is_equal_approx(pathway_end)) {
  1196. Vector3 inters;
  1197. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  1198. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) {
  1199. path.push_back(inters);
  1200. APPEND_METADATA(from_poly->poly);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. void NavMap::_update_merge_rasterizer_cell_dimensions() {
  1207. merge_rasterizer_cell_size = cell_size * merge_rasterizer_cell_scale;
  1208. merge_rasterizer_cell_height = cell_height * merge_rasterizer_cell_scale;
  1209. }
  1210. NavMap::NavMap() {
  1211. avoidance_use_multiple_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_multiple_threads");
  1212. avoidance_use_high_priority_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_high_priority_threads");
  1213. }
  1214. NavMap::~NavMap() {
  1215. }