nav_mesh_generator_2d.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. /**************************************************************************/
  2. /* nav_mesh_generator_2d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "nav_mesh_generator_2d.h"
  31. #include "core/config/project_settings.h"
  32. #include "scene/2d/mesh_instance_2d.h"
  33. #include "scene/2d/multimesh_instance_2d.h"
  34. #include "scene/2d/physics_body_2d.h"
  35. #include "scene/2d/polygon_2d.h"
  36. #include "scene/2d/tile_map.h"
  37. #include "scene/resources/capsule_shape_2d.h"
  38. #include "scene/resources/circle_shape_2d.h"
  39. #include "scene/resources/concave_polygon_shape_2d.h"
  40. #include "scene/resources/convex_polygon_shape_2d.h"
  41. #include "scene/resources/navigation_mesh_source_geometry_data_2d.h"
  42. #include "scene/resources/navigation_polygon.h"
  43. #include "scene/resources/rectangle_shape_2d.h"
  44. #include "thirdparty/clipper2/include/clipper2/clipper.h"
  45. #include "thirdparty/misc/polypartition.h"
  46. NavMeshGenerator2D *NavMeshGenerator2D::singleton = nullptr;
  47. Mutex NavMeshGenerator2D::baking_navmesh_mutex;
  48. Mutex NavMeshGenerator2D::generator_task_mutex;
  49. bool NavMeshGenerator2D::use_threads = true;
  50. bool NavMeshGenerator2D::baking_use_multiple_threads = true;
  51. bool NavMeshGenerator2D::baking_use_high_priority_threads = true;
  52. HashSet<Ref<NavigationPolygon>> NavMeshGenerator2D::baking_navmeshes;
  53. HashMap<WorkerThreadPool::TaskID, NavMeshGenerator2D::NavMeshGeneratorTask2D *> NavMeshGenerator2D::generator_tasks;
  54. NavMeshGenerator2D *NavMeshGenerator2D::get_singleton() {
  55. return singleton;
  56. }
  57. NavMeshGenerator2D::NavMeshGenerator2D() {
  58. ERR_FAIL_COND(singleton != nullptr);
  59. singleton = this;
  60. baking_use_multiple_threads = GLOBAL_GET("navigation/baking/thread_model/baking_use_multiple_threads");
  61. baking_use_high_priority_threads = GLOBAL_GET("navigation/baking/thread_model/baking_use_high_priority_threads");
  62. // Using threads might cause problems on certain exports or with the Editor on certain devices.
  63. // This is the main switch to turn threaded navmesh baking off should the need arise.
  64. use_threads = baking_use_multiple_threads && !Engine::get_singleton()->is_editor_hint();
  65. }
  66. NavMeshGenerator2D::~NavMeshGenerator2D() {
  67. cleanup();
  68. }
  69. void NavMeshGenerator2D::sync() {
  70. if (generator_tasks.size() == 0) {
  71. return;
  72. }
  73. baking_navmesh_mutex.lock();
  74. generator_task_mutex.lock();
  75. LocalVector<WorkerThreadPool::TaskID> finished_task_ids;
  76. for (KeyValue<WorkerThreadPool::TaskID, NavMeshGeneratorTask2D *> &E : generator_tasks) {
  77. if (WorkerThreadPool::get_singleton()->is_task_completed(E.key)) {
  78. WorkerThreadPool::get_singleton()->wait_for_task_completion(E.key);
  79. finished_task_ids.push_back(E.key);
  80. NavMeshGeneratorTask2D *generator_task = E.value;
  81. DEV_ASSERT(generator_task->status == NavMeshGeneratorTask2D::TaskStatus::BAKING_FINISHED);
  82. baking_navmeshes.erase(generator_task->navigation_mesh);
  83. if (generator_task->callback.is_valid()) {
  84. generator_emit_callback(generator_task->callback);
  85. }
  86. memdelete(generator_task);
  87. }
  88. }
  89. for (WorkerThreadPool::TaskID finished_task_id : finished_task_ids) {
  90. generator_tasks.erase(finished_task_id);
  91. }
  92. generator_task_mutex.unlock();
  93. baking_navmesh_mutex.unlock();
  94. }
  95. void NavMeshGenerator2D::cleanup() {
  96. baking_navmesh_mutex.lock();
  97. generator_task_mutex.lock();
  98. baking_navmeshes.clear();
  99. for (KeyValue<WorkerThreadPool::TaskID, NavMeshGeneratorTask2D *> &E : generator_tasks) {
  100. WorkerThreadPool::get_singleton()->wait_for_task_completion(E.key);
  101. NavMeshGeneratorTask2D *generator_task = E.value;
  102. memdelete(generator_task);
  103. }
  104. generator_tasks.clear();
  105. generator_task_mutex.unlock();
  106. baking_navmesh_mutex.unlock();
  107. }
  108. void NavMeshGenerator2D::finish() {
  109. cleanup();
  110. }
  111. void NavMeshGenerator2D::parse_source_geometry_data(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_root_node, const Callable &p_callback) {
  112. ERR_FAIL_COND(!Thread::is_main_thread());
  113. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  114. ERR_FAIL_NULL(p_root_node);
  115. ERR_FAIL_COND(!p_root_node->is_inside_tree());
  116. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  117. generator_parse_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_root_node);
  118. if (p_callback.is_valid()) {
  119. generator_emit_callback(p_callback);
  120. }
  121. }
  122. void NavMeshGenerator2D::bake_from_source_geometry_data(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, const Callable &p_callback) {
  123. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  124. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  125. if (p_navigation_mesh->get_outline_count() == 0 && !p_source_geometry_data->has_data()) {
  126. p_navigation_mesh->clear();
  127. if (p_callback.is_valid()) {
  128. generator_emit_callback(p_callback);
  129. }
  130. return;
  131. }
  132. baking_navmesh_mutex.lock();
  133. if (baking_navmeshes.has(p_navigation_mesh)) {
  134. baking_navmesh_mutex.unlock();
  135. ERR_FAIL_MSG("NavigationPolygon is already baking. Wait for current bake to finish.");
  136. }
  137. baking_navmeshes.insert(p_navigation_mesh);
  138. baking_navmesh_mutex.unlock();
  139. generator_bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data);
  140. baking_navmesh_mutex.lock();
  141. baking_navmeshes.erase(p_navigation_mesh);
  142. baking_navmesh_mutex.unlock();
  143. if (p_callback.is_valid()) {
  144. generator_emit_callback(p_callback);
  145. }
  146. }
  147. void NavMeshGenerator2D::bake_from_source_geometry_data_async(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, const Callable &p_callback) {
  148. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  149. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  150. if (p_navigation_mesh->get_outline_count() == 0 && !p_source_geometry_data->has_data()) {
  151. p_navigation_mesh->clear();
  152. if (p_callback.is_valid()) {
  153. generator_emit_callback(p_callback);
  154. }
  155. return;
  156. }
  157. if (!use_threads) {
  158. bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_callback);
  159. return;
  160. }
  161. baking_navmesh_mutex.lock();
  162. if (baking_navmeshes.has(p_navigation_mesh)) {
  163. baking_navmesh_mutex.unlock();
  164. ERR_FAIL_MSG("NavigationPolygon is already baking. Wait for current bake to finish.");
  165. }
  166. baking_navmeshes.insert(p_navigation_mesh);
  167. baking_navmesh_mutex.unlock();
  168. generator_task_mutex.lock();
  169. NavMeshGeneratorTask2D *generator_task = memnew(NavMeshGeneratorTask2D);
  170. generator_task->navigation_mesh = p_navigation_mesh;
  171. generator_task->source_geometry_data = p_source_geometry_data;
  172. generator_task->callback = p_callback;
  173. generator_task->status = NavMeshGeneratorTask2D::TaskStatus::BAKING_STARTED;
  174. generator_task->thread_task_id = WorkerThreadPool::get_singleton()->add_native_task(&NavMeshGenerator2D::generator_thread_bake, generator_task, NavMeshGenerator2D::baking_use_high_priority_threads, "NavMeshGeneratorBake2D");
  175. generator_tasks.insert(generator_task->thread_task_id, generator_task);
  176. generator_task_mutex.unlock();
  177. }
  178. void NavMeshGenerator2D::generator_thread_bake(void *p_arg) {
  179. NavMeshGeneratorTask2D *generator_task = static_cast<NavMeshGeneratorTask2D *>(p_arg);
  180. generator_bake_from_source_geometry_data(generator_task->navigation_mesh, generator_task->source_geometry_data);
  181. generator_task->status = NavMeshGeneratorTask2D::TaskStatus::BAKING_FINISHED;
  182. }
  183. void NavMeshGenerator2D::generator_parse_geometry_node(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node, bool p_recurse_children) {
  184. generator_parse_meshinstance2d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  185. generator_parse_multimeshinstance2d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  186. generator_parse_polygon2d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  187. generator_parse_staticbody2d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  188. generator_parse_tilemap_node(p_navigation_mesh, p_source_geometry_data, p_node);
  189. if (p_recurse_children) {
  190. for (int i = 0; i < p_node->get_child_count(); i++) {
  191. generator_parse_geometry_node(p_navigation_mesh, p_source_geometry_data, p_node->get_child(i), p_recurse_children);
  192. }
  193. }
  194. }
  195. void NavMeshGenerator2D::generator_parse_meshinstance2d_node(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  196. MeshInstance2D *mesh_instance = Object::cast_to<MeshInstance2D>(p_node);
  197. if (mesh_instance == nullptr) {
  198. return;
  199. }
  200. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  201. if (!(parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH)) {
  202. return;
  203. }
  204. Ref<Mesh> mesh = mesh_instance->get_mesh();
  205. if (!mesh.is_valid()) {
  206. return;
  207. }
  208. const Transform2D mesh_instance_xform = p_source_geometry_data->root_node_transform * mesh_instance->get_global_transform();
  209. using namespace Clipper2Lib;
  210. Paths64 subject_paths, dummy_clip_paths;
  211. for (int i = 0; i < mesh->get_surface_count(); i++) {
  212. if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  213. continue;
  214. }
  215. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FLAG_USE_2D_VERTICES)) {
  216. continue;
  217. }
  218. Path64 subject_path;
  219. int index_count = 0;
  220. if (mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  221. index_count = mesh->surface_get_array_index_len(i);
  222. } else {
  223. index_count = mesh->surface_get_array_len(i);
  224. }
  225. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  226. Array a = mesh->surface_get_arrays(i);
  227. Vector<Vector2> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  228. if (mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  229. Vector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  230. for (int vertex_index : mesh_indices) {
  231. const Vector2 &vertex = mesh_vertices[vertex_index];
  232. const Point64 &point = Point64(vertex.x, vertex.y);
  233. subject_path.push_back(point);
  234. }
  235. } else {
  236. for (const Vector2 &vertex : mesh_vertices) {
  237. const Point64 &point = Point64(vertex.x, vertex.y);
  238. subject_path.push_back(point);
  239. }
  240. }
  241. subject_paths.push_back(subject_path);
  242. }
  243. Paths64 path_solution;
  244. path_solution = Union(subject_paths, dummy_clip_paths, FillRule::NonZero);
  245. //path_solution = RamerDouglasPeucker(path_solution, 0.025);
  246. Vector<Vector<Vector2>> polypaths;
  247. for (const Path64 &scaled_path : path_solution) {
  248. Vector<Vector2> shape_outline;
  249. for (const Point64 &scaled_point : scaled_path) {
  250. shape_outline.push_back(Point2(static_cast<real_t>(scaled_point.x), static_cast<real_t>(scaled_point.y)));
  251. }
  252. for (int i = 0; i < shape_outline.size(); i++) {
  253. shape_outline.write[i] = mesh_instance_xform.xform(shape_outline[i]);
  254. }
  255. p_source_geometry_data->add_obstruction_outline(shape_outline);
  256. }
  257. }
  258. void NavMeshGenerator2D::generator_parse_multimeshinstance2d_node(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  259. MultiMeshInstance2D *multimesh_instance = Object::cast_to<MultiMeshInstance2D>(p_node);
  260. if (multimesh_instance == nullptr) {
  261. return;
  262. }
  263. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  264. if (!(parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH)) {
  265. return;
  266. }
  267. Ref<MultiMesh> multimesh = multimesh_instance->get_multimesh();
  268. if (!(multimesh.is_valid() && multimesh->get_transform_format() == MultiMesh::TRANSFORM_2D)) {
  269. return;
  270. }
  271. Ref<Mesh> mesh = multimesh->get_mesh();
  272. if (!mesh.is_valid()) {
  273. return;
  274. }
  275. using namespace Clipper2Lib;
  276. Paths64 mesh_subject_paths, dummy_clip_paths;
  277. for (int i = 0; i < mesh->get_surface_count(); i++) {
  278. if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  279. continue;
  280. }
  281. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FLAG_USE_2D_VERTICES)) {
  282. continue;
  283. }
  284. Path64 subject_path;
  285. int index_count = 0;
  286. if (mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  287. index_count = mesh->surface_get_array_index_len(i);
  288. } else {
  289. index_count = mesh->surface_get_array_len(i);
  290. }
  291. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  292. Array a = mesh->surface_get_arrays(i);
  293. Vector<Vector2> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  294. if (mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  295. Vector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  296. for (int vertex_index : mesh_indices) {
  297. const Vector2 &vertex = mesh_vertices[vertex_index];
  298. const Point64 &point = Point64(vertex.x, vertex.y);
  299. subject_path.push_back(point);
  300. }
  301. } else {
  302. for (const Vector2 &vertex : mesh_vertices) {
  303. const Point64 &point = Point64(vertex.x, vertex.y);
  304. subject_path.push_back(point);
  305. }
  306. }
  307. mesh_subject_paths.push_back(subject_path);
  308. }
  309. Paths64 mesh_path_solution = Union(mesh_subject_paths, dummy_clip_paths, FillRule::NonZero);
  310. //path_solution = RamerDouglasPeucker(path_solution, 0.025);
  311. int multimesh_instance_count = multimesh->get_visible_instance_count();
  312. if (multimesh_instance_count == -1) {
  313. multimesh_instance_count = multimesh->get_instance_count();
  314. }
  315. const Transform2D multimesh_instance_xform = p_source_geometry_data->root_node_transform * multimesh_instance->get_global_transform();
  316. for (int i = 0; i < multimesh_instance_count; i++) {
  317. const Transform2D multimesh_instance_mesh_instance_xform = multimesh_instance_xform * multimesh->get_instance_transform_2d(i);
  318. for (const Path64 &mesh_path : mesh_path_solution) {
  319. Vector<Vector2> shape_outline;
  320. for (const Point64 &mesh_path_point : mesh_path) {
  321. shape_outline.push_back(Point2(static_cast<real_t>(mesh_path_point.x), static_cast<real_t>(mesh_path_point.y)));
  322. }
  323. for (int j = 0; j < shape_outline.size(); j++) {
  324. shape_outline.write[j] = multimesh_instance_mesh_instance_xform.xform(shape_outline[j]);
  325. }
  326. p_source_geometry_data->add_obstruction_outline(shape_outline);
  327. }
  328. }
  329. }
  330. void NavMeshGenerator2D::generator_parse_polygon2d_node(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  331. Polygon2D *polygon_2d = Object::cast_to<Polygon2D>(p_node);
  332. if (polygon_2d == nullptr) {
  333. return;
  334. }
  335. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  336. if (parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH) {
  337. const Transform2D polygon_2d_xform = p_source_geometry_data->root_node_transform * polygon_2d->get_global_transform();
  338. Vector<Vector2> shape_outline = polygon_2d->get_polygon();
  339. for (int i = 0; i < shape_outline.size(); i++) {
  340. shape_outline.write[i] = polygon_2d_xform.xform(shape_outline[i]);
  341. }
  342. p_source_geometry_data->add_obstruction_outline(shape_outline);
  343. }
  344. }
  345. void NavMeshGenerator2D::generator_parse_staticbody2d_node(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  346. StaticBody2D *static_body = Object::cast_to<StaticBody2D>(p_node);
  347. if (static_body == nullptr) {
  348. return;
  349. }
  350. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  351. if (!(parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH)) {
  352. return;
  353. }
  354. uint32_t parsed_collision_mask = p_navigation_mesh->get_parsed_collision_mask();
  355. if (!(static_body->get_collision_layer() & parsed_collision_mask)) {
  356. return;
  357. }
  358. List<uint32_t> shape_owners;
  359. static_body->get_shape_owners(&shape_owners);
  360. for (uint32_t shape_owner : shape_owners) {
  361. if (static_body->is_shape_owner_disabled(shape_owner)) {
  362. continue;
  363. }
  364. const int shape_count = static_body->shape_owner_get_shape_count(shape_owner);
  365. for (int shape_index = 0; shape_index < shape_count; shape_index++) {
  366. Ref<Shape2D> s = static_body->shape_owner_get_shape(shape_owner, shape_index);
  367. if (s.is_null()) {
  368. continue;
  369. }
  370. const Transform2D static_body_xform = p_source_geometry_data->root_node_transform * static_body->get_global_transform() * static_body->shape_owner_get_transform(shape_owner);
  371. RectangleShape2D *rectangle_shape = Object::cast_to<RectangleShape2D>(*s);
  372. if (rectangle_shape) {
  373. Vector<Vector2> shape_outline;
  374. const Vector2 &rectangle_size = rectangle_shape->get_size();
  375. shape_outline.resize(5);
  376. shape_outline.write[0] = static_body_xform.xform(-rectangle_size * 0.5);
  377. shape_outline.write[1] = static_body_xform.xform(Vector2(rectangle_size.x, -rectangle_size.y) * 0.5);
  378. shape_outline.write[2] = static_body_xform.xform(rectangle_size * 0.5);
  379. shape_outline.write[3] = static_body_xform.xform(Vector2(-rectangle_size.x, rectangle_size.y) * 0.5);
  380. shape_outline.write[4] = static_body_xform.xform(-rectangle_size * 0.5);
  381. p_source_geometry_data->add_obstruction_outline(shape_outline);
  382. }
  383. CapsuleShape2D *capsule_shape = Object::cast_to<CapsuleShape2D>(*s);
  384. if (capsule_shape) {
  385. const real_t capsule_height = capsule_shape->get_height();
  386. const real_t capsule_radius = capsule_shape->get_radius();
  387. Vector<Vector2> shape_outline;
  388. const real_t turn_step = Math_TAU / 12.0;
  389. shape_outline.resize(14);
  390. int shape_outline_inx = 0;
  391. for (int i = 0; i < 12; i++) {
  392. Vector2 ofs = Vector2(0, (i > 3 && i <= 9) ? -capsule_height * 0.5 + capsule_radius : capsule_height * 0.5 - capsule_radius);
  393. shape_outline.write[shape_outline_inx] = static_body_xform.xform(Vector2(Math::sin(i * turn_step), Math::cos(i * turn_step)) * capsule_radius + ofs);
  394. shape_outline_inx += 1;
  395. if (i == 3 || i == 9) {
  396. shape_outline.write[shape_outline_inx] = static_body_xform.xform(Vector2(Math::sin(i * turn_step), Math::cos(i * turn_step)) * capsule_radius - ofs);
  397. shape_outline_inx += 1;
  398. }
  399. }
  400. p_source_geometry_data->add_obstruction_outline(shape_outline);
  401. }
  402. CircleShape2D *circle_shape = Object::cast_to<CircleShape2D>(*s);
  403. if (circle_shape) {
  404. const real_t circle_radius = circle_shape->get_radius();
  405. Vector<Vector2> shape_outline;
  406. int circle_edge_count = 12;
  407. shape_outline.resize(circle_edge_count);
  408. const real_t turn_step = Math_TAU / real_t(circle_edge_count);
  409. for (int i = 0; i < circle_edge_count; i++) {
  410. shape_outline.write[i] = static_body_xform.xform(Vector2(Math::cos(i * turn_step), Math::sin(i * turn_step)) * circle_radius);
  411. }
  412. p_source_geometry_data->add_obstruction_outline(shape_outline);
  413. }
  414. ConcavePolygonShape2D *concave_polygon_shape = Object::cast_to<ConcavePolygonShape2D>(*s);
  415. if (concave_polygon_shape) {
  416. Vector<Vector2> shape_outline = concave_polygon_shape->get_segments();
  417. for (int i = 0; i < shape_outline.size(); i++) {
  418. shape_outline.write[i] = static_body_xform.xform(shape_outline[i]);
  419. }
  420. p_source_geometry_data->add_obstruction_outline(shape_outline);
  421. }
  422. ConvexPolygonShape2D *convex_polygon_shape = Object::cast_to<ConvexPolygonShape2D>(*s);
  423. if (convex_polygon_shape) {
  424. Vector<Vector2> shape_outline = convex_polygon_shape->get_points();
  425. for (int i = 0; i < shape_outline.size(); i++) {
  426. shape_outline.write[i] = static_body_xform.xform(shape_outline[i]);
  427. }
  428. p_source_geometry_data->add_obstruction_outline(shape_outline);
  429. }
  430. }
  431. }
  432. }
  433. void NavMeshGenerator2D::generator_parse_tilemap_node(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  434. TileMap *tilemap = Object::cast_to<TileMap>(p_node);
  435. if (tilemap == nullptr) {
  436. return;
  437. }
  438. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  439. uint32_t parsed_collision_mask = p_navigation_mesh->get_parsed_collision_mask();
  440. if (tilemap->get_layers_count() <= 0) {
  441. return;
  442. }
  443. int tilemap_layer = 0; // only main tile map layer is supported
  444. Ref<TileSet> tile_set = tilemap->get_tileset();
  445. if (!tile_set.is_valid()) {
  446. return;
  447. }
  448. int physics_layers_count = tile_set->get_physics_layers_count();
  449. int navigation_layers_count = tile_set->get_navigation_layers_count();
  450. if (physics_layers_count <= 0 && navigation_layers_count <= 0) {
  451. return;
  452. }
  453. const Transform2D tilemap_xform = p_source_geometry_data->root_node_transform * tilemap->get_global_transform();
  454. TypedArray<Vector2i> used_cells = tilemap->get_used_cells(tilemap_layer);
  455. for (int used_cell_index = 0; used_cell_index < used_cells.size(); used_cell_index++) {
  456. const Vector2i &cell = used_cells[used_cell_index];
  457. const TileData *tile_data = tilemap->get_cell_tile_data(tilemap_layer, cell, false);
  458. if (tile_data == nullptr) {
  459. continue;
  460. }
  461. Transform2D tile_transform;
  462. tile_transform.set_origin(tilemap->map_to_local(cell));
  463. const Transform2D tile_transform_offset = tilemap_xform * tile_transform;
  464. if (navigation_layers_count > 0) {
  465. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(tilemap_layer);
  466. if (navigation_polygon.is_valid()) {
  467. for (int outline_index = 0; outline_index < navigation_polygon->get_outline_count(); outline_index++) {
  468. const Vector<Vector2> &navigation_polygon_outline = navigation_polygon->get_outline(outline_index);
  469. if (navigation_polygon_outline.size() == 0) {
  470. continue;
  471. }
  472. Vector<Vector2> traversable_outline;
  473. traversable_outline.resize(navigation_polygon_outline.size());
  474. const Vector2 *navigation_polygon_outline_ptr = navigation_polygon_outline.ptr();
  475. Vector2 *traversable_outline_ptrw = traversable_outline.ptrw();
  476. for (int traversable_outline_index = 0; traversable_outline_index < traversable_outline.size(); traversable_outline_index++) {
  477. traversable_outline_ptrw[traversable_outline_index] = tile_transform_offset.xform(navigation_polygon_outline_ptr[traversable_outline_index]);
  478. }
  479. p_source_geometry_data->_add_traversable_outline(traversable_outline);
  480. }
  481. }
  482. }
  483. if (physics_layers_count > 0 && (parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH) && (tile_set->get_physics_layer_collision_layer(tilemap_layer) & parsed_collision_mask)) {
  484. for (int collision_polygon_index = 0; collision_polygon_index < tile_data->get_collision_polygons_count(tilemap_layer); collision_polygon_index++) {
  485. const Vector<Vector2> &collision_polygon_points = tile_data->get_collision_polygon_points(tilemap_layer, collision_polygon_index);
  486. if (collision_polygon_points.size() == 0) {
  487. continue;
  488. }
  489. Vector<Vector2> obstruction_outline;
  490. obstruction_outline.resize(collision_polygon_points.size());
  491. const Vector2 *collision_polygon_points_ptr = collision_polygon_points.ptr();
  492. Vector2 *obstruction_outline_ptrw = obstruction_outline.ptrw();
  493. for (int obstruction_outline_index = 0; obstruction_outline_index < obstruction_outline.size(); obstruction_outline_index++) {
  494. obstruction_outline_ptrw[obstruction_outline_index] = tile_transform_offset.xform(collision_polygon_points_ptr[obstruction_outline_index]);
  495. }
  496. p_source_geometry_data->_add_obstruction_outline(obstruction_outline);
  497. }
  498. }
  499. }
  500. }
  501. void NavMeshGenerator2D::generator_parse_source_geometry_data(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_root_node) {
  502. List<Node *> parse_nodes;
  503. if (p_navigation_mesh->get_source_geometry_mode() == NavigationPolygon::SOURCE_GEOMETRY_ROOT_NODE_CHILDREN) {
  504. parse_nodes.push_back(p_root_node);
  505. } else {
  506. p_root_node->get_tree()->get_nodes_in_group(p_navigation_mesh->get_source_geometry_group_name(), &parse_nodes);
  507. }
  508. Transform2D root_node_transform = Transform2D();
  509. if (Object::cast_to<Node2D>(p_root_node)) {
  510. root_node_transform = Object::cast_to<Node2D>(p_root_node)->get_global_transform().affine_inverse();
  511. }
  512. p_source_geometry_data->clear();
  513. p_source_geometry_data->root_node_transform = root_node_transform;
  514. bool recurse_children = p_navigation_mesh->get_source_geometry_mode() != NavigationPolygon::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  515. for (Node *E : parse_nodes) {
  516. generator_parse_geometry_node(p_navigation_mesh, p_source_geometry_data, E, recurse_children);
  517. }
  518. };
  519. static void generator_recursive_process_polytree_items(List<TPPLPoly> &p_tppl_in_polygon, const Clipper2Lib::PolyPath64 *p_polypath_item) {
  520. using namespace Clipper2Lib;
  521. Vector<Vector2> polygon_vertices;
  522. for (const Point64 &polypath_point : p_polypath_item->Polygon()) {
  523. polygon_vertices.push_back(Vector2(static_cast<real_t>(polypath_point.x), static_cast<real_t>(polypath_point.y)));
  524. }
  525. TPPLPoly tp;
  526. tp.Init(polygon_vertices.size());
  527. for (int j = 0; j < polygon_vertices.size(); j++) {
  528. tp[j] = polygon_vertices[j];
  529. }
  530. if (p_polypath_item->IsHole()) {
  531. tp.SetOrientation(TPPL_ORIENTATION_CW);
  532. tp.SetHole(true);
  533. } else {
  534. tp.SetOrientation(TPPL_ORIENTATION_CCW);
  535. }
  536. p_tppl_in_polygon.push_back(tp);
  537. for (size_t i = 0; i < p_polypath_item->Count(); i++) {
  538. const PolyPath64 *polypath_item = p_polypath_item->Child(i);
  539. generator_recursive_process_polytree_items(p_tppl_in_polygon, polypath_item);
  540. }
  541. }
  542. bool NavMeshGenerator2D::generator_emit_callback(const Callable &p_callback) {
  543. ERR_FAIL_COND_V(!p_callback.is_valid(), false);
  544. Callable::CallError ce;
  545. Variant result;
  546. p_callback.callp(nullptr, 0, result, ce);
  547. return ce.error == Callable::CallError::CALL_OK;
  548. }
  549. void NavMeshGenerator2D::generator_bake_from_source_geometry_data(Ref<NavigationPolygon> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data) {
  550. if (p_navigation_mesh.is_null() || p_source_geometry_data.is_null()) {
  551. return;
  552. }
  553. if (p_navigation_mesh->get_outline_count() == 0 && !p_source_geometry_data->has_data()) {
  554. return;
  555. }
  556. int outline_count = p_navigation_mesh->get_outline_count();
  557. const Vector<Vector<Vector2>> &traversable_outlines = p_source_geometry_data->_get_traversable_outlines();
  558. const Vector<Vector<Vector2>> &obstruction_outlines = p_source_geometry_data->_get_obstruction_outlines();
  559. if (outline_count == 0 && traversable_outlines.size() == 0) {
  560. return;
  561. }
  562. using namespace Clipper2Lib;
  563. Paths64 traversable_polygon_paths;
  564. Paths64 obstruction_polygon_paths;
  565. for (int i = 0; i < outline_count; i++) {
  566. const Vector<Vector2> &traversable_outline = p_navigation_mesh->get_outline(i);
  567. Path64 subject_path;
  568. for (const Vector2 &traversable_point : traversable_outline) {
  569. const Point64 &point = Point64(traversable_point.x, traversable_point.y);
  570. subject_path.push_back(point);
  571. }
  572. traversable_polygon_paths.push_back(subject_path);
  573. }
  574. for (const Vector<Vector2> &traversable_outline : traversable_outlines) {
  575. Path64 subject_path;
  576. for (const Vector2 &traversable_point : traversable_outline) {
  577. const Point64 &point = Point64(traversable_point.x, traversable_point.y);
  578. subject_path.push_back(point);
  579. }
  580. traversable_polygon_paths.push_back(subject_path);
  581. }
  582. for (const Vector<Vector2> &obstruction_outline : obstruction_outlines) {
  583. Path64 clip_path;
  584. for (const Vector2 &obstruction_point : obstruction_outline) {
  585. const Point64 &point = Point64(obstruction_point.x, obstruction_point.y);
  586. clip_path.push_back(point);
  587. }
  588. obstruction_polygon_paths.push_back(clip_path);
  589. }
  590. Paths64 path_solution;
  591. // first merge all traversable polygons according to user specified fill rule
  592. Paths64 dummy_clip_path;
  593. traversable_polygon_paths = Union(traversable_polygon_paths, dummy_clip_path, FillRule::NonZero);
  594. // merge all obstruction polygons, don't allow holes for what is considered "solid" 2D geometry
  595. obstruction_polygon_paths = Union(obstruction_polygon_paths, dummy_clip_path, FillRule::NonZero);
  596. path_solution = Difference(traversable_polygon_paths, obstruction_polygon_paths, FillRule::NonZero);
  597. real_t agent_radius_offset = p_navigation_mesh->get_agent_radius();
  598. if (agent_radius_offset > 0.0) {
  599. path_solution = InflatePaths(path_solution, -agent_radius_offset, JoinType::Miter, EndType::Polygon);
  600. }
  601. //path_solution = RamerDouglasPeucker(path_solution, 0.025); //
  602. Vector<Vector<Vector2>> new_baked_outlines;
  603. for (const Path64 &scaled_path : path_solution) {
  604. Vector<Vector2> polypath;
  605. for (const Point64 &scaled_point : scaled_path) {
  606. polypath.push_back(Vector2(static_cast<real_t>(scaled_point.x), static_cast<real_t>(scaled_point.y)));
  607. }
  608. new_baked_outlines.push_back(polypath);
  609. }
  610. if (new_baked_outlines.size() == 0) {
  611. p_navigation_mesh->set_vertices(Vector<Vector2>());
  612. p_navigation_mesh->clear_polygons();
  613. return;
  614. }
  615. Paths64 polygon_paths;
  616. for (const Vector<Vector2> &baked_outline : new_baked_outlines) {
  617. Path64 polygon_path;
  618. for (const Vector2 &baked_outline_point : baked_outline) {
  619. const Point64 &point = Point64(baked_outline_point.x, baked_outline_point.y);
  620. polygon_path.push_back(point);
  621. }
  622. polygon_paths.push_back(polygon_path);
  623. }
  624. ClipType clipper_cliptype = ClipType::Union;
  625. List<TPPLPoly> tppl_in_polygon, tppl_out_polygon;
  626. PolyTree64 polytree;
  627. Clipper64 clipper_64;
  628. clipper_64.AddSubject(polygon_paths);
  629. clipper_64.Execute(clipper_cliptype, FillRule::NonZero, polytree);
  630. for (size_t i = 0; i < polytree.Count(); i++) {
  631. const PolyPath64 *polypath_item = polytree[i];
  632. generator_recursive_process_polytree_items(tppl_in_polygon, polypath_item);
  633. }
  634. TPPLPartition tpart;
  635. if (tpart.ConvexPartition_HM(&tppl_in_polygon, &tppl_out_polygon) == 0) { //failed!
  636. ERR_PRINT("NavigationPolygon Convex partition failed. Unable to create a valid NavigationMesh from defined polygon outline paths.");
  637. p_navigation_mesh->set_vertices(Vector<Vector2>());
  638. p_navigation_mesh->clear_polygons();
  639. return;
  640. }
  641. Vector<Vector2> new_vertices;
  642. Vector<Vector<int>> new_polygons;
  643. HashMap<Vector2, int> points;
  644. for (List<TPPLPoly>::Element *I = tppl_out_polygon.front(); I; I = I->next()) {
  645. TPPLPoly &tp = I->get();
  646. Vector<int> new_polygon;
  647. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  648. HashMap<Vector2, int>::Iterator E = points.find(tp[i]);
  649. if (!E) {
  650. E = points.insert(tp[i], new_vertices.size());
  651. new_vertices.push_back(tp[i]);
  652. }
  653. new_polygon.push_back(E->value);
  654. }
  655. new_polygons.push_back(new_polygon);
  656. }
  657. p_navigation_mesh->set_vertices(new_vertices);
  658. p_navigation_mesh->clear_polygons();
  659. for (int i = 0; i < new_polygons.size(); i++) {
  660. p_navigation_mesh->add_polygon(new_polygons[i]);
  661. }
  662. }