navigation_mesh_generator.cpp 23 KB

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