navigation_mesh_generator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*************************************************************************/
  2. /* navigation_mesh_generator.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. #ifndef _3D_DISABLED
  31. #include "navigation_mesh_generator.h"
  32. #include "core/math/convex_hull.h"
  33. #include "core/os/thread.h"
  34. #include "scene/3d/collision_shape_3d.h"
  35. #include "scene/3d/mesh_instance_3d.h"
  36. #include "scene/3d/multimesh_instance_3d.h"
  37. #include "scene/3d/physics_body_3d.h"
  38. #include "scene/resources/box_shape_3d.h"
  39. #include "scene/resources/capsule_shape_3d.h"
  40. #include "scene/resources/concave_polygon_shape_3d.h"
  41. #include "scene/resources/convex_polygon_shape_3d.h"
  42. #include "scene/resources/cylinder_shape_3d.h"
  43. #include "scene/resources/primitive_meshes.h"
  44. #include "scene/resources/shape_3d.h"
  45. #include "scene/resources/sphere_shape_3d.h"
  46. #include "scene/resources/world_boundary_shape_3d.h"
  47. #ifdef TOOLS_ENABLED
  48. #include "editor/editor_node.h"
  49. #include "editor/editor_settings.h"
  50. #endif
  51. #include "modules/modules_enabled.gen.h" // For csg, gridmap.
  52. #ifdef MODULE_CSG_ENABLED
  53. #include "modules/csg/csg_shape.h"
  54. #endif
  55. #ifdef MODULE_GRIDMAP_ENABLED
  56. #include "modules/gridmap/grid_map.h"
  57. #endif
  58. NavigationMeshGenerator *NavigationMeshGenerator::singleton = nullptr;
  59. void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_vertices) {
  60. p_vertices.push_back(p_vec3.x);
  61. p_vertices.push_back(p_vec3.y);
  62. p_vertices.push_back(p_vec3.z);
  63. }
  64. void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  65. int current_vertex_count;
  66. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  67. current_vertex_count = p_vertices.size() / 3;
  68. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  69. continue;
  70. }
  71. int index_count = 0;
  72. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  73. index_count = p_mesh->surface_get_array_index_len(i);
  74. } else {
  75. index_count = p_mesh->surface_get_array_len(i);
  76. }
  77. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  78. int face_count = index_count / 3;
  79. Array a = p_mesh->surface_get_arrays(i);
  80. Vector<Vector3> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  81. const Vector3 *vr = mesh_vertices.ptr();
  82. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  83. Vector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  84. const int *ir = mesh_indices.ptr();
  85. for (int j = 0; j < mesh_vertices.size(); j++) {
  86. _add_vertex(p_xform.xform(vr[j]), p_vertices);
  87. }
  88. for (int j = 0; j < face_count; j++) {
  89. // CCW
  90. p_indices.push_back(current_vertex_count + (ir[j * 3 + 0]));
  91. p_indices.push_back(current_vertex_count + (ir[j * 3 + 2]));
  92. p_indices.push_back(current_vertex_count + (ir[j * 3 + 1]));
  93. }
  94. } else {
  95. face_count = mesh_vertices.size() / 3;
  96. for (int j = 0; j < face_count; j++) {
  97. _add_vertex(p_xform.xform(vr[j * 3 + 0]), p_vertices);
  98. _add_vertex(p_xform.xform(vr[j * 3 + 2]), p_vertices);
  99. _add_vertex(p_xform.xform(vr[j * 3 + 1]), p_vertices);
  100. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  101. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  102. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  103. }
  104. }
  105. }
  106. }
  107. void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  108. int face_count = p_faces.size() / 3;
  109. int current_vertex_count = p_vertices.size() / 3;
  110. for (int j = 0; j < face_count; j++) {
  111. _add_vertex(p_xform.xform(p_faces[j * 3 + 0]), p_vertices);
  112. _add_vertex(p_xform.xform(p_faces[j * 3 + 1]), p_vertices);
  113. _add_vertex(p_xform.xform(p_faces[j * 3 + 2]), p_vertices);
  114. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  115. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  116. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  117. }
  118. }
  119. void NavigationMeshGenerator::_parse_geometry(Transform3D p_accumulated_transform, Node *p_node, Vector<float> &p_vertices, Vector<int> &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) {
  120. if (Object::cast_to<MeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  121. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_node);
  122. Ref<Mesh> mesh = mesh_instance->get_mesh();
  123. if (mesh.is_valid()) {
  124. _add_mesh(mesh, p_accumulated_transform * mesh_instance->get_transform(), p_vertices, p_indices);
  125. }
  126. }
  127. if (Object::cast_to<MultiMeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  128. MultiMeshInstance3D *multimesh_instance = Object::cast_to<MultiMeshInstance3D>(p_node);
  129. Ref<MultiMesh> multimesh = multimesh_instance->get_multimesh();
  130. Ref<Mesh> mesh = multimesh->get_mesh();
  131. if (mesh.is_valid()) {
  132. int n = multimesh->get_visible_instance_count();
  133. if (n == -1) {
  134. n = multimesh->get_instance_count();
  135. }
  136. for (int i = 0; i < n; i++) {
  137. _add_mesh(mesh, p_accumulated_transform * multimesh->get_instance_transform(i), p_vertices, p_indices);
  138. }
  139. }
  140. }
  141. #ifdef MODULE_CSG_ENABLED
  142. if (Object::cast_to<CSGShape3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  143. CSGShape3D *csg_shape = Object::cast_to<CSGShape3D>(p_node);
  144. Array meshes = csg_shape->get_meshes();
  145. if (!meshes.is_empty()) {
  146. Ref<Mesh> mesh = meshes[1];
  147. if (mesh.is_valid()) {
  148. _add_mesh(mesh, p_accumulated_transform * csg_shape->get_transform(), p_vertices, p_indices);
  149. }
  150. }
  151. }
  152. #endif
  153. if (Object::cast_to<StaticBody3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) {
  154. StaticBody3D *static_body = Object::cast_to<StaticBody3D>(p_node);
  155. if (static_body->get_collision_layer() & p_collision_mask) {
  156. for (int i = 0; i < p_node->get_child_count(); ++i) {
  157. Node *child = p_node->get_child(i);
  158. if (Object::cast_to<CollisionShape3D>(child)) {
  159. CollisionShape3D *col_shape = Object::cast_to<CollisionShape3D>(child);
  160. Transform3D transform = p_accumulated_transform * static_body->get_transform() * col_shape->get_transform();
  161. Ref<Mesh> mesh;
  162. Ref<Shape3D> s = col_shape->get_shape();
  163. BoxShape3D *box = Object::cast_to<BoxShape3D>(*s);
  164. if (box) {
  165. Ref<BoxMesh> box_mesh;
  166. box_mesh.instantiate();
  167. box_mesh->set_size(box->get_size());
  168. mesh = box_mesh;
  169. }
  170. CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s);
  171. if (capsule) {
  172. Ref<CapsuleMesh> capsule_mesh;
  173. capsule_mesh.instantiate();
  174. capsule_mesh->set_radius(capsule->get_radius());
  175. capsule_mesh->set_height(capsule->get_height());
  176. mesh = capsule_mesh;
  177. }
  178. CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s);
  179. if (cylinder) {
  180. Ref<CylinderMesh> cylinder_mesh;
  181. cylinder_mesh.instantiate();
  182. cylinder_mesh->set_height(cylinder->get_height());
  183. cylinder_mesh->set_bottom_radius(cylinder->get_radius());
  184. cylinder_mesh->set_top_radius(cylinder->get_radius());
  185. mesh = cylinder_mesh;
  186. }
  187. SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s);
  188. if (sphere) {
  189. Ref<SphereMesh> sphere_mesh;
  190. sphere_mesh.instantiate();
  191. sphere_mesh->set_radius(sphere->get_radius());
  192. sphere_mesh->set_height(sphere->get_radius() * 2.0);
  193. mesh = sphere_mesh;
  194. }
  195. ConcavePolygonShape3D *concave_polygon = Object::cast_to<ConcavePolygonShape3D>(*s);
  196. if (concave_polygon) {
  197. _add_faces(concave_polygon->get_faces(), transform, p_vertices, p_indices);
  198. }
  199. ConvexPolygonShape3D *convex_polygon = Object::cast_to<ConvexPolygonShape3D>(*s);
  200. if (convex_polygon) {
  201. Vector<Vector3> varr = Variant(convex_polygon->get_points());
  202. Geometry3D::MeshData md;
  203. Error err = ConvexHullComputer::convex_hull(varr, md);
  204. if (err == OK) {
  205. PackedVector3Array faces;
  206. for (int j = 0; j < md.faces.size(); ++j) {
  207. Geometry3D::MeshData::Face face = md.faces[j];
  208. for (int k = 2; k < face.indices.size(); ++k) {
  209. faces.push_back(md.vertices[face.indices[0]]);
  210. faces.push_back(md.vertices[face.indices[k - 1]]);
  211. faces.push_back(md.vertices[face.indices[k]]);
  212. }
  213. }
  214. _add_faces(faces, transform, p_vertices, p_indices);
  215. }
  216. }
  217. if (mesh.is_valid()) {
  218. _add_mesh(mesh, transform, p_vertices, p_indices);
  219. }
  220. }
  221. }
  222. }
  223. }
  224. #ifdef MODULE_GRIDMAP_ENABLED
  225. GridMap *gridmap = Object::cast_to<GridMap>(p_node);
  226. if (gridmap) {
  227. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  228. Array meshes = gridmap->get_meshes();
  229. Transform3D xform = gridmap->get_transform();
  230. for (int i = 0; i < meshes.size(); i += 2) {
  231. Ref<Mesh> mesh = meshes[i + 1];
  232. if (mesh.is_valid()) {
  233. _add_mesh(mesh, p_accumulated_transform * xform * (Transform3D)meshes[i], p_vertices, p_indices);
  234. }
  235. }
  236. }
  237. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES && (gridmap->get_collision_layer() & p_collision_mask)) {
  238. Array shapes = gridmap->get_collision_shapes();
  239. for (int i = 0; i < shapes.size(); i += 2) {
  240. RID shape = shapes[i + 1];
  241. PhysicsServer3D::ShapeType type = PhysicsServer3D::get_singleton()->shape_get_type(shape);
  242. Variant data = PhysicsServer3D::get_singleton()->shape_get_data(shape);
  243. Ref<Mesh> mesh;
  244. switch (type) {
  245. case PhysicsServer3D::SHAPE_SPHERE: {
  246. real_t radius = data;
  247. Ref<SphereMesh> sphere_mesh;
  248. sphere_mesh.instantiate();
  249. sphere_mesh->set_radius(radius);
  250. sphere_mesh->set_height(radius * 2.0);
  251. mesh = sphere_mesh;
  252. } break;
  253. case PhysicsServer3D::SHAPE_BOX: {
  254. Vector3 extents = data;
  255. Ref<BoxMesh> box_mesh;
  256. box_mesh.instantiate();
  257. box_mesh->set_size(2.0 * extents);
  258. mesh = box_mesh;
  259. } break;
  260. case PhysicsServer3D::SHAPE_CAPSULE: {
  261. Dictionary dict = data;
  262. real_t radius = dict["radius"];
  263. real_t height = dict["height"];
  264. Ref<CapsuleMesh> capsule_mesh;
  265. capsule_mesh.instantiate();
  266. capsule_mesh->set_radius(radius);
  267. capsule_mesh->set_height(height);
  268. mesh = capsule_mesh;
  269. } break;
  270. case PhysicsServer3D::SHAPE_CYLINDER: {
  271. Dictionary dict = data;
  272. real_t radius = dict["radius"];
  273. real_t height = dict["height"];
  274. Ref<CylinderMesh> cylinder_mesh;
  275. cylinder_mesh.instantiate();
  276. cylinder_mesh->set_height(height);
  277. cylinder_mesh->set_bottom_radius(radius);
  278. cylinder_mesh->set_top_radius(radius);
  279. mesh = cylinder_mesh;
  280. } break;
  281. case PhysicsServer3D::SHAPE_CONVEX_POLYGON: {
  282. PackedVector3Array vertices = data;
  283. Geometry3D::MeshData md;
  284. Error err = ConvexHullComputer::convex_hull(vertices, md);
  285. if (err == OK) {
  286. PackedVector3Array faces;
  287. for (int j = 0; j < md.faces.size(); ++j) {
  288. Geometry3D::MeshData::Face face = md.faces[j];
  289. for (int k = 2; k < face.indices.size(); ++k) {
  290. faces.push_back(md.vertices[face.indices[0]]);
  291. faces.push_back(md.vertices[face.indices[k - 1]]);
  292. faces.push_back(md.vertices[face.indices[k]]);
  293. }
  294. }
  295. _add_faces(faces, shapes[i], p_vertices, p_indices);
  296. }
  297. } break;
  298. case PhysicsServer3D::SHAPE_CONCAVE_POLYGON: {
  299. Dictionary dict = data;
  300. PackedVector3Array faces = Variant(dict["faces"]);
  301. _add_faces(faces, shapes[i], p_vertices, p_indices);
  302. } break;
  303. default: {
  304. WARN_PRINT("Unsupported collision shape type.");
  305. } break;
  306. }
  307. if (mesh.is_valid()) {
  308. _add_mesh(mesh, shapes[i], p_vertices, p_indices);
  309. }
  310. }
  311. }
  312. }
  313. #endif
  314. if (Object::cast_to<Node3D>(p_node)) {
  315. Node3D *spatial = Object::cast_to<Node3D>(p_node);
  316. p_accumulated_transform = p_accumulated_transform * spatial->get_transform();
  317. }
  318. if (p_recurse_children) {
  319. for (int i = 0; i < p_node->get_child_count(); i++) {
  320. _parse_geometry(p_accumulated_transform, p_node->get_child(i), p_vertices, p_indices, p_generate_from, p_collision_mask, p_recurse_children);
  321. }
  322. }
  323. }
  324. void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
  325. Vector<Vector3> nav_vertices;
  326. for (int i = 0; i < p_detail_mesh->nverts; i++) {
  327. const float *v = &p_detail_mesh->verts[i * 3];
  328. nav_vertices.push_back(Vector3(v[0], v[1], v[2]));
  329. }
  330. p_nav_mesh->set_vertices(nav_vertices);
  331. for (int i = 0; i < p_detail_mesh->nmeshes; i++) {
  332. const unsigned int *m = &p_detail_mesh->meshes[i * 4];
  333. const unsigned int bverts = m[0];
  334. const unsigned int btris = m[2];
  335. const unsigned int ntris = m[3];
  336. const unsigned char *tris = &p_detail_mesh->tris[btris * 4];
  337. for (unsigned int j = 0; j < ntris; j++) {
  338. Vector<int> nav_indices;
  339. nav_indices.resize(3);
  340. // Polygon order in recast is opposite than godot's
  341. nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0]));
  342. nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2]));
  343. nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1]));
  344. p_nav_mesh->add_polygon(nav_indices);
  345. }
  346. }
  347. }
  348. void NavigationMeshGenerator::_build_recast_navigation_mesh(
  349. Ref<NavigationMesh> p_nav_mesh,
  350. #ifdef TOOLS_ENABLED
  351. EditorProgress *ep,
  352. #endif
  353. rcHeightfield *hf,
  354. rcCompactHeightfield *chf,
  355. rcContourSet *cset,
  356. rcPolyMesh *poly_mesh,
  357. rcPolyMeshDetail *detail_mesh,
  358. Vector<float> &vertices,
  359. Vector<int> &indices) {
  360. rcContext ctx;
  361. #ifdef TOOLS_ENABLED
  362. if (ep) {
  363. ep->step(TTR("Setting up Configuration..."), 1);
  364. }
  365. #endif
  366. const float *verts = vertices.ptr();
  367. const int nverts = vertices.size() / 3;
  368. const int *tris = indices.ptr();
  369. const int ntris = indices.size() / 3;
  370. float bmin[3], bmax[3];
  371. rcCalcBounds(verts, nverts, bmin, bmax);
  372. rcConfig cfg;
  373. memset(&cfg, 0, sizeof(cfg));
  374. cfg.cs = p_nav_mesh->get_cell_size();
  375. cfg.ch = p_nav_mesh->get_cell_height();
  376. cfg.walkableSlopeAngle = p_nav_mesh->get_agent_max_slope();
  377. cfg.walkableHeight = (int)Math::ceil(p_nav_mesh->get_agent_height() / cfg.ch);
  378. cfg.walkableClimb = (int)Math::floor(p_nav_mesh->get_agent_max_climb() / cfg.ch);
  379. cfg.walkableRadius = (int)Math::ceil(p_nav_mesh->get_agent_radius() / cfg.cs);
  380. cfg.maxEdgeLen = (int)(p_nav_mesh->get_edge_max_length() / p_nav_mesh->get_cell_size());
  381. cfg.maxSimplificationError = p_nav_mesh->get_edge_max_error();
  382. cfg.minRegionArea = (int)(p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size());
  383. cfg.mergeRegionArea = (int)(p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size());
  384. cfg.maxVertsPerPoly = (int)p_nav_mesh->get_verts_per_poly();
  385. cfg.detailSampleDist = p_nav_mesh->get_detail_sample_distance() < 0.9f ? 0 : p_nav_mesh->get_cell_size() * p_nav_mesh->get_detail_sample_distance();
  386. cfg.detailSampleMaxError = p_nav_mesh->get_cell_height() * p_nav_mesh->get_detail_sample_max_error();
  387. cfg.bmin[0] = bmin[0];
  388. cfg.bmin[1] = bmin[1];
  389. cfg.bmin[2] = bmin[2];
  390. cfg.bmax[0] = bmax[0];
  391. cfg.bmax[1] = bmax[1];
  392. cfg.bmax[2] = bmax[2];
  393. #ifdef TOOLS_ENABLED
  394. if (ep) {
  395. ep->step(TTR("Calculating grid size..."), 2);
  396. }
  397. #endif
  398. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  399. #ifdef TOOLS_ENABLED
  400. if (ep) {
  401. ep->step(TTR("Creating heightfield..."), 3);
  402. }
  403. #endif
  404. hf = rcAllocHeightfield();
  405. ERR_FAIL_COND(!hf);
  406. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  407. #ifdef TOOLS_ENABLED
  408. if (ep) {
  409. ep->step(TTR("Marking walkable triangles..."), 4);
  410. }
  411. #endif
  412. {
  413. Vector<unsigned char> tri_areas;
  414. tri_areas.resize(ntris);
  415. ERR_FAIL_COND(tri_areas.size() == 0);
  416. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  417. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  418. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  419. }
  420. if (p_nav_mesh->get_filter_low_hanging_obstacles()) {
  421. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  422. }
  423. if (p_nav_mesh->get_filter_ledge_spans()) {
  424. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  425. }
  426. if (p_nav_mesh->get_filter_walkable_low_height_spans()) {
  427. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  428. }
  429. #ifdef TOOLS_ENABLED
  430. if (ep) {
  431. ep->step(TTR("Constructing compact heightfield..."), 5);
  432. }
  433. #endif
  434. chf = rcAllocCompactHeightfield();
  435. ERR_FAIL_COND(!chf);
  436. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  437. rcFreeHeightField(hf);
  438. hf = nullptr;
  439. #ifdef TOOLS_ENABLED
  440. if (ep) {
  441. ep->step(TTR("Eroding walkable area..."), 6);
  442. }
  443. #endif
  444. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  445. #ifdef TOOLS_ENABLED
  446. if (ep) {
  447. ep->step(TTR("Partitioning..."), 7);
  448. }
  449. #endif
  450. if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  451. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  452. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  453. } else if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  454. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  455. } else {
  456. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea));
  457. }
  458. #ifdef TOOLS_ENABLED
  459. if (ep) {
  460. ep->step(TTR("Creating contours..."), 8);
  461. }
  462. #endif
  463. cset = rcAllocContourSet();
  464. ERR_FAIL_COND(!cset);
  465. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  466. #ifdef TOOLS_ENABLED
  467. if (ep) {
  468. ep->step(TTR("Creating polymesh..."), 9);
  469. }
  470. #endif
  471. poly_mesh = rcAllocPolyMesh();
  472. ERR_FAIL_COND(!poly_mesh);
  473. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  474. detail_mesh = rcAllocPolyMeshDetail();
  475. ERR_FAIL_COND(!detail_mesh);
  476. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  477. rcFreeCompactHeightfield(chf);
  478. chf = nullptr;
  479. rcFreeContourSet(cset);
  480. cset = nullptr;
  481. #ifdef TOOLS_ENABLED
  482. if (ep) {
  483. ep->step(TTR("Converting to native navigation mesh..."), 10);
  484. }
  485. #endif
  486. _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
  487. rcFreePolyMesh(poly_mesh);
  488. poly_mesh = nullptr;
  489. rcFreePolyMeshDetail(detail_mesh);
  490. detail_mesh = nullptr;
  491. }
  492. NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() {
  493. return singleton;
  494. }
  495. NavigationMeshGenerator::NavigationMeshGenerator() {
  496. singleton = this;
  497. }
  498. NavigationMeshGenerator::~NavigationMeshGenerator() {
  499. }
  500. void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
  501. ERR_FAIL_COND_MSG(!p_nav_mesh.is_valid(), "Invalid navigation mesh.");
  502. #ifdef TOOLS_ENABLED
  503. EditorProgress *ep(nullptr);
  504. if (Engine::get_singleton()->is_editor_hint()) {
  505. ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11));
  506. }
  507. if (ep) {
  508. ep->step(TTR("Parsing Geometry..."), 0);
  509. }
  510. #endif
  511. Vector<float> vertices;
  512. Vector<int> indices;
  513. List<Node *> parse_nodes;
  514. if (p_nav_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
  515. parse_nodes.push_back(p_node);
  516. } else {
  517. p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes);
  518. }
  519. Transform3D navmesh_xform = Object::cast_to<Node3D>(p_node)->get_transform().affine_inverse();
  520. for (Node *E : parse_nodes) {
  521. NavigationMesh::ParsedGeometryType geometry_type = p_nav_mesh->get_parsed_geometry_type();
  522. uint32_t collision_mask = p_nav_mesh->get_collision_mask();
  523. bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  524. _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children);
  525. }
  526. if (vertices.size() > 0 && indices.size() > 0) {
  527. rcHeightfield *hf = nullptr;
  528. rcCompactHeightfield *chf = nullptr;
  529. rcContourSet *cset = nullptr;
  530. rcPolyMesh *poly_mesh = nullptr;
  531. rcPolyMeshDetail *detail_mesh = nullptr;
  532. _build_recast_navigation_mesh(
  533. p_nav_mesh,
  534. #ifdef TOOLS_ENABLED
  535. ep,
  536. #endif
  537. hf,
  538. chf,
  539. cset,
  540. poly_mesh,
  541. detail_mesh,
  542. vertices,
  543. indices);
  544. rcFreeHeightField(hf);
  545. hf = nullptr;
  546. rcFreeCompactHeightfield(chf);
  547. chf = nullptr;
  548. rcFreeContourSet(cset);
  549. cset = nullptr;
  550. rcFreePolyMesh(poly_mesh);
  551. poly_mesh = nullptr;
  552. rcFreePolyMeshDetail(detail_mesh);
  553. detail_mesh = nullptr;
  554. }
  555. #ifdef TOOLS_ENABLED
  556. if (ep) {
  557. ep->step(TTR("Done!"), 11);
  558. }
  559. if (ep) {
  560. memdelete(ep);
  561. }
  562. #endif
  563. }
  564. void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) {
  565. if (p_nav_mesh.is_valid()) {
  566. p_nav_mesh->clear_polygons();
  567. p_nav_mesh->set_vertices(Vector<Vector3>());
  568. }
  569. }
  570. void NavigationMeshGenerator::_bind_methods() {
  571. ClassDB::bind_method(D_METHOD("bake", "nav_mesh", "root_node"), &NavigationMeshGenerator::bake);
  572. ClassDB::bind_method(D_METHOD("clear", "nav_mesh"), &NavigationMeshGenerator::clear);
  573. }
  574. #endif