navigation_mesh_generator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "navigation_mesh_generator.h"
  31. void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) {
  32. p_verticies.push_back(p_vec3.x);
  33. p_verticies.push_back(p_vec3.y);
  34. p_verticies.push_back(p_vec3.z);
  35. }
  36. void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) {
  37. int current_vertex_count = 0;
  38. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  39. current_vertex_count = p_verticies.size() / 3;
  40. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
  41. continue;
  42. int index_count = 0;
  43. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  44. index_count = p_mesh->surface_get_array_index_len(i);
  45. } else {
  46. index_count = p_mesh->surface_get_array_len(i);
  47. }
  48. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  49. int face_count = index_count / 3;
  50. Array a = p_mesh->surface_get_arrays(i);
  51. PoolVector<Vector3> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  52. PoolVector<Vector3>::Read vr = mesh_vertices.read();
  53. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  54. PoolVector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  55. PoolVector<int>::Read ir = mesh_indices.read();
  56. for (int i = 0; i < mesh_vertices.size(); i++) {
  57. _add_vertex(p_xform.xform(vr[i]), p_verticies);
  58. }
  59. for (int i = 0; i < face_count; i++) {
  60. // CCW
  61. p_indices.push_back(current_vertex_count + (ir[i * 3 + 0]));
  62. p_indices.push_back(current_vertex_count + (ir[i * 3 + 2]));
  63. p_indices.push_back(current_vertex_count + (ir[i * 3 + 1]));
  64. }
  65. } else {
  66. face_count = mesh_vertices.size() / 3;
  67. for (int i = 0; i < face_count; i++) {
  68. _add_vertex(p_xform.xform(vr[i * 3 + 0]), p_verticies);
  69. _add_vertex(p_xform.xform(vr[i * 3 + 2]), p_verticies);
  70. _add_vertex(p_xform.xform(vr[i * 3 + 1]), p_verticies);
  71. p_indices.push_back(current_vertex_count + (i * 3 + 0));
  72. p_indices.push_back(current_vertex_count + (i * 3 + 1));
  73. p_indices.push_back(current_vertex_count + (i * 3 + 2));
  74. }
  75. }
  76. }
  77. }
  78. void NavigationMeshGenerator::_parse_geometry(const Transform &p_base_inverse, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices) {
  79. if (Object::cast_to<MeshInstance>(p_node)) {
  80. MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(p_node);
  81. Ref<Mesh> mesh = mesh_instance->get_mesh();
  82. if (mesh.is_valid()) {
  83. _add_mesh(mesh, p_base_inverse * mesh_instance->get_global_transform(), p_verticies, p_indices);
  84. }
  85. }
  86. for (int i = 0; i < p_node->get_child_count(); i++) {
  87. _parse_geometry(p_base_inverse, p_node->get_child(i), p_verticies, p_indices);
  88. }
  89. }
  90. void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
  91. PoolVector<Vector3> nav_vertices;
  92. for (int i = 0; i < p_detail_mesh->nverts; i++) {
  93. const float *v = &p_detail_mesh->verts[i * 3];
  94. nav_vertices.append(Vector3(v[0], v[1], v[2]));
  95. }
  96. p_nav_mesh->set_vertices(nav_vertices);
  97. for (int i = 0; i < p_detail_mesh->nmeshes; i++) {
  98. const unsigned int *m = &p_detail_mesh->meshes[i * 4];
  99. const unsigned int bverts = m[0];
  100. const unsigned int btris = m[2];
  101. const unsigned int ntris = m[3];
  102. const unsigned char *tris = &p_detail_mesh->tris[btris * 4];
  103. for (unsigned int j = 0; j < ntris; j++) {
  104. Vector<int> nav_indices;
  105. nav_indices.resize(3);
  106. nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0]));
  107. nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 1]));
  108. nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 2]));
  109. p_nav_mesh->add_polygon(nav_indices);
  110. }
  111. }
  112. }
  113. void NavigationMeshGenerator::_build_recast_navigation_mesh(Ref<NavigationMesh> p_nav_mesh, EditorProgress *ep,
  114. rcHeightfield *hf, rcCompactHeightfield *chf, rcContourSet *cset, rcPolyMesh *poly_mesh, rcPolyMeshDetail *detail_mesh,
  115. Vector<float> &vertices, Vector<int> &indices) {
  116. rcContext ctx;
  117. ep->step(TTR("Setting up Configuration..."), 1);
  118. const float *verts = vertices.ptr();
  119. const int nverts = vertices.size() / 3;
  120. const int *tris = indices.ptr();
  121. const int ntris = indices.size() / 3;
  122. float bmin[3], bmax[3];
  123. rcCalcBounds(verts, nverts, bmin, bmax);
  124. rcConfig cfg;
  125. memset(&cfg, 0, sizeof(cfg));
  126. cfg.cs = p_nav_mesh->get_cell_size();
  127. cfg.ch = p_nav_mesh->get_cell_height();
  128. cfg.walkableSlopeAngle = p_nav_mesh->get_agent_max_slope();
  129. cfg.walkableHeight = (int)Math::ceil(p_nav_mesh->get_agent_height() / cfg.ch);
  130. cfg.walkableClimb = (int)Math::floor(p_nav_mesh->get_agent_max_climb() / cfg.ch);
  131. cfg.walkableRadius = (int)Math::ceil(p_nav_mesh->get_agent_radius() / cfg.cs);
  132. cfg.maxEdgeLen = (int)(p_nav_mesh->get_edge_max_length() / p_nav_mesh->get_cell_size());
  133. cfg.maxSimplificationError = p_nav_mesh->get_edge_max_error();
  134. cfg.minRegionArea = (int)(p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size());
  135. cfg.mergeRegionArea = (int)(p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size());
  136. cfg.maxVertsPerPoly = (int)p_nav_mesh->get_verts_per_poly();
  137. 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();
  138. cfg.detailSampleMaxError = p_nav_mesh->get_cell_height() * p_nav_mesh->get_detail_sample_max_error();
  139. cfg.bmin[0] = bmin[0];
  140. cfg.bmin[1] = bmin[1];
  141. cfg.bmin[2] = bmin[2];
  142. cfg.bmax[0] = bmax[0];
  143. cfg.bmax[1] = bmax[1];
  144. cfg.bmax[2] = bmax[2];
  145. ep->step(TTR("Calculating grid size..."), 2);
  146. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  147. ep->step(TTR("Creating heightfield..."), 3);
  148. hf = rcAllocHeightfield();
  149. ERR_FAIL_COND(!hf);
  150. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  151. ep->step(TTR("Marking walkable triangles..."), 4);
  152. {
  153. Vector<unsigned char> tri_areas;
  154. tri_areas.resize(ntris);
  155. ERR_FAIL_COND(tri_areas.size() == 0);
  156. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  157. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  158. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  159. }
  160. if (p_nav_mesh->get_filter_low_hanging_obstacles())
  161. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  162. if (p_nav_mesh->get_filter_ledge_spans())
  163. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  164. if (p_nav_mesh->get_filter_walkable_low_height_spans())
  165. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  166. ep->step(TTR("Constructing compact heightfield..."), 5);
  167. chf = rcAllocCompactHeightfield();
  168. ERR_FAIL_COND(!chf);
  169. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  170. rcFreeHeightField(hf);
  171. hf = 0;
  172. ep->step(TTR("Eroding walkable area..."), 6);
  173. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  174. ep->step(TTR("Partitioning..."), 7);
  175. if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  176. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  177. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  178. } else if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  179. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  180. } else {
  181. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea));
  182. }
  183. ep->step(TTR("Creating contours..."), 8);
  184. cset = rcAllocContourSet();
  185. ERR_FAIL_COND(!cset);
  186. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  187. ep->step(TTR("Creating polymesh..."), 9);
  188. poly_mesh = rcAllocPolyMesh();
  189. ERR_FAIL_COND(!poly_mesh);
  190. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  191. detail_mesh = rcAllocPolyMeshDetail();
  192. ERR_FAIL_COND(!detail_mesh);
  193. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  194. rcFreeCompactHeightfield(chf);
  195. chf = 0;
  196. rcFreeContourSet(cset);
  197. cset = 0;
  198. ep->step(TTR("Converting to native navigation mesh..."), 10);
  199. _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
  200. rcFreePolyMesh(poly_mesh);
  201. poly_mesh = 0;
  202. rcFreePolyMeshDetail(detail_mesh);
  203. detail_mesh = 0;
  204. }
  205. void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
  206. ERR_FAIL_COND(!p_nav_mesh.is_valid());
  207. EditorProgress ep("bake", TTR("Navigation Mesh Generator Setup:"), 11);
  208. ep.step(TTR("Parsing Geometry..."), 0);
  209. Vector<float> vertices;
  210. Vector<int> indices;
  211. _parse_geometry(Object::cast_to<Spatial>(p_node)->get_global_transform().affine_inverse(), p_node, vertices, indices);
  212. if (vertices.size() > 0 && indices.size() > 0) {
  213. rcHeightfield *hf = NULL;
  214. rcCompactHeightfield *chf = NULL;
  215. rcContourSet *cset = NULL;
  216. rcPolyMesh *poly_mesh = NULL;
  217. rcPolyMeshDetail *detail_mesh = NULL;
  218. _build_recast_navigation_mesh(p_nav_mesh, &ep, hf, chf, cset, poly_mesh, detail_mesh, vertices, indices);
  219. rcFreeHeightField(hf);
  220. hf = 0;
  221. rcFreeCompactHeightfield(chf);
  222. chf = 0;
  223. rcFreeContourSet(cset);
  224. cset = 0;
  225. rcFreePolyMesh(poly_mesh);
  226. poly_mesh = 0;
  227. rcFreePolyMeshDetail(detail_mesh);
  228. detail_mesh = 0;
  229. }
  230. ep.step(TTR("Done!"), 11);
  231. }
  232. void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) {
  233. if (p_nav_mesh.is_valid()) {
  234. p_nav_mesh->clear_polygons();
  235. p_nav_mesh->set_vertices(PoolVector<Vector3>());
  236. }
  237. }