nav_map.cpp 25 KB

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