1 /*************************************************************************/
2 /*  grid_map.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 "grid_map.h"
32 
33 #include "core/io/marshalls.h"
34 #include "core/message_queue.h"
35 #include "scene/3d/light.h"
36 #include "scene/resources/mesh_library.h"
37 #include "scene/resources/surface_tool.h"
38 #include "scene/scene_string_names.h"
39 #include "servers/visual_server.h"
40 
_set(const StringName & p_name,const Variant & p_value)41 bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
42 
43 	String name = p_name;
44 
45 	if (name == "data") {
46 
47 		Dictionary d = p_value;
48 
49 		if (d.has("cells")) {
50 
51 			PoolVector<int> cells = d["cells"];
52 			int amount = cells.size();
53 			PoolVector<int>::Read r = cells.read();
54 			ERR_FAIL_COND_V(amount % 3, false); // not even
55 			cell_map.clear();
56 			for (int i = 0; i < amount / 3; i++) {
57 
58 				IndexKey ik;
59 				ik.key = decode_uint64((const uint8_t *)&r[i * 3]);
60 				Cell cell;
61 				cell.cell = decode_uint32((const uint8_t *)&r[i * 3 + 2]);
62 				cell_map[ik] = cell;
63 			}
64 		}
65 
66 		_recreate_octant_data();
67 
68 	} else if (name == "baked_meshes") {
69 
70 		clear_baked_meshes();
71 
72 		Array meshes = p_value;
73 
74 		for (int i = 0; i < meshes.size(); i++) {
75 			BakedMesh bm;
76 			bm.mesh = meshes[i];
77 			ERR_CONTINUE(!bm.mesh.is_valid());
78 			bm.instance = VS::get_singleton()->instance_create();
79 			VS::get_singleton()->get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid());
80 			VS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id());
81 			if (is_inside_tree()) {
82 				VS::get_singleton()->instance_set_scenario(bm.instance, get_world()->get_scenario());
83 				VS::get_singleton()->instance_set_transform(bm.instance, get_global_transform());
84 			}
85 			baked_meshes.push_back(bm);
86 		}
87 
88 		_recreate_octant_data();
89 
90 	} else {
91 		return false;
92 	}
93 
94 	return true;
95 }
96 
_get(const StringName & p_name,Variant & r_ret) const97 bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
98 
99 	String name = p_name;
100 
101 	if (name == "data") {
102 
103 		Dictionary d;
104 
105 		PoolVector<int> cells;
106 		cells.resize(cell_map.size() * 3);
107 		{
108 			PoolVector<int>::Write w = cells.write();
109 			int i = 0;
110 			for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next(), i++) {
111 
112 				encode_uint64(E->key().key, (uint8_t *)&w[i * 3]);
113 				encode_uint32(E->get().cell, (uint8_t *)&w[i * 3 + 2]);
114 			}
115 		}
116 
117 		d["cells"] = cells;
118 
119 		r_ret = d;
120 	} else if (name == "baked_meshes") {
121 
122 		Array ret;
123 		ret.resize(baked_meshes.size());
124 		for (int i = 0; i < baked_meshes.size(); i++) {
125 			ret[i] = baked_meshes[i].mesh;
126 		}
127 		r_ret = ret;
128 
129 	} else
130 		return false;
131 
132 	return true;
133 }
134 
_get_property_list(List<PropertyInfo> * p_list) const135 void GridMap::_get_property_list(List<PropertyInfo> *p_list) const {
136 
137 	if (baked_meshes.size()) {
138 		p_list->push_back(PropertyInfo(Variant::ARRAY, "baked_meshes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
139 	}
140 
141 	p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
142 }
143 
set_collision_layer(uint32_t p_layer)144 void GridMap::set_collision_layer(uint32_t p_layer) {
145 
146 	collision_layer = p_layer;
147 	_reset_physic_bodies_collision_filters();
148 }
149 
get_collision_layer() const150 uint32_t GridMap::get_collision_layer() const {
151 
152 	return collision_layer;
153 }
154 
set_collision_mask(uint32_t p_mask)155 void GridMap::set_collision_mask(uint32_t p_mask) {
156 
157 	collision_mask = p_mask;
158 	_reset_physic_bodies_collision_filters();
159 }
160 
get_collision_mask() const161 uint32_t GridMap::get_collision_mask() const {
162 
163 	return collision_mask;
164 }
165 
set_collision_mask_bit(int p_bit,bool p_value)166 void GridMap::set_collision_mask_bit(int p_bit, bool p_value) {
167 
168 	uint32_t mask = get_collision_mask();
169 	if (p_value)
170 		mask |= 1 << p_bit;
171 	else
172 		mask &= ~(1 << p_bit);
173 	set_collision_mask(mask);
174 }
175 
get_collision_mask_bit(int p_bit) const176 bool GridMap::get_collision_mask_bit(int p_bit) const {
177 
178 	return get_collision_mask() & (1 << p_bit);
179 }
180 
set_collision_layer_bit(int p_bit,bool p_value)181 void GridMap::set_collision_layer_bit(int p_bit, bool p_value) {
182 
183 	uint32_t mask = get_collision_layer();
184 	if (p_value)
185 		mask |= 1 << p_bit;
186 	else
187 		mask &= ~(1 << p_bit);
188 	set_collision_layer(mask);
189 }
190 
get_collision_layer_bit(int p_bit) const191 bool GridMap::get_collision_layer_bit(int p_bit) const {
192 
193 	return get_collision_layer() & (1 << p_bit);
194 }
195 
set_mesh_library(const Ref<MeshLibrary> & p_mesh_library)196 void GridMap::set_mesh_library(const Ref<MeshLibrary> &p_mesh_library) {
197 
198 	if (!mesh_library.is_null())
199 		mesh_library->unregister_owner(this);
200 	mesh_library = p_mesh_library;
201 	if (!mesh_library.is_null())
202 		mesh_library->register_owner(this);
203 
204 	_recreate_octant_data();
205 	_change_notify("mesh_library");
206 }
207 
get_mesh_library() const208 Ref<MeshLibrary> GridMap::get_mesh_library() const {
209 
210 	return mesh_library;
211 }
212 
set_cell_size(const Vector3 & p_size)213 void GridMap::set_cell_size(const Vector3 &p_size) {
214 	ERR_FAIL_COND(p_size.x < 0.001 || p_size.y < 0.001 || p_size.z < 0.001);
215 	cell_size = p_size;
216 	_recreate_octant_data();
217 	emit_signal("cell_size_changed", cell_size);
218 }
get_cell_size() const219 Vector3 GridMap::get_cell_size() const {
220 
221 	return cell_size;
222 }
223 
set_octant_size(int p_size)224 void GridMap::set_octant_size(int p_size) {
225 
226 	ERR_FAIL_COND(p_size == 0);
227 	octant_size = p_size;
228 	_recreate_octant_data();
229 }
get_octant_size() const230 int GridMap::get_octant_size() const {
231 
232 	return octant_size;
233 }
234 
set_center_x(bool p_enable)235 void GridMap::set_center_x(bool p_enable) {
236 
237 	center_x = p_enable;
238 	_recreate_octant_data();
239 }
240 
get_center_x() const241 bool GridMap::get_center_x() const {
242 	return center_x;
243 }
244 
set_center_y(bool p_enable)245 void GridMap::set_center_y(bool p_enable) {
246 
247 	center_y = p_enable;
248 	_recreate_octant_data();
249 }
250 
get_center_y() const251 bool GridMap::get_center_y() const {
252 	return center_y;
253 }
254 
set_center_z(bool p_enable)255 void GridMap::set_center_z(bool p_enable) {
256 
257 	center_z = p_enable;
258 	_recreate_octant_data();
259 }
260 
get_center_z() const261 bool GridMap::get_center_z() const {
262 	return center_z;
263 }
264 
set_cell_item(int p_x,int p_y,int p_z,int p_item,int p_rot)265 void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) {
266 
267 	if (baked_meshes.size() && !recreating_octants) {
268 		//if you set a cell item, baked meshes go good bye
269 		clear_baked_meshes();
270 		_recreate_octant_data();
271 	}
272 
273 	ERR_FAIL_INDEX(ABS(p_x), 1 << 20);
274 	ERR_FAIL_INDEX(ABS(p_y), 1 << 20);
275 	ERR_FAIL_INDEX(ABS(p_z), 1 << 20);
276 
277 	IndexKey key;
278 	key.x = p_x;
279 	key.y = p_y;
280 	key.z = p_z;
281 
282 	OctantKey ok;
283 	ok.x = p_x / octant_size;
284 	ok.y = p_y / octant_size;
285 	ok.z = p_z / octant_size;
286 
287 	if (p_item < 0) {
288 		//erase
289 		if (cell_map.has(key)) {
290 			OctantKey octantkey = ok;
291 
292 			ERR_FAIL_COND(!octant_map.has(octantkey));
293 			Octant &g = *octant_map[octantkey];
294 			g.cells.erase(key);
295 			g.dirty = true;
296 			cell_map.erase(key);
297 			_queue_octants_dirty();
298 		}
299 		return;
300 	}
301 
302 	OctantKey octantkey = ok;
303 
304 	if (!octant_map.has(octantkey)) {
305 		//create octant because it does not exist
306 		Octant *g = memnew(Octant);
307 		g->dirty = true;
308 		g->static_body = PhysicsServer::get_singleton()->body_create(PhysicsServer::BODY_MODE_STATIC);
309 		PhysicsServer::get_singleton()->body_attach_object_instance_id(g->static_body, get_instance_id());
310 		PhysicsServer::get_singleton()->body_set_collision_layer(g->static_body, collision_layer);
311 		PhysicsServer::get_singleton()->body_set_collision_mask(g->static_body, collision_mask);
312 		SceneTree *st = SceneTree::get_singleton();
313 
314 		if (st && st->is_debugging_collisions_hint()) {
315 
316 			g->collision_debug = VisualServer::get_singleton()->mesh_create();
317 			g->collision_debug_instance = VisualServer::get_singleton()->instance_create();
318 			VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance, g->collision_debug);
319 		}
320 
321 		octant_map[octantkey] = g;
322 
323 		if (is_inside_world()) {
324 			_octant_enter_world(octantkey);
325 			_octant_transform(octantkey);
326 		}
327 	}
328 
329 	Octant &g = *octant_map[octantkey];
330 	g.cells.insert(key);
331 	g.dirty = true;
332 	_queue_octants_dirty();
333 
334 	Cell c;
335 	c.item = p_item;
336 	c.rot = p_rot;
337 
338 	cell_map[key] = c;
339 }
340 
get_cell_item(int p_x,int p_y,int p_z) const341 int GridMap::get_cell_item(int p_x, int p_y, int p_z) const {
342 
343 	ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, INVALID_CELL_ITEM);
344 	ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, INVALID_CELL_ITEM);
345 	ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, INVALID_CELL_ITEM);
346 
347 	IndexKey key;
348 	key.x = p_x;
349 	key.y = p_y;
350 	key.z = p_z;
351 
352 	if (!cell_map.has(key))
353 		return INVALID_CELL_ITEM;
354 	return cell_map[key].item;
355 }
356 
get_cell_item_orientation(int p_x,int p_y,int p_z) const357 int GridMap::get_cell_item_orientation(int p_x, int p_y, int p_z) const {
358 
359 	ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, -1);
360 	ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, -1);
361 	ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, -1);
362 
363 	IndexKey key;
364 	key.x = p_x;
365 	key.y = p_y;
366 	key.z = p_z;
367 
368 	if (!cell_map.has(key))
369 		return -1;
370 	return cell_map[key].rot;
371 }
372 
world_to_map(const Vector3 & p_world_pos) const373 Vector3 GridMap::world_to_map(const Vector3 &p_world_pos) const {
374 	Vector3 map_pos = p_world_pos / cell_size;
375 	map_pos.x = floor(map_pos.x);
376 	map_pos.y = floor(map_pos.y);
377 	map_pos.z = floor(map_pos.z);
378 	return map_pos;
379 }
380 
map_to_world(int p_x,int p_y,int p_z) const381 Vector3 GridMap::map_to_world(int p_x, int p_y, int p_z) const {
382 	Vector3 offset = _get_offset();
383 	Vector3 world_pos(
384 			p_x * cell_size.x + offset.x,
385 			p_y * cell_size.y + offset.y,
386 			p_z * cell_size.z + offset.z);
387 	return world_pos;
388 }
389 
_octant_transform(const OctantKey & p_key)390 void GridMap::_octant_transform(const OctantKey &p_key) {
391 
392 	ERR_FAIL_COND(!octant_map.has(p_key));
393 	Octant &g = *octant_map[p_key];
394 	PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
395 
396 	if (g.collision_debug_instance.is_valid()) {
397 		VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
398 	}
399 
400 	for (int i = 0; i < g.multimesh_instances.size(); i++) {
401 		VS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform());
402 	}
403 }
404 
_octant_update(const OctantKey & p_key)405 bool GridMap::_octant_update(const OctantKey &p_key) {
406 	ERR_FAIL_COND_V(!octant_map.has(p_key), false);
407 	Octant &g = *octant_map[p_key];
408 	if (!g.dirty)
409 		return false;
410 
411 	//erase body shapes
412 	PhysicsServer::get_singleton()->body_clear_shapes(g.static_body);
413 
414 	//erase body shapes debug
415 	if (g.collision_debug.is_valid()) {
416 
417 		VS::get_singleton()->mesh_clear(g.collision_debug);
418 	}
419 
420 	//erase navigation
421 	if (navigation) {
422 		for (Map<IndexKey, Octant::NavMesh>::Element *E = g.navmesh_ids.front(); E; E = E->next()) {
423 			navigation->navmesh_remove(E->get().id);
424 		}
425 		g.navmesh_ids.clear();
426 	}
427 
428 	//erase multimeshes
429 
430 	for (int i = 0; i < g.multimesh_instances.size(); i++) {
431 
432 		VS::get_singleton()->free(g.multimesh_instances[i].instance);
433 		VS::get_singleton()->free(g.multimesh_instances[i].multimesh);
434 	}
435 	g.multimesh_instances.clear();
436 
437 	if (g.cells.size() == 0) {
438 		//octant no longer needed
439 		_octant_clean_up(p_key);
440 		return true;
441 	}
442 
443 	PoolVector<Vector3> col_debug;
444 
445 	/*
446 	 * foreach item in this octant,
447 	 * set item's multimesh's instance count to number of cells which have this item
448 	 * and set said multimesh bounding box to one containing all cells which have this item
449 	 */
450 
451 	Map<int, List<Pair<Transform, IndexKey> > > multimesh_items;
452 
453 	for (Set<IndexKey>::Element *E = g.cells.front(); E; E = E->next()) {
454 
455 		ERR_CONTINUE(!cell_map.has(E->get()));
456 		const Cell &c = cell_map[E->get()];
457 
458 		if (!mesh_library.is_valid() || !mesh_library->has_item(c.item))
459 			continue;
460 
461 		Vector3 cellpos = Vector3(E->get().x, E->get().y, E->get().z);
462 		Vector3 ofs = _get_offset();
463 
464 		Transform xform;
465 
466 		xform.basis.set_orthogonal_index(c.rot);
467 		xform.set_origin(cellpos * cell_size + ofs);
468 		xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
469 		if (baked_meshes.size() == 0) {
470 			if (mesh_library->get_item_mesh(c.item).is_valid()) {
471 				if (!multimesh_items.has(c.item)) {
472 					multimesh_items[c.item] = List<Pair<Transform, IndexKey> >();
473 				}
474 
475 				Pair<Transform, IndexKey> p;
476 				p.first = xform;
477 				p.second = E->get();
478 				multimesh_items[c.item].push_back(p);
479 			}
480 		}
481 
482 		Vector<MeshLibrary::ShapeData> shapes = mesh_library->get_item_shapes(c.item);
483 		// add the item's shape at given xform to octant's static_body
484 		for (int i = 0; i < shapes.size(); i++) {
485 			// add the item's shape
486 			if (!shapes[i].shape.is_valid())
487 				continue;
488 			PhysicsServer::get_singleton()->body_add_shape(g.static_body, shapes[i].shape->get_rid(), xform * shapes[i].local_transform);
489 			if (g.collision_debug.is_valid()) {
490 				shapes.write[i].shape->add_vertices_to_array(col_debug, xform * shapes[i].local_transform);
491 			}
492 		}
493 
494 		// add the item's navmesh at given xform to GridMap's Navigation ancestor
495 		Ref<NavigationMesh> navmesh = mesh_library->get_item_navmesh(c.item);
496 		if (navmesh.is_valid()) {
497 			Octant::NavMesh nm;
498 			nm.xform = xform * mesh_library->get_item_navmesh_transform(c.item);
499 
500 			if (navigation) {
501 				nm.id = navigation->navmesh_add(navmesh, xform, this);
502 			} else {
503 				nm.id = -1;
504 			}
505 			g.navmesh_ids[E->get()] = nm;
506 		}
507 	}
508 
509 	//update multimeshes, only if not baked
510 	if (baked_meshes.size() == 0) {
511 
512 		for (Map<int, List<Pair<Transform, IndexKey> > >::Element *E = multimesh_items.front(); E; E = E->next()) {
513 			Octant::MultimeshInstance mmi;
514 
515 			RID mm = VS::get_singleton()->multimesh_create();
516 			VS::get_singleton()->multimesh_allocate(mm, E->get().size(), VS::MULTIMESH_TRANSFORM_3D, VS::MULTIMESH_COLOR_NONE);
517 			VS::get_singleton()->multimesh_set_mesh(mm, mesh_library->get_item_mesh(E->key())->get_rid());
518 
519 			int idx = 0;
520 			for (List<Pair<Transform, IndexKey> >::Element *F = E->get().front(); F; F = F->next()) {
521 				VS::get_singleton()->multimesh_instance_set_transform(mm, idx, F->get().first);
522 #ifdef TOOLS_ENABLED
523 
524 				Octant::MultimeshInstance::Item it;
525 				it.index = idx;
526 				it.transform = F->get().first;
527 				it.key = F->get().second;
528 				mmi.items.push_back(it);
529 #endif
530 
531 				idx++;
532 			}
533 
534 			RID instance = VS::get_singleton()->instance_create();
535 			VS::get_singleton()->instance_set_base(instance, mm);
536 
537 			if (is_inside_tree()) {
538 				VS::get_singleton()->instance_set_scenario(instance, get_world()->get_scenario());
539 				VS::get_singleton()->instance_set_transform(instance, get_global_transform());
540 			}
541 
542 			mmi.multimesh = mm;
543 			mmi.instance = instance;
544 
545 			g.multimesh_instances.push_back(mmi);
546 		}
547 	}
548 
549 	if (col_debug.size()) {
550 
551 		Array arr;
552 		arr.resize(VS::ARRAY_MAX);
553 		arr[VS::ARRAY_VERTEX] = col_debug;
554 
555 		VS::get_singleton()->mesh_add_surface_from_arrays(g.collision_debug, VS::PRIMITIVE_LINES, arr);
556 		SceneTree *st = SceneTree::get_singleton();
557 		if (st) {
558 			VS::get_singleton()->mesh_surface_set_material(g.collision_debug, 0, st->get_debug_collision_material()->get_rid());
559 		}
560 	}
561 
562 	g.dirty = false;
563 
564 	return false;
565 }
566 
_reset_physic_bodies_collision_filters()567 void GridMap::_reset_physic_bodies_collision_filters() {
568 	for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
569 		PhysicsServer::get_singleton()->body_set_collision_layer(E->get()->static_body, collision_layer);
570 		PhysicsServer::get_singleton()->body_set_collision_mask(E->get()->static_body, collision_mask);
571 	}
572 }
573 
_octant_enter_world(const OctantKey & p_key)574 void GridMap::_octant_enter_world(const OctantKey &p_key) {
575 
576 	ERR_FAIL_COND(!octant_map.has(p_key));
577 	Octant &g = *octant_map[p_key];
578 	PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
579 	PhysicsServer::get_singleton()->body_set_space(g.static_body, get_world()->get_space());
580 
581 	if (g.collision_debug_instance.is_valid()) {
582 		VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world()->get_scenario());
583 		VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
584 	}
585 
586 	for (int i = 0; i < g.multimesh_instances.size(); i++) {
587 		VS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, get_world()->get_scenario());
588 		VS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform());
589 	}
590 
591 	if (navigation && mesh_library.is_valid()) {
592 		for (Map<IndexKey, Octant::NavMesh>::Element *F = g.navmesh_ids.front(); F; F = F->next()) {
593 
594 			if (cell_map.has(F->key()) && F->get().id < 0) {
595 				Ref<NavigationMesh> nm = mesh_library->get_item_navmesh(cell_map[F->key()].item);
596 				if (nm.is_valid()) {
597 					F->get().id = navigation->navmesh_add(nm, F->get().xform, this);
598 				}
599 			}
600 		}
601 	}
602 }
603 
_octant_exit_world(const OctantKey & p_key)604 void GridMap::_octant_exit_world(const OctantKey &p_key) {
605 
606 	ERR_FAIL_COND(!octant_map.has(p_key));
607 	Octant &g = *octant_map[p_key];
608 	PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
609 	PhysicsServer::get_singleton()->body_set_space(g.static_body, RID());
610 
611 	if (g.collision_debug_instance.is_valid()) {
612 
613 		VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, RID());
614 	}
615 
616 	for (int i = 0; i < g.multimesh_instances.size(); i++) {
617 		VS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, RID());
618 	}
619 
620 	if (navigation) {
621 		for (Map<IndexKey, Octant::NavMesh>::Element *F = g.navmesh_ids.front(); F; F = F->next()) {
622 
623 			if (F->get().id >= 0) {
624 				navigation->navmesh_remove(F->get().id);
625 				F->get().id = -1;
626 			}
627 		}
628 	}
629 }
630 
_octant_clean_up(const OctantKey & p_key)631 void GridMap::_octant_clean_up(const OctantKey &p_key) {
632 
633 	ERR_FAIL_COND(!octant_map.has(p_key));
634 	Octant &g = *octant_map[p_key];
635 
636 	if (g.collision_debug.is_valid())
637 		VS::get_singleton()->free(g.collision_debug);
638 	if (g.collision_debug_instance.is_valid())
639 		VS::get_singleton()->free(g.collision_debug_instance);
640 
641 	PhysicsServer::get_singleton()->free(g.static_body);
642 
643 	//erase navigation
644 	if (navigation) {
645 		for (Map<IndexKey, Octant::NavMesh>::Element *E = g.navmesh_ids.front(); E; E = E->next()) {
646 			navigation->navmesh_remove(E->get().id);
647 		}
648 		g.navmesh_ids.clear();
649 	}
650 
651 	//erase multimeshes
652 
653 	for (int i = 0; i < g.multimesh_instances.size(); i++) {
654 
655 		VS::get_singleton()->free(g.multimesh_instances[i].instance);
656 		VS::get_singleton()->free(g.multimesh_instances[i].multimesh);
657 	}
658 	g.multimesh_instances.clear();
659 }
660 
_notification(int p_what)661 void GridMap::_notification(int p_what) {
662 
663 	switch (p_what) {
664 
665 		case NOTIFICATION_ENTER_WORLD: {
666 
667 			Spatial *c = this;
668 			while (c) {
669 				navigation = Object::cast_to<Navigation>(c);
670 				if (navigation) {
671 					break;
672 				}
673 
674 				c = Object::cast_to<Spatial>(c->get_parent());
675 			}
676 
677 			last_transform = get_global_transform();
678 
679 			for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
680 				_octant_enter_world(E->key());
681 			}
682 
683 			for (int i = 0; i < baked_meshes.size(); i++) {
684 				VS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, get_world()->get_scenario());
685 				VS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform());
686 			}
687 
688 		} break;
689 		case NOTIFICATION_TRANSFORM_CHANGED: {
690 
691 			Transform new_xform = get_global_transform();
692 			if (new_xform == last_transform)
693 				break;
694 			//update run
695 			for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
696 				_octant_transform(E->key());
697 			}
698 
699 			last_transform = new_xform;
700 
701 			for (int i = 0; i < baked_meshes.size(); i++) {
702 				VS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform());
703 			}
704 
705 		} break;
706 		case NOTIFICATION_EXIT_WORLD: {
707 
708 			for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
709 				_octant_exit_world(E->key());
710 			}
711 
712 			navigation = NULL;
713 
714 			//_queue_octants_dirty(MAP_DIRTY_INSTANCES|MAP_DIRTY_TRANSFORMS);
715 			//_update_octants_callback();
716 			//_update_area_instances();
717 			for (int i = 0; i < baked_meshes.size(); i++) {
718 				VS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, RID());
719 			}
720 
721 		} break;
722 		case NOTIFICATION_VISIBILITY_CHANGED: {
723 			_update_visibility();
724 		} break;
725 	}
726 }
727 
_update_visibility()728 void GridMap::_update_visibility() {
729 	if (!is_inside_tree())
730 		return;
731 
732 	_change_notify("visible");
733 
734 	for (Map<OctantKey, Octant *>::Element *e = octant_map.front(); e; e = e->next()) {
735 		Octant *octant = e->value();
736 		for (int i = 0; i < octant->multimesh_instances.size(); i++) {
737 			const Octant::MultimeshInstance &mi = octant->multimesh_instances[i];
738 			VS::get_singleton()->instance_set_visible(mi.instance, is_visible());
739 		}
740 	}
741 }
742 
_queue_octants_dirty()743 void GridMap::_queue_octants_dirty() {
744 
745 	if (awaiting_update)
746 		return;
747 
748 	MessageQueue::get_singleton()->push_call(this, "_update_octants_callback");
749 	awaiting_update = true;
750 }
751 
_recreate_octant_data()752 void GridMap::_recreate_octant_data() {
753 
754 	recreating_octants = true;
755 	Map<IndexKey, Cell> cell_copy = cell_map;
756 	_clear_internal();
757 	for (Map<IndexKey, Cell>::Element *E = cell_copy.front(); E; E = E->next()) {
758 
759 		set_cell_item(E->key().x, E->key().y, E->key().z, E->get().item, E->get().rot);
760 	}
761 	recreating_octants = false;
762 }
763 
_clear_internal()764 void GridMap::_clear_internal() {
765 
766 	for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
767 		if (is_inside_world())
768 			_octant_exit_world(E->key());
769 
770 		_octant_clean_up(E->key());
771 		memdelete(E->get());
772 	}
773 
774 	octant_map.clear();
775 	cell_map.clear();
776 }
777 
clear()778 void GridMap::clear() {
779 
780 	_clear_internal();
781 	clear_baked_meshes();
782 }
783 
resource_changed(const RES & p_res)784 void GridMap::resource_changed(const RES &p_res) {
785 
786 	_recreate_octant_data();
787 }
788 
_update_octants_callback()789 void GridMap::_update_octants_callback() {
790 
791 	if (!awaiting_update)
792 		return;
793 
794 	List<OctantKey> to_delete;
795 	for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
796 
797 		if (_octant_update(E->key())) {
798 			to_delete.push_back(E->key());
799 		}
800 	}
801 
802 	while (to_delete.front()) {
803 		octant_map.erase(to_delete.front()->get());
804 		to_delete.pop_back();
805 	}
806 
807 	_update_visibility();
808 	awaiting_update = false;
809 }
810 
_bind_methods()811 void GridMap::_bind_methods() {
812 
813 	ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &GridMap::set_collision_layer);
814 	ClassDB::bind_method(D_METHOD("get_collision_layer"), &GridMap::get_collision_layer);
815 
816 	ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &GridMap::set_collision_mask);
817 	ClassDB::bind_method(D_METHOD("get_collision_mask"), &GridMap::get_collision_mask);
818 
819 	ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &GridMap::set_collision_mask_bit);
820 	ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &GridMap::get_collision_mask_bit);
821 
822 	ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &GridMap::set_collision_layer_bit);
823 	ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &GridMap::get_collision_layer_bit);
824 
825 	ClassDB::bind_method(D_METHOD("set_mesh_library", "mesh_library"), &GridMap::set_mesh_library);
826 	ClassDB::bind_method(D_METHOD("get_mesh_library"), &GridMap::get_mesh_library);
827 
828 	ClassDB::bind_method(D_METHOD("set_cell_size", "size"), &GridMap::set_cell_size);
829 	ClassDB::bind_method(D_METHOD("get_cell_size"), &GridMap::get_cell_size);
830 
831 	ClassDB::bind_method(D_METHOD("set_cell_scale", "scale"), &GridMap::set_cell_scale);
832 	ClassDB::bind_method(D_METHOD("get_cell_scale"), &GridMap::get_cell_scale);
833 
834 	ClassDB::bind_method(D_METHOD("set_octant_size", "size"), &GridMap::set_octant_size);
835 	ClassDB::bind_method(D_METHOD("get_octant_size"), &GridMap::get_octant_size);
836 
837 	ClassDB::bind_method(D_METHOD("set_cell_item", "x", "y", "z", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0));
838 	ClassDB::bind_method(D_METHOD("get_cell_item", "x", "y", "z"), &GridMap::get_cell_item);
839 	ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "x", "y", "z"), &GridMap::get_cell_item_orientation);
840 
841 	ClassDB::bind_method(D_METHOD("world_to_map", "pos"), &GridMap::world_to_map);
842 	ClassDB::bind_method(D_METHOD("map_to_world", "x", "y", "z"), &GridMap::map_to_world);
843 
844 	ClassDB::bind_method(D_METHOD("_update_octants_callback"), &GridMap::_update_octants_callback);
845 	ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &GridMap::resource_changed);
846 
847 	ClassDB::bind_method(D_METHOD("set_center_x", "enable"), &GridMap::set_center_x);
848 	ClassDB::bind_method(D_METHOD("get_center_x"), &GridMap::get_center_x);
849 	ClassDB::bind_method(D_METHOD("set_center_y", "enable"), &GridMap::set_center_y);
850 	ClassDB::bind_method(D_METHOD("get_center_y"), &GridMap::get_center_y);
851 	ClassDB::bind_method(D_METHOD("set_center_z", "enable"), &GridMap::set_center_z);
852 	ClassDB::bind_method(D_METHOD("get_center_z"), &GridMap::get_center_z);
853 
854 	ClassDB::bind_method(D_METHOD("set_clip", "enabled", "clipabove", "floor", "axis"), &GridMap::set_clip, DEFVAL(true), DEFVAL(0), DEFVAL(Vector3::AXIS_X));
855 
856 	ClassDB::bind_method(D_METHOD("clear"), &GridMap::clear);
857 
858 	ClassDB::bind_method(D_METHOD("get_used_cells"), &GridMap::get_used_cells);
859 
860 	ClassDB::bind_method(D_METHOD("get_meshes"), &GridMap::get_meshes);
861 	ClassDB::bind_method(D_METHOD("get_bake_meshes"), &GridMap::get_bake_meshes);
862 	ClassDB::bind_method(D_METHOD("get_bake_mesh_instance", "idx"), &GridMap::get_bake_mesh_instance);
863 
864 	ClassDB::bind_method(D_METHOD("clear_baked_meshes"), &GridMap::clear_baked_meshes);
865 	ClassDB::bind_method(D_METHOD("make_baked_meshes", "gen_lightmap_uv", "lightmap_uv_texel_size"), &GridMap::make_baked_meshes, DEFVAL(false), DEFVAL(0.1));
866 
867 	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh_library", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary"), "set_mesh_library", "get_mesh_library");
868 	ADD_GROUP("Cell", "cell_");
869 	ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "cell_size"), "set_cell_size", "get_cell_size");
870 	ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_octant_size", PROPERTY_HINT_RANGE, "1,1024,1"), "set_octant_size", "get_octant_size");
871 	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_x"), "set_center_x", "get_center_x");
872 	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_y"), "set_center_y", "get_center_y");
873 	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_z"), "set_center_z", "get_center_z");
874 	ADD_PROPERTY(PropertyInfo(Variant::REAL, "cell_scale"), "set_cell_scale", "get_cell_scale");
875 	ADD_GROUP("Collision", "collision_");
876 	ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
877 	ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
878 
879 	BIND_CONSTANT(INVALID_CELL_ITEM);
880 
881 	ADD_SIGNAL(MethodInfo("cell_size_changed", PropertyInfo(Variant::VECTOR3, "cell_size")));
882 }
883 
set_clip(bool p_enabled,bool p_clip_above,int p_floor,Vector3::Axis p_axis)884 void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) {
885 
886 	if (!p_enabled && !clip)
887 		return;
888 	if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis)
889 		return;
890 
891 	clip = p_enabled;
892 	clip_floor = p_floor;
893 	clip_axis = p_axis;
894 	clip_above = p_clip_above;
895 
896 	//make it all update
897 	for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
898 
899 		Octant *g = E->get();
900 		g->dirty = true;
901 	}
902 	awaiting_update = true;
903 	_update_octants_callback();
904 }
905 
set_cell_scale(float p_scale)906 void GridMap::set_cell_scale(float p_scale) {
907 
908 	cell_scale = p_scale;
909 	_recreate_octant_data();
910 }
911 
get_cell_scale() const912 float GridMap::get_cell_scale() const {
913 
914 	return cell_scale;
915 }
916 
get_used_cells() const917 Array GridMap::get_used_cells() const {
918 
919 	Array a;
920 	a.resize(cell_map.size());
921 	int i = 0;
922 	for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
923 		Vector3 p(E->key().x, E->key().y, E->key().z);
924 		a[i++] = p;
925 	}
926 
927 	return a;
928 }
929 
get_meshes()930 Array GridMap::get_meshes() {
931 
932 	if (mesh_library.is_null())
933 		return Array();
934 
935 	Vector3 ofs = _get_offset();
936 	Array meshes;
937 
938 	for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
939 
940 		int id = E->get().item;
941 		if (!mesh_library->has_item(id))
942 			continue;
943 		Ref<Mesh> mesh = mesh_library->get_item_mesh(id);
944 		if (mesh.is_null())
945 			continue;
946 
947 		IndexKey ik = E->key();
948 
949 		Vector3 cellpos = Vector3(ik.x, ik.y, ik.z);
950 
951 		Transform xform;
952 
953 		xform.basis.set_orthogonal_index(E->get().rot);
954 
955 		xform.set_origin(cellpos * cell_size + ofs);
956 		xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
957 
958 		meshes.push_back(xform);
959 		meshes.push_back(mesh);
960 	}
961 
962 	return meshes;
963 }
964 
_get_offset() const965 Vector3 GridMap::_get_offset() const {
966 	return Vector3(
967 			cell_size.x * 0.5 * int(center_x),
968 			cell_size.y * 0.5 * int(center_y),
969 			cell_size.z * 0.5 * int(center_z));
970 }
971 
clear_baked_meshes()972 void GridMap::clear_baked_meshes() {
973 
974 	for (int i = 0; i < baked_meshes.size(); i++) {
975 		VS::get_singleton()->free(baked_meshes[i].instance);
976 	}
977 	baked_meshes.clear();
978 
979 	_recreate_octant_data();
980 }
981 
make_baked_meshes(bool p_gen_lightmap_uv,float p_lightmap_uv_texel_size)982 void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texel_size) {
983 
984 	if (!mesh_library.is_valid())
985 		return;
986 
987 	//generate
988 	Map<OctantKey, Map<Ref<Material>, Ref<SurfaceTool> > > surface_map;
989 
990 	for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
991 
992 		IndexKey key = E->key();
993 
994 		int item = E->get().item;
995 		if (!mesh_library->has_item(item))
996 			continue;
997 
998 		Ref<Mesh> mesh = mesh_library->get_item_mesh(item);
999 		if (!mesh.is_valid())
1000 			continue;
1001 
1002 		Vector3 cellpos = Vector3(key.x, key.y, key.z);
1003 		Vector3 ofs = _get_offset();
1004 
1005 		Transform xform;
1006 
1007 		xform.basis.set_orthogonal_index(E->get().rot);
1008 		xform.set_origin(cellpos * cell_size + ofs);
1009 		xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
1010 
1011 		OctantKey ok;
1012 		ok.x = key.x / octant_size;
1013 		ok.y = key.y / octant_size;
1014 		ok.z = key.z / octant_size;
1015 
1016 		if (!surface_map.has(ok)) {
1017 			surface_map[ok] = Map<Ref<Material>, Ref<SurfaceTool> >();
1018 		}
1019 
1020 		Map<Ref<Material>, Ref<SurfaceTool> > &mat_map = surface_map[ok];
1021 
1022 		for (int i = 0; i < mesh->get_surface_count(); i++) {
1023 
1024 			if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
1025 				continue;
1026 
1027 			Ref<Material> surf_mat = mesh->surface_get_material(i);
1028 			if (!mat_map.has(surf_mat)) {
1029 				Ref<SurfaceTool> st;
1030 				st.instance();
1031 				st->begin(Mesh::PRIMITIVE_TRIANGLES);
1032 				st->set_material(surf_mat);
1033 				mat_map[surf_mat] = st;
1034 			}
1035 
1036 			mat_map[surf_mat]->append_from(mesh, i, xform);
1037 		}
1038 	}
1039 
1040 	for (Map<OctantKey, Map<Ref<Material>, Ref<SurfaceTool> > >::Element *E = surface_map.front(); E; E = E->next()) {
1041 
1042 		Ref<ArrayMesh> mesh;
1043 		mesh.instance();
1044 		for (Map<Ref<Material>, Ref<SurfaceTool> >::Element *F = E->get().front(); F; F = F->next()) {
1045 			F->get()->commit(mesh);
1046 		}
1047 
1048 		BakedMesh bm;
1049 		bm.mesh = mesh;
1050 		bm.instance = VS::get_singleton()->instance_create();
1051 		VS::get_singleton()->get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid());
1052 		VS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id());
1053 		if (is_inside_tree()) {
1054 			VS::get_singleton()->instance_set_scenario(bm.instance, get_world()->get_scenario());
1055 			VS::get_singleton()->instance_set_transform(bm.instance, get_global_transform());
1056 		}
1057 
1058 		if (p_gen_lightmap_uv) {
1059 			mesh->lightmap_unwrap(get_global_transform(), p_lightmap_uv_texel_size);
1060 		}
1061 		baked_meshes.push_back(bm);
1062 	}
1063 
1064 	_recreate_octant_data();
1065 }
1066 
get_bake_meshes()1067 Array GridMap::get_bake_meshes() {
1068 
1069 	if (!baked_meshes.size()) {
1070 		make_baked_meshes(true);
1071 	}
1072 
1073 	Array arr;
1074 	for (int i = 0; i < baked_meshes.size(); i++) {
1075 		arr.push_back(baked_meshes[i].mesh);
1076 		arr.push_back(Transform());
1077 	}
1078 
1079 	return arr;
1080 }
1081 
get_bake_mesh_instance(int p_idx)1082 RID GridMap::get_bake_mesh_instance(int p_idx) {
1083 
1084 	ERR_FAIL_INDEX_V(p_idx, baked_meshes.size(), RID());
1085 	return baked_meshes[p_idx].instance;
1086 }
1087 
GridMap()1088 GridMap::GridMap() {
1089 
1090 	collision_layer = 1;
1091 	collision_mask = 1;
1092 
1093 	cell_size = Vector3(2, 2, 2);
1094 	octant_size = 8;
1095 	awaiting_update = false;
1096 	_in_tree = false;
1097 	center_x = true;
1098 	center_y = true;
1099 	center_z = true;
1100 
1101 	clip = false;
1102 	clip_floor = 0;
1103 	clip_axis = Vector3::AXIS_Z;
1104 	clip_above = true;
1105 	cell_scale = 1.0;
1106 
1107 	navigation = NULL;
1108 	set_notify_transform(true);
1109 	recreating_octants = false;
1110 }
1111 
~GridMap()1112 GridMap::~GridMap() {
1113 
1114 	if (!mesh_library.is_null())
1115 		mesh_library->unregister_owner(this);
1116 
1117 	clear();
1118 }
1119