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