nav_map.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. /*************************************************************************/
  2. /* nav_map.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 "core/os/threaded_array_processor.h"
  32. #include "nav_region.h"
  33. #include "rvo_agent.h"
  34. #include <algorithm>
  35. /**
  36. @author AndreaCatania
  37. */
  38. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  39. void NavMap::set_up(Vector3 p_up) {
  40. up = p_up;
  41. regenerate_polygons = true;
  42. }
  43. void NavMap::set_cell_size(float p_cell_size) {
  44. cell_size = p_cell_size;
  45. regenerate_polygons = true;
  46. }
  47. void NavMap::set_edge_connection_margin(float p_edge_connection_margin) {
  48. edge_connection_margin = p_edge_connection_margin;
  49. regenerate_links = true;
  50. }
  51. gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
  52. const int x = int(Math::floor(p_pos.x / cell_size));
  53. const int y = int(Math::floor(p_pos.y / cell_size));
  54. const int z = int(Math::floor(p_pos.z / cell_size));
  55. gd::PointKey p;
  56. p.key = 0;
  57. p.x = x;
  58. p.y = y;
  59. p.z = z;
  60. return p;
  61. }
  62. Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_layers) const {
  63. // Find the start poly and the end poly on this map.
  64. const gd::Polygon *begin_poly = nullptr;
  65. const gd::Polygon *end_poly = nullptr;
  66. Vector3 begin_point;
  67. Vector3 end_point;
  68. float begin_d = 1e20;
  69. float end_d = 1e20;
  70. // Find the initial poly and the end poly on this map.
  71. for (size_t i(0); i < polygons.size(); i++) {
  72. const gd::Polygon &p = polygons[i];
  73. // Only consider the polygon if it in a region with compatible layers.
  74. if ((p_layers & p.owner->get_layers()) == 0) {
  75. continue;
  76. }
  77. // For each point cast a face and check the distance between the origin/destination
  78. for (size_t point_id = 0; point_id < p.points.size(); point_id++) {
  79. const Vector3 p1 = p.points[point_id].pos;
  80. const Vector3 p2 = p.points[(point_id + 1) % p.points.size()].pos;
  81. const Vector3 p3 = p.points[(point_id + 2) % p.points.size()].pos;
  82. const Face3 face(p1, p2, p3);
  83. Vector3 point = face.get_closest_point_to(p_origin);
  84. float distance_to_point = point.distance_to(p_origin);
  85. if (distance_to_point < begin_d) {
  86. begin_d = distance_to_point;
  87. begin_poly = &p;
  88. begin_point = point;
  89. }
  90. point = face.get_closest_point_to(p_destination);
  91. distance_to_point = point.distance_to(p_destination);
  92. if (distance_to_point < end_d) {
  93. end_d = distance_to_point;
  94. end_poly = &p;
  95. end_point = point;
  96. }
  97. }
  98. }
  99. // Check for trival cases
  100. if (!begin_poly || !end_poly) {
  101. return Vector<Vector3>();
  102. }
  103. if (begin_poly == end_poly) {
  104. Vector<Vector3> path;
  105. path.resize(2);
  106. path.write[0] = begin_point;
  107. path.write[1] = end_point;
  108. return path;
  109. }
  110. // List of all reachable navigation polys.
  111. std::vector<gd::NavigationPoly> navigation_polys;
  112. navigation_polys.reserve(polygons.size() * 0.75);
  113. // Add the start polygon to the reachable navigation polygons.
  114. gd::NavigationPoly begin_navigation_poly = gd::NavigationPoly(begin_poly);
  115. begin_navigation_poly.self_id = 0;
  116. begin_navigation_poly.entry = begin_point;
  117. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  118. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  119. navigation_polys.push_back(begin_navigation_poly);
  120. // List of polygon IDs to visit.
  121. List<uint32_t> to_visit;
  122. to_visit.push_back(0);
  123. // This is an implementation of the A* algorithm.
  124. int least_cost_id = 0;
  125. bool found_route = false;
  126. const gd::Polygon *reachable_end = nullptr;
  127. float reachable_d = 1e30;
  128. bool is_reachable = true;
  129. while (true) {
  130. gd::NavigationPoly *least_cost_poly = &navigation_polys[least_cost_id];
  131. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  132. for (size_t i = 0; i < least_cost_poly->poly->edges.size(); i++) {
  133. const gd::Edge &edge = least_cost_poly->poly->edges[i];
  134. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  135. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  136. const gd::Edge::Connection &connection = edge.connections[connection_index];
  137. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  138. if ((p_layers & connection.polygon->owner->get_layers()) == 0) {
  139. continue;
  140. }
  141. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  142. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly->entry, pathway);
  143. const float new_distance = least_cost_poly->entry.distance_to(new_entry) + least_cost_poly->traveled_distance;
  144. const std::vector<gd::NavigationPoly>::iterator it = std::find(
  145. navigation_polys.begin(),
  146. navigation_polys.end(),
  147. gd::NavigationPoly(connection.polygon));
  148. if (it != navigation_polys.end()) {
  149. // Polygon already visited, check if we can reduce the travel cost.
  150. if (new_distance < it->traveled_distance) {
  151. it->back_navigation_poly_id = least_cost_id;
  152. it->back_navigation_edge = connection.edge;
  153. it->back_navigation_edge_pathway_start = connection.pathway_start;
  154. it->back_navigation_edge_pathway_end = connection.pathway_end;
  155. it->traveled_distance = new_distance;
  156. it->entry = new_entry;
  157. }
  158. } else {
  159. // Add the neighbour polygon to the reachable ones.
  160. gd::NavigationPoly new_navigation_poly = gd::NavigationPoly(connection.polygon);
  161. new_navigation_poly.self_id = navigation_polys.size();
  162. new_navigation_poly.back_navigation_poly_id = least_cost_id;
  163. new_navigation_poly.back_navigation_edge = connection.edge;
  164. new_navigation_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  165. new_navigation_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  166. new_navigation_poly.traveled_distance = new_distance;
  167. new_navigation_poly.entry = new_entry;
  168. navigation_polys.push_back(new_navigation_poly);
  169. // Add the neighbour polygon to the polygons to visit.
  170. to_visit.push_back(navigation_polys.size() - 1);
  171. }
  172. }
  173. }
  174. // Removes the least cost polygon from the list of polygons to visit so we can advance.
  175. to_visit.erase(least_cost_id);
  176. // When the list of polygons to visit is empty at this point it means the End Polygon is not reachable
  177. if (to_visit.size() == 0) {
  178. // Thus use the further reachable polygon
  179. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  180. is_reachable = false;
  181. if (reachable_end == nullptr) {
  182. // The path is not found and there is not a way out.
  183. break;
  184. }
  185. // Set as end point the furthest reachable point.
  186. end_poly = reachable_end;
  187. end_d = 1e20;
  188. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  189. Face3 f(end_poly->points[point_id - 2].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  190. Vector3 spoint = f.get_closest_point_to(p_destination);
  191. float dpoint = spoint.distance_to(p_destination);
  192. if (dpoint < end_d) {
  193. end_point = spoint;
  194. end_d = dpoint;
  195. }
  196. }
  197. // Reset open and navigation_polys
  198. gd::NavigationPoly np = navigation_polys[0];
  199. navigation_polys.clear();
  200. navigation_polys.push_back(np);
  201. to_visit.clear();
  202. to_visit.push_back(0);
  203. reachable_end = nullptr;
  204. continue;
  205. }
  206. // Find the polygon with the minimum cost from the list of polygons to visit.
  207. least_cost_id = -1;
  208. float least_cost = 1e30;
  209. for (List<uint32_t>::Element *element = to_visit.front(); element != nullptr; element = element->next()) {
  210. gd::NavigationPoly *np = &navigation_polys[element->get()];
  211. float cost = np->traveled_distance;
  212. cost += np->entry.distance_to(end_point);
  213. if (cost < least_cost) {
  214. least_cost_id = np->self_id;
  215. least_cost = cost;
  216. }
  217. }
  218. // Stores the further reachable end polygon, in case our goal is not reachable.
  219. if (is_reachable) {
  220. float d = navigation_polys[least_cost_id].entry.distance_to(p_destination);
  221. if (reachable_d > d) {
  222. reachable_d = d;
  223. reachable_end = navigation_polys[least_cost_id].poly;
  224. }
  225. }
  226. ERR_BREAK(least_cost_id == -1);
  227. // Check if we reached the end
  228. if (navigation_polys[least_cost_id].poly == end_poly) {
  229. found_route = true;
  230. break;
  231. }
  232. }
  233. // If we did not find a route, return an empty path.
  234. if (!found_route) {
  235. return Vector<Vector3>();
  236. }
  237. Vector<Vector3> path;
  238. // Optimize the path.
  239. if (p_optimize) {
  240. // Set the apex poly/point to the end point
  241. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  242. Vector3 apex_point = end_point;
  243. gd::NavigationPoly *left_poly = apex_poly;
  244. Vector3 left_portal = apex_point;
  245. gd::NavigationPoly *right_poly = apex_poly;
  246. Vector3 right_portal = apex_point;
  247. gd::NavigationPoly *p = apex_poly;
  248. path.push_back(end_point);
  249. while (p) {
  250. // Set left and right points of the pathway between polygons.
  251. Vector3 left = p->back_navigation_edge_pathway_start;
  252. Vector3 right = p->back_navigation_edge_pathway_end;
  253. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(up) < 0) {
  254. SWAP(left, right);
  255. }
  256. bool skip = false;
  257. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(up) >= 0) {
  258. //process
  259. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(up) > 0) {
  260. left_poly = p;
  261. left_portal = left;
  262. } else {
  263. clip_path(navigation_polys, path, apex_poly, right_portal, right_poly);
  264. apex_point = right_portal;
  265. p = right_poly;
  266. left_poly = p;
  267. apex_poly = p;
  268. left_portal = apex_point;
  269. right_portal = apex_point;
  270. path.push_back(apex_point);
  271. skip = true;
  272. }
  273. }
  274. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(up) <= 0) {
  275. //process
  276. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(up) < 0) {
  277. right_poly = p;
  278. right_portal = right;
  279. } else {
  280. clip_path(navigation_polys, path, apex_poly, left_portal, left_poly);
  281. apex_point = left_portal;
  282. p = left_poly;
  283. right_poly = p;
  284. apex_poly = p;
  285. right_portal = apex_point;
  286. left_portal = apex_point;
  287. path.push_back(apex_point);
  288. }
  289. }
  290. // Go to the previous polygon.
  291. if (p->back_navigation_poly_id != -1) {
  292. p = &navigation_polys[p->back_navigation_poly_id];
  293. } else {
  294. // The end
  295. p = nullptr;
  296. }
  297. }
  298. // If the last point is not the begin point, add it to the list.
  299. if (path[path.size() - 1] != begin_point) {
  300. path.push_back(begin_point);
  301. }
  302. path.reverse();
  303. } else {
  304. path.push_back(end_point);
  305. // Add mid points
  306. int np_id = least_cost_id;
  307. while (np_id != -1) {
  308. path.push_back(navigation_polys[np_id].entry);
  309. np_id = navigation_polys[np_id].back_navigation_poly_id;
  310. }
  311. path.reverse();
  312. }
  313. return path;
  314. }
  315. Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
  316. bool use_collision = p_use_collision;
  317. Vector3 closest_point;
  318. real_t closest_point_d = 1e20;
  319. // Find the initial poly and the end poly on this map.
  320. for (size_t i(0); i < polygons.size(); i++) {
  321. const gd::Polygon &p = polygons[i];
  322. // For each point cast a face and check the distance to the segment
  323. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  324. const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  325. Vector3 inters;
  326. if (f.intersects_segment(p_from, p_to, &inters)) {
  327. const real_t d = closest_point_d = p_from.distance_to(inters);
  328. if (use_collision == false) {
  329. closest_point = inters;
  330. use_collision = true;
  331. closest_point_d = d;
  332. } else if (closest_point_d > d) {
  333. closest_point = inters;
  334. closest_point_d = d;
  335. }
  336. }
  337. }
  338. if (use_collision == false) {
  339. for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
  340. Vector3 a, b;
  341. Geometry3D::get_closest_points_between_segments(
  342. p_from,
  343. p_to,
  344. p.points[point_id].pos,
  345. p.points[(point_id + 1) % p.points.size()].pos,
  346. a,
  347. b);
  348. const real_t d = a.distance_to(b);
  349. if (d < closest_point_d) {
  350. closest_point_d = d;
  351. closest_point = b;
  352. }
  353. }
  354. }
  355. }
  356. return closest_point;
  357. }
  358. Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
  359. // TODO this is really not optimal, please redesign the API to directly return all this data
  360. Vector3 closest_point;
  361. real_t closest_point_d = 1e20;
  362. // Find the initial poly and the end poly on this map.
  363. for (size_t i(0); i < polygons.size(); i++) {
  364. const gd::Polygon &p = polygons[i];
  365. // For each point cast a face and check the distance to the point
  366. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  367. const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  368. const Vector3 inters = f.get_closest_point_to(p_point);
  369. const real_t d = inters.distance_to(p_point);
  370. if (d < closest_point_d) {
  371. closest_point = inters;
  372. closest_point_d = d;
  373. }
  374. }
  375. }
  376. return closest_point;
  377. }
  378. Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
  379. // TODO this is really not optimal, please redesign the API to directly return all this data
  380. Vector3 closest_point;
  381. Vector3 closest_point_normal;
  382. real_t closest_point_d = 1e20;
  383. // Find the initial poly and the end poly on this map.
  384. for (size_t i(0); i < polygons.size(); i++) {
  385. const gd::Polygon &p = polygons[i];
  386. // For each point cast a face and check the distance to the point
  387. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  388. const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  389. const Vector3 inters = f.get_closest_point_to(p_point);
  390. const real_t d = inters.distance_to(p_point);
  391. if (d < closest_point_d) {
  392. closest_point = inters;
  393. closest_point_normal = f.get_plane().normal;
  394. closest_point_d = d;
  395. }
  396. }
  397. }
  398. return closest_point_normal;
  399. }
  400. RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
  401. // TODO this is really not optimal, please redesign the API to directly return all this data
  402. Vector3 closest_point;
  403. RID closest_point_owner;
  404. real_t closest_point_d = 1e20;
  405. // Find the initial poly and the end poly on this map.
  406. for (size_t i(0); i < polygons.size(); i++) {
  407. const gd::Polygon &p = polygons[i];
  408. // For each point cast a face and check the distance to the point
  409. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  410. const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  411. const Vector3 inters = f.get_closest_point_to(p_point);
  412. const real_t d = inters.distance_to(p_point);
  413. if (d < closest_point_d) {
  414. closest_point = inters;
  415. closest_point_owner = p.owner->get_self();
  416. closest_point_d = d;
  417. }
  418. }
  419. }
  420. return closest_point_owner;
  421. }
  422. void NavMap::add_region(NavRegion *p_region) {
  423. regions.push_back(p_region);
  424. regenerate_links = true;
  425. }
  426. void NavMap::remove_region(NavRegion *p_region) {
  427. const std::vector<NavRegion *>::iterator it = std::find(regions.begin(), regions.end(), p_region);
  428. if (it != regions.end()) {
  429. regions.erase(it);
  430. regenerate_links = true;
  431. }
  432. }
  433. bool NavMap::has_agent(RvoAgent *agent) const {
  434. return std::find(agents.begin(), agents.end(), agent) != agents.end();
  435. }
  436. void NavMap::add_agent(RvoAgent *agent) {
  437. if (!has_agent(agent)) {
  438. agents.push_back(agent);
  439. agents_dirty = true;
  440. }
  441. }
  442. void NavMap::remove_agent(RvoAgent *agent) {
  443. remove_agent_as_controlled(agent);
  444. const std::vector<RvoAgent *>::iterator it = std::find(agents.begin(), agents.end(), agent);
  445. if (it != agents.end()) {
  446. agents.erase(it);
  447. agents_dirty = true;
  448. }
  449. }
  450. void NavMap::set_agent_as_controlled(RvoAgent *agent) {
  451. const bool exist = std::find(controlled_agents.begin(), controlled_agents.end(), agent) != controlled_agents.end();
  452. if (!exist) {
  453. ERR_FAIL_COND(!has_agent(agent));
  454. controlled_agents.push_back(agent);
  455. }
  456. }
  457. void NavMap::remove_agent_as_controlled(RvoAgent *agent) {
  458. const std::vector<RvoAgent *>::iterator it = std::find(controlled_agents.begin(), controlled_agents.end(), agent);
  459. if (it != controlled_agents.end()) {
  460. controlled_agents.erase(it);
  461. }
  462. }
  463. void NavMap::sync() {
  464. // Check if we need to update the links.
  465. if (regenerate_polygons) {
  466. for (size_t r(0); r < regions.size(); r++) {
  467. regions[r]->scratch_polygons();
  468. }
  469. regenerate_links = true;
  470. }
  471. for (size_t r(0); r < regions.size(); r++) {
  472. if (regions[r]->sync()) {
  473. regenerate_links = true;
  474. }
  475. }
  476. if (regenerate_links) {
  477. // Remove regions connections.
  478. for (size_t r(0); r < regions.size(); r++) {
  479. regions[r]->get_connections().clear();
  480. }
  481. // Resize the polygon count.
  482. int count = 0;
  483. for (size_t r(0); r < regions.size(); r++) {
  484. count += regions[r]->get_polygons().size();
  485. }
  486. polygons.resize(count);
  487. // Copy all region polygons in the map.
  488. count = 0;
  489. for (size_t r(0); r < regions.size(); r++) {
  490. std::copy(
  491. regions[r]->get_polygons().data(),
  492. regions[r]->get_polygons().data() + regions[r]->get_polygons().size(),
  493. polygons.begin() + count);
  494. count += regions[r]->get_polygons().size();
  495. }
  496. // Group all edges per key.
  497. Map<gd::EdgeKey, Vector<gd::Edge::Connection>> connections;
  498. for (size_t poly_id(0); poly_id < polygons.size(); poly_id++) {
  499. gd::Polygon &poly(polygons[poly_id]);
  500. for (size_t p(0); p < poly.points.size(); p++) {
  501. int next_point = (p + 1) % poly.points.size();
  502. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  503. Map<gd::EdgeKey, Vector<gd::Edge::Connection>>::Element *connection = connections.find(ek);
  504. if (!connection) {
  505. connections[ek] = Vector<gd::Edge::Connection>();
  506. }
  507. if (connections[ek].size() <= 1) {
  508. // Add the polygon/edge tuple to this key.
  509. gd::Edge::Connection new_connection;
  510. new_connection.polygon = &poly;
  511. new_connection.edge = p;
  512. new_connection.pathway_start = poly.points[p].pos;
  513. new_connection.pathway_end = poly.points[next_point].pos;
  514. connections[ek].push_back(new_connection);
  515. } else {
  516. // The edge is already connected with another edge, skip.
  517. ERR_PRINT("Attempted to merge a navigation mesh triangle edge with another already-merged edge. This happens when the current `cell_size` is different from the one used to generate the navigation mesh. This will cause navigation problem.");
  518. }
  519. }
  520. }
  521. Vector<gd::Edge::Connection> free_edges;
  522. for (Map<gd::EdgeKey, Vector<gd::Edge::Connection>>::Element *E = connections.front(); E; E = E->next()) {
  523. if (E->get().size() == 2) {
  524. // Connect edge that are shared in different polygons.
  525. gd::Edge::Connection &c1 = E->get().write[0];
  526. gd::Edge::Connection &c2 = E->get().write[1];
  527. c1.polygon->edges[c1.edge].connections.push_back(c2);
  528. c2.polygon->edges[c2.edge].connections.push_back(c1);
  529. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  530. } else {
  531. CRASH_COND_MSG(E->get().size() != 1, vformat("Number of connection != 1. Found: %d", E->get().size()));
  532. free_edges.push_back(E->get()[0]);
  533. }
  534. }
  535. // Find the compatible near edges.
  536. //
  537. // Note:
  538. // Considering that the edges must be compatible (for obvious reasons)
  539. // to be connected, create new polygons to remove that small gap is
  540. // not really useful and would result in wasteful computation during
  541. // connection, integration and path finding.
  542. for (int i = 0; i < free_edges.size(); i++) {
  543. const gd::Edge::Connection &free_edge = free_edges[i];
  544. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  545. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  546. for (int j = 0; j < free_edges.size(); j++) {
  547. const gd::Edge::Connection &other_edge = free_edges[j];
  548. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  549. continue;
  550. }
  551. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  552. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  553. // Compute the projection of the opposite edge on the current one
  554. Vector3 edge_vector = edge_p2 - edge_p1;
  555. float projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  556. float projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  557. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  558. continue;
  559. }
  560. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  561. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  562. Vector3 other1;
  563. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  564. other1 = other_edge_p1;
  565. } else {
  566. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  567. }
  568. if ((self1 - other1).length() > edge_connection_margin) {
  569. continue;
  570. }
  571. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  572. Vector3 other2;
  573. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  574. other2 = other_edge_p2;
  575. } else {
  576. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  577. }
  578. if ((self2 - other2).length() > edge_connection_margin) {
  579. continue;
  580. }
  581. // The edges can now be connected.
  582. gd::Edge::Connection new_connection = other_edge;
  583. new_connection.pathway_start = (self1 + other1) / 2.0;
  584. new_connection.pathway_end = (self2 + other2) / 2.0;
  585. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  586. // Add the connection to the region_connection map.
  587. free_edge.polygon->owner->get_connections().push_back(new_connection);
  588. }
  589. }
  590. // Update the update ID.
  591. map_update_id = (map_update_id + 1) % 9999999;
  592. }
  593. // Update agents tree.
  594. if (agents_dirty) {
  595. std::vector<RVO::Agent *> raw_agents;
  596. raw_agents.reserve(agents.size());
  597. for (size_t i(0); i < agents.size(); i++) {
  598. raw_agents.push_back(agents[i]->get_agent());
  599. }
  600. rvo.buildAgentTree(raw_agents);
  601. }
  602. regenerate_polygons = false;
  603. regenerate_links = false;
  604. agents_dirty = false;
  605. }
  606. void NavMap::compute_single_step(uint32_t index, RvoAgent **agent) {
  607. (*(agent + index))->get_agent()->computeNeighbors(&rvo);
  608. (*(agent + index))->get_agent()->computeNewVelocity(deltatime);
  609. }
  610. void NavMap::step(real_t p_deltatime) {
  611. deltatime = p_deltatime;
  612. if (controlled_agents.size() > 0) {
  613. thread_process_array(
  614. controlled_agents.size(),
  615. this,
  616. &NavMap::compute_single_step,
  617. controlled_agents.data());
  618. }
  619. }
  620. void NavMap::dispatch_callbacks() {
  621. for (int i(0); i < static_cast<int>(controlled_agents.size()); i++) {
  622. controlled_agents[i]->dispatch_callback();
  623. }
  624. }
  625. void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly) const {
  626. Vector3 from = path[path.size() - 1];
  627. if (from.distance_to(p_to_point) < CMP_EPSILON) {
  628. return;
  629. }
  630. Plane cut_plane;
  631. cut_plane.normal = (from - p_to_point).cross(up);
  632. if (cut_plane.normal == Vector3()) {
  633. return;
  634. }
  635. cut_plane.normal.normalize();
  636. cut_plane.d = cut_plane.normal.dot(from);
  637. while (from_poly != p_to_poly) {
  638. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  639. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  640. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  641. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  642. if (pathway_start.distance_to(pathway_end) > CMP_EPSILON) {
  643. Vector3 inters;
  644. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  645. if (inters.distance_to(p_to_point) > CMP_EPSILON && inters.distance_to(path[path.size() - 1]) > CMP_EPSILON) {
  646. path.push_back(inters);
  647. }
  648. }
  649. }
  650. }
  651. }