From 4d73c7e9c6f6b8e53a0a95fc31d0d44841a57f0d Mon Sep 17 00:00:00 2001 From: Relintai Date: Fri, 31 May 2019 23:03:38 +0200 Subject: [PATCH] Added in gridmap from godot, I currently think it is a nice place to start from with the voxel world, as it pretty much already works like it, and it has a nice editor plugin as well. Also I haven't yet used godot's servers too much. --- doc_classes/GridMap.xml | 225 +++++ doc_classes/README.md | 1 + world/grid_map.cpp | 1147 ++++++++++++++++++++++ world/grid_map.h | 279 ++++++ world/grid_map_editor_plugin.cpp | 1557 ++++++++++++++++++++++++++++++ world/grid_map_editor_plugin.h | 274 ++++++ 6 files changed, 3483 insertions(+) create mode 100644 doc_classes/GridMap.xml create mode 100644 doc_classes/README.md create mode 100644 world/grid_map.cpp create mode 100644 world/grid_map.h create mode 100644 world/grid_map_editor_plugin.cpp create mode 100644 world/grid_map_editor_plugin.h diff --git a/doc_classes/GridMap.xml b/doc_classes/GridMap.xml new file mode 100644 index 0000000..f8f9fc1 --- /dev/null +++ b/doc_classes/GridMap.xml @@ -0,0 +1,225 @@ + + + + Node for 3D tile-based maps. + + + GridMap lets you place meshes on a grid interactively. It works both from the editor and can help you create in-game level editors. + GridMaps use a [MeshLibrary] which contain a list of tiles: meshes with materials plus optional collisions and extra elements. + A GridMap contains a collection of cells. Each grid cell refers to a [MeshLibrary] item. All cells in the map have the same dimensions. + A GridMap is split into a sparse collection of octants for efficient rendering and physics processing. Every octant has the same dimensions and can contain several cells. + + + https://docs.godotengine.org/en/latest/tutorials/3d/using_gridmaps.html + + + + + + + Clear all cells. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The [MeshLibrary] item index located at the grid-based X, Y and Z coordinates. If the cell is empty, [constant INVALID_CELL_ITEM] will be returned. + + + + + + + + + + + + + The orientation of the cell at the grid-based X, Y and Z coordinates. -1 is returned if the cell is empty. + + + + + + + + + + + + + + + + + + + + + + + Array of [Transform] and [Mesh] references corresponding to the non empty cells in the grid. The transforms are specified in world space. + + + + + + + Array of [Vector3] with the non empty cell coordinates in the grid map. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Set the mesh index for the cell referenced by its grid-based X, Y and Z coordinates. + A negative item index will clear the cell. + Optionally, the item's orientation can be passed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + If [code]true[/code], grid items are centered on the X axis. + + + If [code]true[/code], grid items are centered on the Y axis. + + + If [code]true[/code], grid items are centered on the Z axis. + + + The size of each octant measured in number of cells. This applies to all three axis. + + + + + The dimensions of the grid's cells. + + + + + + + The assigned [MeshLibrary]. + + + Deprecated, use [member mesh_library] instead. + + + + + Invalid cell item that can be used in [method set_cell_item] to clear cells (or represent an empty cell in [method get_cell_item]). + + + diff --git a/doc_classes/README.md b/doc_classes/README.md new file mode 100644 index 0000000..b1ec905 --- /dev/null +++ b/doc_classes/README.md @@ -0,0 +1 @@ +Doc classes will appear here when generating \ No newline at end of file diff --git a/world/grid_map.cpp b/world/grid_map.cpp new file mode 100644 index 0000000..32a014e --- /dev/null +++ b/world/grid_map.cpp @@ -0,0 +1,1147 @@ +/*************************************************************************/ +/* grid_map.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "grid_map.h" + +#include "core/io/marshalls.h" +#include "core/message_queue.h" +#include "scene/3d/light.h" +#include "scene/resources/mesh_library.h" +#include "scene/resources/surface_tool.h" +#include "scene/scene_string_names.h" +#include "servers/visual_server.h" + +bool GridMap::_set(const StringName &p_name, const Variant &p_value) { + + String name = p_name; + + if (name == "data") { + + Dictionary d = p_value; + + if (d.has("cells")) { + + PoolVector cells = d["cells"]; + int amount = cells.size(); + PoolVector::Read r = cells.read(); + ERR_FAIL_COND_V(amount % 3, false); // not even + cell_map.clear(); + for (int i = 0; i < amount / 3; i++) { + + IndexKey ik; + ik.key = decode_uint64((const uint8_t *)&r[i * 3]); + Cell cell; + cell.cell = decode_uint32((const uint8_t *)&r[i * 3 + 2]); + cell_map[ik] = cell; + } + } + + _recreate_octant_data(); + + } else if (name == "baked_meshes") { + + clear_baked_meshes(); + + Array meshes = p_value; + + for (int i = 0; i < meshes.size(); i++) { + BakedMesh bm; + bm.mesh = meshes[i]; + ERR_CONTINUE(!bm.mesh.is_valid()); + bm.instance = VS::get_singleton()->instance_create(); + VS::get_singleton()->get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid()); + VS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id()); + if (is_inside_tree()) { + VS::get_singleton()->instance_set_scenario(bm.instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(bm.instance, get_global_transform()); + } + baked_meshes.push_back(bm); + } + + _recreate_octant_data(); + + } else { + return false; + } + + return true; +} + +bool GridMap::_get(const StringName &p_name, Variant &r_ret) const { + + String name = p_name; + + if (name == "data") { + + Dictionary d; + + PoolVector cells; + cells.resize(cell_map.size() * 3); + { + PoolVector::Write w = cells.write(); + int i = 0; + for (Map::Element *E = cell_map.front(); E; E = E->next(), i++) { + + encode_uint64(E->key().key, (uint8_t *)&w[i * 3]); + encode_uint32(E->get().cell, (uint8_t *)&w[i * 3 + 2]); + } + } + + d["cells"] = cells; + + r_ret = d; + } else if (name == "baked_meshes") { + + Array ret; + ret.resize(baked_meshes.size()); + for (int i = 0; i < baked_meshes.size(); i++) { + ret.push_back(baked_meshes[i].mesh); + } + r_ret = ret; + + } else + return false; + + return true; +} + +void GridMap::_get_property_list(List *p_list) const { + + if (baked_meshes.size()) { + p_list->push_back(PropertyInfo(Variant::ARRAY, "baked_meshes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); + } + + p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE)); +} + +void GridMap::set_collision_layer(uint32_t p_layer) { + + collision_layer = p_layer; + _reset_physic_bodies_collision_filters(); +} + +uint32_t GridMap::get_collision_layer() const { + + return collision_layer; +} + +void GridMap::set_collision_mask(uint32_t p_mask) { + + collision_mask = p_mask; + _reset_physic_bodies_collision_filters(); +} + +uint32_t GridMap::get_collision_mask() const { + + return collision_mask; +} + +void GridMap::set_collision_mask_bit(int p_bit, bool p_value) { + + uint32_t mask = get_collision_mask(); + if (p_value) + mask |= 1 << p_bit; + else + mask &= ~(1 << p_bit); + set_collision_mask(mask); +} + +bool GridMap::get_collision_mask_bit(int p_bit) const { + + return get_collision_mask() & (1 << p_bit); +} + +void GridMap::set_collision_layer_bit(int p_bit, bool p_value) { + + uint32_t mask = get_collision_layer(); + if (p_value) + mask |= 1 << p_bit; + else + mask &= ~(1 << p_bit); + set_collision_layer(mask); +} + +bool GridMap::get_collision_layer_bit(int p_bit) const { + + return get_collision_layer() & (1 << p_bit); +} + +#ifndef DISABLE_DEPRECATED +void GridMap::set_theme(const Ref &p_theme) { + + ERR_EXPLAIN("GridMap.theme/set_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/set_mesh_library() instead."); + WARN_DEPRECATED + + set_mesh_library(p_theme); +} + +Ref GridMap::get_theme() const { + + ERR_EXPLAIN("GridMap.theme/get_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/get_mesh_library() instead."); + WARN_DEPRECATED + + return get_mesh_library(); +} +#endif // DISABLE_DEPRECATED + +void GridMap::set_mesh_library(const Ref &p_mesh_library) { + + if (!mesh_library.is_null()) + mesh_library->unregister_owner(this); + mesh_library = p_mesh_library; + if (!mesh_library.is_null()) + mesh_library->register_owner(this); + + _recreate_octant_data(); + _change_notify("mesh_library"); +} + +Ref GridMap::get_mesh_library() const { + + return mesh_library; +} + +void GridMap::set_cell_size(const Vector3 &p_size) { + + ERR_FAIL_COND(p_size.x < 0.001 || p_size.y < 0.001 || p_size.z < 0.001); + cell_size = p_size; + _recreate_octant_data(); +} +Vector3 GridMap::get_cell_size() const { + + return cell_size; +} + +void GridMap::set_octant_size(int p_size) { + + octant_size = p_size; + _recreate_octant_data(); +} +int GridMap::get_octant_size() const { + + return octant_size; +} + +void GridMap::set_center_x(bool p_enable) { + + center_x = p_enable; + _recreate_octant_data(); +} + +bool GridMap::get_center_x() const { + return center_x; +} + +void GridMap::set_center_y(bool p_enable) { + + center_y = p_enable; + _recreate_octant_data(); +} + +bool GridMap::get_center_y() const { + return center_y; +} + +void GridMap::set_center_z(bool p_enable) { + + center_z = p_enable; + _recreate_octant_data(); +} + +bool GridMap::get_center_z() const { + return center_z; +} + +void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) { + + if (baked_meshes.size() && !recreating_octants) { + //if you set a cell item, baked meshes go good bye + clear_baked_meshes(); + _recreate_octant_data(); + } + + ERR_FAIL_INDEX(ABS(p_x), 1 << 20); + ERR_FAIL_INDEX(ABS(p_y), 1 << 20); + ERR_FAIL_INDEX(ABS(p_z), 1 << 20); + + IndexKey key; + key.x = p_x; + key.y = p_y; + key.z = p_z; + + OctantKey ok; + ok.x = p_x / octant_size; + ok.y = p_y / octant_size; + ok.z = p_z / octant_size; + + if (p_item < 0) { + //erase + if (cell_map.has(key)) { + OctantKey octantkey = ok; + + ERR_FAIL_COND(!octant_map.has(octantkey)); + Octant &g = *octant_map[octantkey]; + g.cells.erase(key); + g.dirty = true; + cell_map.erase(key); + _queue_octants_dirty(); + } + return; + } + + OctantKey octantkey = ok; + + if (!octant_map.has(octantkey)) { + //create octant because it does not exist + Octant *g = memnew(Octant); + g->dirty = true; + g->static_body = PhysicsServer::get_singleton()->body_create(PhysicsServer::BODY_MODE_STATIC); + PhysicsServer::get_singleton()->body_attach_object_instance_id(g->static_body, get_instance_id()); + PhysicsServer::get_singleton()->body_set_collision_layer(g->static_body, collision_layer); + PhysicsServer::get_singleton()->body_set_collision_mask(g->static_body, collision_mask); + SceneTree *st = SceneTree::get_singleton(); + + if (st && st->is_debugging_collisions_hint()) { + + g->collision_debug = VisualServer::get_singleton()->mesh_create(); + g->collision_debug_instance = VisualServer::get_singleton()->instance_create(); + VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance, g->collision_debug); + } + + octant_map[octantkey] = g; + + if (is_inside_world()) { + _octant_enter_world(octantkey); + _octant_transform(octantkey); + } + } + + Octant &g = *octant_map[octantkey]; + g.cells.insert(key); + g.dirty = true; + _queue_octants_dirty(); + + Cell c; + c.item = p_item; + c.rot = p_rot; + + cell_map[key] = c; +} + +int GridMap::get_cell_item(int p_x, int p_y, int p_z) const { + + ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, INVALID_CELL_ITEM); + ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, INVALID_CELL_ITEM); + ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, INVALID_CELL_ITEM); + + IndexKey key; + key.x = p_x; + key.y = p_y; + key.z = p_z; + + if (!cell_map.has(key)) + return INVALID_CELL_ITEM; + return cell_map[key].item; +} + +int GridMap::get_cell_item_orientation(int p_x, int p_y, int p_z) const { + + ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, -1); + ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, -1); + ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, -1); + + IndexKey key; + key.x = p_x; + key.y = p_y; + key.z = p_z; + + if (!cell_map.has(key)) + return -1; + return cell_map[key].rot; +} + +Vector3 GridMap::world_to_map(const Vector3 &p_world_pos) const { + Vector3 map_pos = p_world_pos / cell_size; + map_pos.x = floor(map_pos.x); + map_pos.y = floor(map_pos.y); + map_pos.z = floor(map_pos.z); + return map_pos; +} + +Vector3 GridMap::map_to_world(int p_x, int p_y, int p_z) const { + Vector3 offset = _get_offset(); + Vector3 world_pos( + p_x * cell_size.x + offset.x, + p_y * cell_size.y + offset.y, + p_z * cell_size.z + offset.z); + return world_pos; +} + +void GridMap::_octant_transform(const OctantKey &p_key) { + + ERR_FAIL_COND(!octant_map.has(p_key)); + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); + + if (g.collision_debug_instance.is_valid()) { + VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform()); + } + + for (int i = 0; i < g.multimesh_instances.size(); i++) { + VS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform()); + } +} + +bool GridMap::_octant_update(const OctantKey &p_key) { + ERR_FAIL_COND_V(!octant_map.has(p_key), false); + Octant &g = *octant_map[p_key]; + if (!g.dirty) + return false; + + //erase body shapes + PhysicsServer::get_singleton()->body_clear_shapes(g.static_body); + + //erase body shapes debug + if (g.collision_debug.is_valid()) { + + VS::get_singleton()->mesh_clear(g.collision_debug); + } + + //erase navigation + if (navigation) { + for (Map::Element *E = g.navmesh_ids.front(); E; E = E->next()) { + navigation->navmesh_remove(E->get().id); + } + g.navmesh_ids.clear(); + } + + //erase multimeshes + + for (int i = 0; i < g.multimesh_instances.size(); i++) { + + VS::get_singleton()->free(g.multimesh_instances[i].instance); + VS::get_singleton()->free(g.multimesh_instances[i].multimesh); + } + g.multimesh_instances.clear(); + + if (g.cells.size() == 0) { + //octant no longer needed + _octant_clean_up(p_key); + return true; + } + + PoolVector col_debug; + + /* + * foreach item in this octant, + * set item's multimesh's instance count to number of cells which have this item + * and set said multimesh bounding box to one containing all cells which have this item + */ + + Map > > multimesh_items; + + for (Set::Element *E = g.cells.front(); E; E = E->next()) { + + ERR_CONTINUE(!cell_map.has(E->get())); + const Cell &c = cell_map[E->get()]; + + if (!mesh_library.is_valid() || !mesh_library->has_item(c.item)) + continue; + + Vector3 cellpos = Vector3(E->get().x, E->get().y, E->get().z); + Vector3 ofs = _get_offset(); + + Transform xform; + + if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) { + + } else { + } + + xform.basis.set_orthogonal_index(c.rot); + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); + if (baked_meshes.size() == 0) { + if (mesh_library->get_item_mesh(c.item).is_valid()) { + if (!multimesh_items.has(c.item)) { + multimesh_items[c.item] = List >(); + } + + Pair p; + p.first = xform; + p.second = E->get(); + multimesh_items[c.item].push_back(p); + } + } + + Vector shapes = mesh_library->get_item_shapes(c.item); + // add the item's shape at given xform to octant's static_body + for (int i = 0; i < shapes.size(); i++) { + // add the item's shape + if (!shapes[i].shape.is_valid()) + continue; + PhysicsServer::get_singleton()->body_add_shape(g.static_body, shapes[i].shape->get_rid(), xform * shapes[i].local_transform); + if (g.collision_debug.is_valid()) { + shapes.write[i].shape->add_vertices_to_array(col_debug, xform * shapes[i].local_transform); + } + } + + // add the item's navmesh at given xform to GridMap's Navigation ancestor + Ref navmesh = mesh_library->get_item_navmesh(c.item); + if (navmesh.is_valid()) { + Octant::NavMesh nm; + nm.xform = xform * mesh_library->get_item_navmesh_transform(c.item); + + if (navigation) { + nm.id = navigation->navmesh_add(navmesh, xform, this); + } else { + nm.id = -1; + } + g.navmesh_ids[E->get()] = nm; + } + } + + //update multimeshes, only if not baked + if (baked_meshes.size() == 0) { + + for (Map > >::Element *E = multimesh_items.front(); E; E = E->next()) { + Octant::MultimeshInstance mmi; + + RID mm = VS::get_singleton()->multimesh_create(); + VS::get_singleton()->multimesh_allocate(mm, E->get().size(), VS::MULTIMESH_TRANSFORM_3D, VS::MULTIMESH_COLOR_NONE); + VS::get_singleton()->multimesh_set_mesh(mm, mesh_library->get_item_mesh(E->key())->get_rid()); + + int idx = 0; + for (List >::Element *F = E->get().front(); F; F = F->next()) { + VS::get_singleton()->multimesh_instance_set_transform(mm, idx, F->get().first); +#ifdef TOOLS_ENABLED + + Octant::MultimeshInstance::Item it; + it.index = idx; + it.transform = F->get().first; + it.key = F->get().second; + mmi.items.push_back(it); +#endif + + idx++; + } + + RID instance = VS::get_singleton()->instance_create(); + VS::get_singleton()->instance_set_base(instance, mm); + + if (is_inside_tree()) { + VS::get_singleton()->instance_set_scenario(instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(instance, get_global_transform()); + } + + mmi.multimesh = mm; + mmi.instance = instance; + + g.multimesh_instances.push_back(mmi); + } + } + + if (col_debug.size()) { + + Array arr; + arr.resize(VS::ARRAY_MAX); + arr[VS::ARRAY_VERTEX] = col_debug; + + VS::get_singleton()->mesh_add_surface_from_arrays(g.collision_debug, VS::PRIMITIVE_LINES, arr); + SceneTree *st = SceneTree::get_singleton(); + if (st) { + VS::get_singleton()->mesh_surface_set_material(g.collision_debug, 0, st->get_debug_collision_material()->get_rid()); + } + } + + g.dirty = false; + + return false; +} + +void GridMap::_reset_physic_bodies_collision_filters() { + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + PhysicsServer::get_singleton()->body_set_collision_layer(E->get()->static_body, collision_layer); + PhysicsServer::get_singleton()->body_set_collision_mask(E->get()->static_body, collision_mask); + } +} + +void GridMap::_octant_enter_world(const OctantKey &p_key) { + + ERR_FAIL_COND(!octant_map.has(p_key)); + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); + PhysicsServer::get_singleton()->body_set_space(g.static_body, get_world()->get_space()); + + if (g.collision_debug_instance.is_valid()) { + VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform()); + } + + for (int i = 0; i < g.multimesh_instances.size(); i++) { + VS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform()); + } + + if (navigation && mesh_library.is_valid()) { + for (Map::Element *F = g.navmesh_ids.front(); F; F = F->next()) { + + if (cell_map.has(F->key()) && F->get().id < 0) { + Ref nm = mesh_library->get_item_navmesh(cell_map[F->key()].item); + if (nm.is_valid()) { + F->get().id = navigation->navmesh_add(nm, F->get().xform, this); + } + } + } + } +} + +void GridMap::_octant_exit_world(const OctantKey &p_key) { + + ERR_FAIL_COND(!octant_map.has(p_key)); + Octant &g = *octant_map[p_key]; + PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); + PhysicsServer::get_singleton()->body_set_space(g.static_body, RID()); + + if (g.collision_debug_instance.is_valid()) { + + VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, RID()); + } + + for (int i = 0; i < g.multimesh_instances.size(); i++) { + VS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, RID()); + } + + if (navigation) { + for (Map::Element *F = g.navmesh_ids.front(); F; F = F->next()) { + + if (F->get().id >= 0) { + navigation->navmesh_remove(F->get().id); + F->get().id = -1; + } + } + } +} + +void GridMap::_octant_clean_up(const OctantKey &p_key) { + + ERR_FAIL_COND(!octant_map.has(p_key)); + Octant &g = *octant_map[p_key]; + + if (g.collision_debug.is_valid()) + VS::get_singleton()->free(g.collision_debug); + if (g.collision_debug_instance.is_valid()) + VS::get_singleton()->free(g.collision_debug_instance); + + PhysicsServer::get_singleton()->free(g.static_body); + + //erase navigation + if (navigation) { + for (Map::Element *E = g.navmesh_ids.front(); E; E = E->next()) { + navigation->navmesh_remove(E->get().id); + } + g.navmesh_ids.clear(); + } + + //erase multimeshes + + for (int i = 0; i < g.multimesh_instances.size(); i++) { + + VS::get_singleton()->free(g.multimesh_instances[i].instance); + VS::get_singleton()->free(g.multimesh_instances[i].multimesh); + } + g.multimesh_instances.clear(); +} + +void GridMap::_notification(int p_what) { + + switch (p_what) { + + case NOTIFICATION_ENTER_WORLD: { + + Spatial *c = this; + while (c) { + navigation = Object::cast_to(c); + if (navigation) { + break; + } + + c = Object::cast_to(c->get_parent()); + } + + last_transform = get_global_transform(); + + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + _octant_enter_world(E->key()); + } + + for (int i = 0; i < baked_meshes.size(); i++) { + VS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform()); + } + + } break; + case NOTIFICATION_TRANSFORM_CHANGED: { + + Transform new_xform = get_global_transform(); + if (new_xform == last_transform) + break; + //update run + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + _octant_transform(E->key()); + } + + last_transform = new_xform; + + for (int i = 0; i < baked_meshes.size(); i++) { + VS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform()); + } + + } break; + case NOTIFICATION_EXIT_WORLD: { + + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + _octant_exit_world(E->key()); + } + + navigation = NULL; + + //_queue_octants_dirty(MAP_DIRTY_INSTANCES|MAP_DIRTY_TRANSFORMS); + //_update_octants_callback(); + //_update_area_instances(); + for (int i = 0; i < baked_meshes.size(); i++) { + VS::get_singleton()->instance_set_scenario(baked_meshes[i].instance, RID()); + } + + } break; + case NOTIFICATION_VISIBILITY_CHANGED: { + _update_visibility(); + } break; + } +} + +void GridMap::_update_visibility() { + if (!is_inside_tree()) + return; + + _change_notify("visible"); + + for (Map::Element *e = octant_map.front(); e; e = e->next()) { + Octant *octant = e->value(); + for (int i = 0; i < octant->multimesh_instances.size(); i++) { + const Octant::MultimeshInstance &mi = octant->multimesh_instances[i]; + VS::get_singleton()->instance_set_visible(mi.instance, is_visible()); + } + } +} + +void GridMap::_queue_octants_dirty() { + + if (awaiting_update) + return; + + MessageQueue::get_singleton()->push_call(this, "_update_octants_callback"); + awaiting_update = true; +} + +void GridMap::_recreate_octant_data() { + + recreating_octants = true; + Map cell_copy = cell_map; + _clear_internal(); + for (Map::Element *E = cell_copy.front(); E; E = E->next()) { + + set_cell_item(E->key().x, E->key().y, E->key().z, E->get().item, E->get().rot); + } + recreating_octants = false; +} + +void GridMap::_clear_internal() { + + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + if (is_inside_world()) + _octant_exit_world(E->key()); + + _octant_clean_up(E->key()); + memdelete(E->get()); + } + + octant_map.clear(); + cell_map.clear(); +} + +void GridMap::clear() { + + _clear_internal(); + clear_baked_meshes(); +} + +void GridMap::resource_changed(const RES &p_res) { + + _recreate_octant_data(); +} + +void GridMap::_update_octants_callback() { + + if (!awaiting_update) + return; + + List to_delete; + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + + if (_octant_update(E->key())) { + to_delete.push_back(E->key()); + } + } + + while (to_delete.front()) { + octant_map.erase(to_delete.front()->get()); + to_delete.pop_back(); + } + + _update_visibility(); + awaiting_update = false; +} + +void GridMap::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &GridMap::set_collision_layer); + ClassDB::bind_method(D_METHOD("get_collision_layer"), &GridMap::get_collision_layer); + + ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &GridMap::set_collision_mask); + ClassDB::bind_method(D_METHOD("get_collision_mask"), &GridMap::get_collision_mask); + + ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &GridMap::set_collision_mask_bit); + ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &GridMap::get_collision_mask_bit); + + ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &GridMap::set_collision_layer_bit); + ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &GridMap::get_collision_layer_bit); + +#ifndef DISABLE_DEPRECATED + ClassDB::bind_method(D_METHOD("set_theme", "theme"), &GridMap::set_theme); + ClassDB::bind_method(D_METHOD("get_theme"), &GridMap::get_theme); +#endif // DISABLE_DEPRECATED + + ClassDB::bind_method(D_METHOD("set_mesh_library", "mesh_library"), &GridMap::set_mesh_library); + ClassDB::bind_method(D_METHOD("get_mesh_library"), &GridMap::get_mesh_library); + + ClassDB::bind_method(D_METHOD("set_cell_size", "size"), &GridMap::set_cell_size); + ClassDB::bind_method(D_METHOD("get_cell_size"), &GridMap::get_cell_size); + + ClassDB::bind_method(D_METHOD("set_cell_scale", "scale"), &GridMap::set_cell_scale); + ClassDB::bind_method(D_METHOD("get_cell_scale"), &GridMap::get_cell_scale); + + ClassDB::bind_method(D_METHOD("set_octant_size", "size"), &GridMap::set_octant_size); + ClassDB::bind_method(D_METHOD("get_octant_size"), &GridMap::get_octant_size); + + ClassDB::bind_method(D_METHOD("set_cell_item", "x", "y", "z", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_cell_item", "x", "y", "z"), &GridMap::get_cell_item); + ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "x", "y", "z"), &GridMap::get_cell_item_orientation); + + ClassDB::bind_method(D_METHOD("world_to_map", "pos"), &GridMap::world_to_map); + ClassDB::bind_method(D_METHOD("map_to_world", "x", "y", "z"), &GridMap::map_to_world); + + ClassDB::bind_method(D_METHOD("_update_octants_callback"), &GridMap::_update_octants_callback); + ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &GridMap::resource_changed); + + ClassDB::bind_method(D_METHOD("set_center_x", "enable"), &GridMap::set_center_x); + ClassDB::bind_method(D_METHOD("get_center_x"), &GridMap::get_center_x); + ClassDB::bind_method(D_METHOD("set_center_y", "enable"), &GridMap::set_center_y); + ClassDB::bind_method(D_METHOD("get_center_y"), &GridMap::get_center_y); + ClassDB::bind_method(D_METHOD("set_center_z", "enable"), &GridMap::set_center_z); + ClassDB::bind_method(D_METHOD("get_center_z"), &GridMap::get_center_z); + + ClassDB::bind_method(D_METHOD("set_clip", "enabled", "clipabove", "floor", "axis"), &GridMap::set_clip, DEFVAL(true), DEFVAL(0), DEFVAL(Vector3::AXIS_X)); + + ClassDB::bind_method(D_METHOD("clear"), &GridMap::clear); + + ClassDB::bind_method(D_METHOD("get_used_cells"), &GridMap::get_used_cells); + + ClassDB::bind_method(D_METHOD("get_meshes"), &GridMap::get_meshes); + ClassDB::bind_method(D_METHOD("get_bake_meshes"), &GridMap::get_bake_meshes); + ClassDB::bind_method(D_METHOD("get_bake_mesh_instance", "idx"), &GridMap::get_bake_mesh_instance); + + ClassDB::bind_method(D_METHOD("clear_baked_meshes"), &GridMap::clear_baked_meshes); + ClassDB::bind_method(D_METHOD("make_baked_meshes", "gen_lightmap_uv", "lightmap_uv_texel_size"), &GridMap::make_baked_meshes, DEFVAL(false), DEFVAL(0.1)); + +#ifndef DISABLE_DEPRECATED + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary", 0), "set_theme", "get_theme"); +#endif // DISABLE_DEPRECATED + + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh_library", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary"), "set_mesh_library", "get_mesh_library"); + ADD_GROUP("Cell", "cell_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "cell_size"), "set_cell_size", "get_cell_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_octant_size", PROPERTY_HINT_RANGE, "1,1024,1"), "set_octant_size", "get_octant_size"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_x"), "set_center_x", "get_center_x"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_y"), "set_center_y", "get_center_y"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_center_z"), "set_center_z", "get_center_z"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "cell_scale"), "set_cell_scale", "get_cell_scale"); + ADD_GROUP("Collision", "collision_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask"); + + BIND_CONSTANT(INVALID_CELL_ITEM); +} + +void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) { + + if (!p_enabled && !clip) + return; + if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis) + return; + + clip = p_enabled; + clip_floor = p_floor; + clip_axis = p_axis; + clip_above = p_clip_above; + + //make it all update + for (Map::Element *E = octant_map.front(); E; E = E->next()) { + + Octant *g = E->get(); + g->dirty = true; + } + awaiting_update = true; + _update_octants_callback(); +} + +void GridMap::set_cell_scale(float p_scale) { + + cell_scale = p_scale; + _recreate_octant_data(); +} + +float GridMap::get_cell_scale() const { + + return cell_scale; +} + +Array GridMap::get_used_cells() const { + + Array a; + a.resize(cell_map.size()); + int i = 0; + for (Map::Element *E = cell_map.front(); E; E = E->next()) { + Vector3 p(E->key().x, E->key().y, E->key().z); + a[i++] = p; + } + + return a; +} + +Array GridMap::get_meshes() { + + if (mesh_library.is_null()) + return Array(); + + Vector3 ofs = _get_offset(); + Array meshes; + + for (Map::Element *E = cell_map.front(); E; E = E->next()) { + + int id = E->get().item; + if (!mesh_library->has_item(id)) + continue; + Ref mesh = mesh_library->get_item_mesh(id); + if (mesh.is_null()) + continue; + + IndexKey ik = E->key(); + + Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); + + Transform xform; + + xform.basis.set_orthogonal_index(E->get().rot); + + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); + + meshes.push_back(xform); + meshes.push_back(mesh); + } + + return meshes; +} + +Vector3 GridMap::_get_offset() const { + return Vector3( + cell_size.x * 0.5 * int(center_x), + cell_size.y * 0.5 * int(center_y), + cell_size.z * 0.5 * int(center_z)); +} + +void GridMap::clear_baked_meshes() { + + for (int i = 0; i < baked_meshes.size(); i++) { + VS::get_singleton()->free(baked_meshes[i].instance); + } + baked_meshes.clear(); + + _recreate_octant_data(); +} + +void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texel_size) { + + if (!mesh_library.is_valid()) + return; + + //generate + Map, Ref > > surface_map; + + for (Map::Element *E = cell_map.front(); E; E = E->next()) { + + IndexKey key = E->key(); + + int item = E->get().item; + if (!mesh_library->has_item(item)) + continue; + + Ref mesh = mesh_library->get_item_mesh(item); + if (!mesh.is_valid()) + continue; + + Vector3 cellpos = Vector3(key.x, key.y, key.z); + Vector3 ofs = _get_offset(); + + Transform xform; + + xform.basis.set_orthogonal_index(E->get().rot); + xform.set_origin(cellpos * cell_size + ofs); + xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); + + OctantKey ok; + ok.x = key.x / octant_size; + ok.y = key.y / octant_size; + ok.z = key.z / octant_size; + + if (!surface_map.has(ok)) { + surface_map[ok] = Map, Ref >(); + } + + Map, Ref > &mat_map = surface_map[ok]; + + for (int i = 0; i < mesh->get_surface_count(); i++) { + + if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) + continue; + + Ref surf_mat = mesh->surface_get_material(i); + if (!mat_map.has(surf_mat)) { + Ref st; + st.instance(); + st->begin(Mesh::PRIMITIVE_TRIANGLES); + st->set_material(surf_mat); + mat_map[surf_mat] = st; + } + + mat_map[surf_mat]->append_from(mesh, i, xform); + } + } + + for (Map, Ref > >::Element *E = surface_map.front(); E; E = E->next()) { + + Ref mesh; + mesh.instance(); + for (Map, Ref >::Element *F = E->get().front(); F; F = F->next()) { + F->get()->commit(mesh); + } + + BakedMesh bm; + bm.mesh = mesh; + bm.instance = VS::get_singleton()->instance_create(); + VS::get_singleton()->get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid()); + VS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id()); + if (is_inside_tree()) { + VS::get_singleton()->instance_set_scenario(bm.instance, get_world()->get_scenario()); + VS::get_singleton()->instance_set_transform(bm.instance, get_global_transform()); + } + + if (p_gen_lightmap_uv) { + mesh->lightmap_unwrap(get_global_transform(), p_lightmap_uv_texel_size); + } + baked_meshes.push_back(bm); + } + + _recreate_octant_data(); +} + +Array GridMap::get_bake_meshes() { + + if (!baked_meshes.size()) { + make_baked_meshes(true); + } + + Array arr; + for (int i = 0; i < baked_meshes.size(); i++) { + arr.push_back(baked_meshes[i].mesh); + arr.push_back(Transform()); + } + + return arr; +} + +RID GridMap::get_bake_mesh_instance(int p_idx) { + + ERR_FAIL_INDEX_V(p_idx, baked_meshes.size(), RID()); + return baked_meshes[p_idx].instance; +} + +GridMap::GridMap() { + + collision_layer = 1; + collision_mask = 1; + + cell_size = Vector3(2, 2, 2); + octant_size = 8; + awaiting_update = false; + _in_tree = false; + center_x = true; + center_y = true; + center_z = true; + + clip = false; + clip_floor = 0; + clip_axis = Vector3::AXIS_Z; + clip_above = true; + cell_scale = 1.0; + + navigation = NULL; + set_notify_transform(true); + recreating_octants = false; +} + +GridMap::~GridMap() { + + if (!mesh_library.is_null()) + mesh_library->unregister_owner(this); + + clear(); +} diff --git a/world/grid_map.h b/world/grid_map.h new file mode 100644 index 0000000..f440709 --- /dev/null +++ b/world/grid_map.h @@ -0,0 +1,279 @@ +/*************************************************************************/ +/* grid_map.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GRID_MAP_H +#define GRID_MAP_H + +#include "scene/3d/navigation.h" +#include "scene/3d/spatial.h" +#include "scene/resources/mesh_library.h" +#include "scene/resources/multimesh.h" + +//heh heh, godotsphir!! this shares no code and the design is completely different with previous projects i've done.. +//should scale better with hardware that supports instancing + +class GridMap : public Spatial { + + GDCLASS(GridMap, Spatial); + + enum { + MAP_DIRTY_TRANSFORMS = 1, + MAP_DIRTY_INSTANCES = 2, + }; + + union IndexKey { + + struct { + int16_t x; + int16_t y; + int16_t z; + }; + uint64_t key; + + _FORCE_INLINE_ bool operator<(const IndexKey &p_key) const { + + return key < p_key.key; + } + + IndexKey() { key = 0; } + }; + + /** + * @brief A Cell is a single cell in the cube map space; it is defined by its coordinates and the populating Item, identified by int id. + */ + union Cell { + + struct { + unsigned int item : 16; + unsigned int rot : 5; + unsigned int layer : 8; + }; + uint32_t cell; + + Cell() { + item = 0; + rot = 0; + layer = 0; + } + }; + + /** + * @brief An Octant is a prism containing Cells, and possibly belonging to an Area. + * A GridMap can have multiple Octants. + */ + struct Octant { + + struct NavMesh { + int id; + Transform xform; + }; + + struct MultimeshInstance { + RID instance; + RID multimesh; + struct Item { + int index; + Transform transform; + IndexKey key; + }; + + Vector items; //tools only, for changing visibility + }; + + Vector multimesh_instances; + Set cells; + RID collision_debug; + RID collision_debug_instance; + + bool dirty; + RID static_body; + Map navmesh_ids; + }; + + union OctantKey { + + struct { + int16_t x; + int16_t y; + int16_t z; + int16_t empty; + }; + + uint64_t key; + + _FORCE_INLINE_ bool operator<(const OctantKey &p_key) const { + + return key < p_key.key; + } + + //OctantKey(const IndexKey& p_k, int p_item) { indexkey=p_k.key; item=p_item; } + OctantKey() { key = 0; } + }; + + uint32_t collision_layer; + uint32_t collision_mask; + + Transform last_transform; + + bool _in_tree; + Vector3 cell_size; + int octant_size; + bool center_x, center_y, center_z; + float cell_scale; + Navigation *navigation; + + bool clip; + bool clip_above; + int clip_floor; + + bool recreating_octants; + + Vector3::Axis clip_axis; + + Ref mesh_library; + + Map octant_map; + Map cell_map; + + void _recreate_octant_data(); + + struct BakeLight { + + VS::LightType type; + Vector3 pos; + Vector3 dir; + float param[VS::LIGHT_PARAM_MAX]; + }; + + _FORCE_INLINE_ Vector3 _octant_get_offset(const OctantKey &p_key) const { + + return Vector3(p_key.x, p_key.y, p_key.z) * cell_size * octant_size; + } + + void _reset_physic_bodies_collision_filters(); + void _octant_enter_world(const OctantKey &p_key); + void _octant_exit_world(const OctantKey &p_key); + bool _octant_update(const OctantKey &p_key); + void _octant_clean_up(const OctantKey &p_key); + void _octant_transform(const OctantKey &p_key); + bool awaiting_update; + + void _queue_octants_dirty(); + void _update_octants_callback(); + + void resource_changed(const RES &p_res); + + void _clear_internal(); + + Vector3 _get_offset() const; + + struct BakedMesh { + Ref mesh; + RID instance; + }; + + Vector baked_meshes; + +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; + + void _notification(int p_what); + void _update_visibility(); + static void _bind_methods(); + +public: + enum { + INVALID_CELL_ITEM = -1 + }; + + void set_collision_layer(uint32_t p_layer); + uint32_t get_collision_layer() const; + + void set_collision_mask(uint32_t p_mask); + uint32_t get_collision_mask() const; + + void set_collision_layer_bit(int p_bit, bool p_value); + bool get_collision_layer_bit(int p_bit) const; + + void set_collision_mask_bit(int p_bit, bool p_value); + bool get_collision_mask_bit(int p_bit) const; + +#ifndef DISABLE_DEPRECATED + void set_theme(const Ref &p_theme); + Ref get_theme() const; +#endif // DISABLE_DEPRECATED + + void set_mesh_library(const Ref &p_mesh_library); + Ref get_mesh_library() const; + + void set_cell_size(const Vector3 &p_size); + Vector3 get_cell_size() const; + + void set_octant_size(int p_size); + int get_octant_size() const; + + void set_center_x(bool p_enable); + bool get_center_x() const; + void set_center_y(bool p_enable); + bool get_center_y() const; + void set_center_z(bool p_enable); + bool get_center_z() const; + + void set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot = 0); + int get_cell_item(int p_x, int p_y, int p_z) const; + int get_cell_item_orientation(int p_x, int p_y, int p_z) const; + + Vector3 world_to_map(const Vector3 &p_world_pos) const; + Vector3 map_to_world(int p_x, int p_y, int p_z) const; + + void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X); + + void set_cell_scale(float p_scale); + float get_cell_scale() const; + + Array get_used_cells() const; + + Array get_meshes(); + + void clear_baked_meshes(); + void make_baked_meshes(bool p_gen_lightmap_uv = false, float p_lightmap_uv_texel_size = 0.1); + + void clear(); + + Array get_bake_meshes(); + RID get_bake_mesh_instance(int p_idx); + + GridMap(); + ~GridMap(); +}; + +#endif // GRID_MAP_H diff --git a/world/grid_map_editor_plugin.cpp b/world/grid_map_editor_plugin.cpp new file mode 100644 index 0000000..890bd73 --- /dev/null +++ b/world/grid_map_editor_plugin.cpp @@ -0,0 +1,1557 @@ +/*************************************************************************/ +/* grid_map_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "grid_map_editor_plugin.h" +#include "core/os/input.h" +#include "editor/editor_scale.h" +#include "editor/editor_settings.h" +#include "editor/plugins/spatial_editor_plugin.h" +#include "scene/3d/camera.h" + +#include "core/math/geometry.h" +#include "core/os/keyboard.h" + +void GridMapEditor::_node_removed(Node *p_node) { + + if (p_node == node) { + node = NULL; + hide(); + mesh_library_palette->hide(); + } +} + +void GridMapEditor::_configure() { + + if (!node) + return; + + update_grid(); +} + +void GridMapEditor::_menu_option(int p_option) { + + switch (p_option) { + + case MENU_OPTION_PREV_LEVEL: { + floor->set_value(floor->get_value() - 1); + } break; + + case MENU_OPTION_NEXT_LEVEL: { + floor->set_value(floor->get_value() + 1); + } break; + + case MENU_OPTION_LOCK_VIEW: { + + int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW); + lock_view = !options->get_popup()->is_item_checked(index); + + options->get_popup()->set_item_checked(index, lock_view); + } break; + case MENU_OPTION_CLIP_DISABLED: + case MENU_OPTION_CLIP_ABOVE: + case MENU_OPTION_CLIP_BELOW: { + + clip_mode = ClipMode(p_option - MENU_OPTION_CLIP_DISABLED); + for (int i = 0; i < 3; i++) { + + int index = options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED + i); + options->get_popup()->set_item_checked(index, i == clip_mode); + } + + _update_clip(); + } break; + case MENU_OPTION_X_AXIS: + case MENU_OPTION_Y_AXIS: + case MENU_OPTION_Z_AXIS: { + + int new_axis = p_option - MENU_OPTION_X_AXIS; + for (int i = 0; i < 3; i++) { + int idx = options->get_popup()->get_item_index(MENU_OPTION_X_AXIS + i); + options->get_popup()->set_item_checked(idx, i == new_axis); + } + + if (edit_axis != new_axis) { + int item1 = options->get_popup()->get_item_index(MENU_OPTION_NEXT_LEVEL); + int item2 = options->get_popup()->get_item_index(MENU_OPTION_PREV_LEVEL); + if (edit_axis == Vector3::AXIS_Y) { + options->get_popup()->set_item_text(item1, TTR("Next Plane")); + options->get_popup()->set_item_text(item2, TTR("Previous Plane")); + spin_box_label->set_text(TTR("Plane:")); + } else if (new_axis == Vector3::AXIS_Y) { + options->get_popup()->set_item_text(item1, TTR("Next Floor")); + options->get_popup()->set_item_text(item2, TTR("Previous Floor")); + spin_box_label->set_text(TTR("Floor:")); + } + } + edit_axis = Vector3::Axis(new_axis); + update_grid(); + _update_clip(); + + } break; + case MENU_OPTION_CURSOR_ROTATE_Y: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_ROTATE_X: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_ROTATE_Z: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_BACK_ROTATE_Y: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_BACK_ROTATE_X: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_BACK_ROTATE_Z: { + + Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + + r.set_orthogonal_index(cursor_rot); + r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); + cursor_rot = r.get_orthogonal_index(); + _update_cursor_transform(); + } break; + case MENU_OPTION_CURSOR_CLEAR_ROTATION: { + + if (input_action == INPUT_PASTE) { + + paste_indicator.orientation = 0; + _update_paste_indicator(); + break; + } + + cursor_rot = 0; + _update_cursor_transform(); + } break; + + case MENU_OPTION_PASTE_SELECTS: { + int idx = options->get_popup()->get_item_index(MENU_OPTION_PASTE_SELECTS); + options->get_popup()->set_item_checked(idx, !options->get_popup()->is_item_checked(idx)); + } break; + + case MENU_OPTION_SELECTION_DUPLICATE: // fallthrough + case MENU_OPTION_SELECTION_CUT: { + if (!(selection.active && input_action == INPUT_NONE)) + break; + + _set_clipboard_data(); + + if (p_option == MENU_OPTION_SELECTION_CUT) { + _delete_selection(); + } + + input_action = INPUT_PASTE; + paste_indicator.click = selection.begin; + paste_indicator.current = selection.begin; + paste_indicator.begin = selection.begin; + paste_indicator.end = selection.end; + paste_indicator.orientation = 0; + _update_paste_indicator(); + } break; + case MENU_OPTION_SELECTION_CLEAR: { + if (!selection.active) + break; + + _delete_selection(); + + } break; + case MENU_OPTION_SELECTION_FILL: { + if (!selection.active) + return; + + _fill_selection(); + + } break; + case MENU_OPTION_GRIDMAP_SETTINGS: { + settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50) * EDSCALE); + } break; + } +} + +void GridMapEditor::_update_cursor_transform() { + + cursor_transform = Transform(); + cursor_transform.origin = cursor_origin; + cursor_transform.basis.set_orthogonal_index(cursor_rot); + cursor_transform = node->get_transform() * cursor_transform; + + if (cursor_instance.is_valid()) { + VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform); + VisualServer::get_singleton()->instance_set_visible(cursor_instance, cursor_visible); + } +} + +void GridMapEditor::_update_selection_transform() { + Transform xf_zero; + xf_zero.basis.set_zero(); + + if (!selection.active) { + + VisualServer::get_singleton()->instance_set_transform(selection_instance, xf_zero); + for (int i = 0; i < 3; i++) { + VisualServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf_zero); + } + return; + } + + Transform xf; + xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); + xf.origin = selection.begin * node->get_cell_size(); + + VisualServer::get_singleton()->instance_set_transform(selection_instance, node->get_global_transform() * xf); + + for (int i = 0; i < 3; i++) { + if (i != edit_axis || (edit_floor[edit_axis] < selection.begin[edit_axis]) || (edit_floor[edit_axis] > selection.end[edit_axis] + 1)) { + VisualServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf_zero); + } else { + + Vector3 scale = (selection.end - selection.begin + Vector3(1, 1, 1)); + scale[edit_axis] = 1.0; + Vector3 pos = selection.begin; + pos[edit_axis] = edit_floor[edit_axis]; + + scale *= node->get_cell_size(); + pos *= node->get_cell_size(); + + Transform xf2; + xf2.basis.scale(scale); + xf2.origin = pos; + + VisualServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf2); + } + } +} + +void GridMapEditor::_validate_selection() { + + if (!selection.active) + return; + selection.begin = selection.click; + selection.end = selection.current; + + if (selection.begin.x > selection.end.x) + SWAP(selection.begin.x, selection.end.x); + if (selection.begin.y > selection.end.y) + SWAP(selection.begin.y, selection.end.y); + if (selection.begin.z > selection.end.z) + SWAP(selection.begin.z, selection.end.z); + + _update_selection_transform(); +} + +void GridMapEditor::_set_selection(bool p_active, const Vector3 p_begin, const Vector3 p_end) { + + selection.active = p_active; + selection.begin = p_begin; + selection.end = p_end; + selection.click = p_begin; + selection.current = p_end; + + _update_selection_transform(); +} + +bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click) { + + if (!spatial_editor) + return false; + + if (selected_palette < 0 && input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE) + return false; + Ref mesh_library = node->get_mesh_library(); + if (mesh_library.is_null()) + return false; + if (input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE && !mesh_library->has_item(selected_palette)) + return false; + + Camera *camera = p_camera; + Vector3 from = camera->project_ray_origin(p_point); + Vector3 normal = camera->project_ray_normal(p_point); + Transform local_xform = node->get_global_transform().affine_inverse(); + Vector planes = camera->get_frustum(); + from = local_xform.xform(from); + normal = local_xform.basis.xform(normal).normalized(); + + Plane p; + p.normal[edit_axis] = 1.0; + p.d = edit_floor[edit_axis] * node->get_cell_size()[edit_axis]; + + Vector3 inters; + if (!p.intersects_segment(from, from + normal * settings_pick_distance->get_value(), &inters)) + return false; + + //make sure the intersection is inside the frustum planes, to avoid + //painting on invisible regions + for (int i = 0; i < planes.size(); i++) { + + Plane fp = local_xform.xform(planes[i]); + if (fp.is_point_over(inters)) + return false; + } + + int cell[3]; + float cell_size[3] = { node->get_cell_size().x, node->get_cell_size().y, node->get_cell_size().z }; + + last_mouseover = Vector3(-1, -1, -1); + + for (int i = 0; i < 3; i++) { + + if (i == edit_axis) + cell[i] = edit_floor[i]; + else { + + cell[i] = inters[i] / node->get_cell_size()[i]; + if (inters[i] < 0) + cell[i] -= 1; //compensate negative + grid_ofs[i] = cell[i] * cell_size[i]; + } + + /*if (cell[i]<0 || cell[i]>=grid_size[i]) { + + cursor_visible=false; + _update_cursor_transform(); + return false; + }*/ + } + + last_mouseover = Vector3(cell[0], cell[1], cell[2]); + VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Basis(), grid_ofs)); + + if (cursor_instance.is_valid()) { + + cursor_origin = (Vector3(cell[0], cell[1], cell[2]) + Vector3(0.5 * node->get_center_x(), 0.5 * node->get_center_y(), 0.5 * node->get_center_z())) * node->get_cell_size(); + cursor_visible = true; + + if (input_action == INPUT_SELECT || input_action == INPUT_PASTE) { + cursor_visible = false; + } + + _update_cursor_transform(); + } + + if (input_action == INPUT_PASTE) { + + paste_indicator.current = Vector3(cell[0], cell[1], cell[2]); + _update_paste_indicator(); + + } else if (input_action == INPUT_SELECT) { + + selection.current = Vector3(cell[0], cell[1], cell[2]); + if (p_click) + selection.click = selection.current; + selection.active = true; + _validate_selection(); + + return true; + } else if (input_action == INPUT_PICK) { + + int item = node->get_cell_item(cell[0], cell[1], cell[2]); + if (item >= 0) { + selected_palette = item; + mesh_library_palette->set_current(item); + update_palette(); + _update_cursor_instance(); + } + return true; + } + if (input_action == INPUT_PAINT) { + SetItem si; + si.pos = Vector3(cell[0], cell[1], cell[2]); + si.new_value = selected_palette; + si.new_orientation = cursor_rot; + si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]); + si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]); + set_items.push_back(si); + node->set_cell_item(cell[0], cell[1], cell[2], selected_palette, cursor_rot); + return true; + } else if (input_action == INPUT_ERASE) { + SetItem si; + si.pos = Vector3(cell[0], cell[1], cell[2]); + si.new_value = -1; + si.new_orientation = 0; + si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]); + si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]); + set_items.push_back(si); + node->set_cell_item(cell[0], cell[1], cell[2], -1); + return true; + } + + return false; +} + +void GridMapEditor::_delete_selection() { + + if (!selection.active) + return; + + undo_redo->create_action(TTR("GridMap Delete Selection")); + for (int i = selection.begin.x; i <= selection.end.x; i++) { + + for (int j = selection.begin.y; j <= selection.end.y; j++) { + + for (int k = selection.begin.z; k <= selection.end.z; k++) { + + undo_redo->add_do_method(node, "set_cell_item", i, j, k, GridMap::INVALID_CELL_ITEM); + undo_redo->add_undo_method(node, "set_cell_item", i, j, k, node->get_cell_item(i, j, k), node->get_cell_item_orientation(i, j, k)); + } + } + } + undo_redo->add_do_method(this, "_set_selection", !selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); + undo_redo->commit_action(); +} + +void GridMapEditor::_fill_selection() { + + if (!selection.active) + return; + + undo_redo->create_action(TTR("GridMap Fill Selection")); + for (int i = selection.begin.x; i <= selection.end.x; i++) { + + for (int j = selection.begin.y; j <= selection.end.y; j++) { + + for (int k = selection.begin.z; k <= selection.end.z; k++) { + + undo_redo->add_do_method(node, "set_cell_item", i, j, k, selected_palette, cursor_rot); + undo_redo->add_undo_method(node, "set_cell_item", i, j, k, node->get_cell_item(i, j, k), node->get_cell_item_orientation(i, j, k)); + } + } + } + undo_redo->add_do_method(this, "_set_selection", !selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); + undo_redo->commit_action(); +} + +void GridMapEditor::_clear_clipboard_data() { + + for (List::Element *E = clipboard_items.front(); E; E = E->next()) { + + VisualServer::get_singleton()->free(E->get().instance); + } + + clipboard_items.clear(); +} + +void GridMapEditor::_set_clipboard_data() { + + _clear_clipboard_data(); + + Ref meshLibrary = node->get_mesh_library(); + + for (int i = selection.begin.x; i <= selection.end.x; i++) { + + for (int j = selection.begin.y; j <= selection.end.y; j++) { + + for (int k = selection.begin.z; k <= selection.end.z; k++) { + + int itm = node->get_cell_item(i, j, k); + if (itm == GridMap::INVALID_CELL_ITEM) + continue; + + Ref mesh = meshLibrary->get_item_mesh(itm); + + ClipboardItem item; + item.cell_item = itm; + item.grid_offset = Vector3(i, j, k) - selection.begin; + item.orientation = node->get_cell_item_orientation(i, j, k); + item.instance = VisualServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world()->get_scenario()); + + clipboard_items.push_back(item); + } + } + } +} + +void GridMapEditor::_update_paste_indicator() { + + if (input_action != INPUT_PASTE) { + + Transform xf; + xf.basis.set_zero(); + VisualServer::get_singleton()->instance_set_transform(paste_instance, xf); + return; + } + + Vector3 center = 0.5 * Vector3(node->get_center_x(), node->get_center_y(), node->get_center_z()); + Vector3 scale = (Vector3(1, 1, 1) + (paste_indicator.end - paste_indicator.begin)) * node->get_cell_size(); + Transform xf; + xf.scale(scale); + xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); + Basis rot; + rot.set_orthogonal_index(paste_indicator.orientation); + xf.basis = rot * xf.basis; + xf.translate((-center * node->get_cell_size()) / scale); + + VisualServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf); + + for (List::Element *E = clipboard_items.front(); E; E = E->next()) { + + ClipboardItem &item = E->get(); + + xf = Transform(); + xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); + xf.basis = rot * xf.basis; + xf.translate(item.grid_offset * node->get_cell_size()); + + Basis item_rot; + item_rot.set_orthogonal_index(item.orientation); + xf.basis = item_rot * xf.basis; + + VisualServer::get_singleton()->instance_set_transform(item.instance, node->get_global_transform() * xf); + } +} + +void GridMapEditor::_do_paste() { + + int idx = options->get_popup()->get_item_index(MENU_OPTION_PASTE_SELECTS); + bool reselect = options->get_popup()->is_item_checked(idx); + + Basis rot; + rot.set_orthogonal_index(paste_indicator.orientation); + + Vector3 ofs = paste_indicator.current - paste_indicator.click; + undo_redo->create_action(TTR("GridMap Paste Selection")); + + for (List::Element *E = clipboard_items.front(); E; E = E->next()) { + + ClipboardItem &item = E->get(); + + Vector3 pos = rot.xform(item.grid_offset) + paste_indicator.begin + ofs; + + Basis orm; + orm.set_orthogonal_index(item.orientation); + orm = rot * orm; + + undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, item.cell_item, orm.get_orthogonal_index()); + undo_redo->add_undo_method(node, "set_cell_item", pos.x, pos.y, pos.z, node->get_cell_item(pos.x, pos.y, pos.z), node->get_cell_item_orientation(pos.x, pos.y, pos.z)); + } + + if (reselect) { + + undo_redo->add_do_method(this, "_set_selection", true, paste_indicator.begin + ofs, paste_indicator.end + ofs); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); + } + + undo_redo->commit_action(); + + _clear_clipboard_data(); +} + +bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref &p_event) { + if (!node) { + return false; + } + + Ref mb = p_event; + + if (mb.is_valid()) { + + if (mb->get_button_index() == BUTTON_WHEEL_UP && (mb->get_command() || mb->get_shift())) { + if (mb->is_pressed()) + floor->set_value(floor->get_value() + mb->get_factor()); + + return true; //eaten + } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && (mb->get_command() || mb->get_shift())) { + if (mb->is_pressed()) + floor->set_value(floor->get_value() - mb->get_factor()); + return true; + } + + if (mb->is_pressed()) { + + if (mb->get_button_index() == BUTTON_LEFT) { + + if (input_action == INPUT_PASTE) { + _do_paste(); + input_action = INPUT_NONE; + _update_paste_indicator(); + } else if (mb->get_shift()) { + input_action = INPUT_SELECT; + last_selection = selection; + } else if (mb->get_command()) { + input_action = INPUT_PICK; + } else { + input_action = INPUT_PAINT; + set_items.clear(); + } + } else if (mb->get_button_index() == BUTTON_RIGHT) { + if (input_action == INPUT_PASTE) { + _clear_clipboard_data(); + input_action = INPUT_NONE; + _update_paste_indicator(); + return true; + } else if (selection.active) { + _set_selection(false); + return true; + } else { + input_action = INPUT_ERASE; + set_items.clear(); + } + } else { + return false; + } + + return do_input_action(p_camera, Point2(mb->get_position().x, mb->get_position().y), true); + } else { + + if ( + (mb->get_button_index() == BUTTON_RIGHT && input_action == INPUT_ERASE) || + (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_PAINT)) { + + if (set_items.size()) { + undo_redo->create_action(TTR("GridMap Paint")); + for (List::Element *E = set_items.front(); E; E = E->next()) { + + const SetItem &si = E->get(); + undo_redo->add_do_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.new_value, si.new_orientation); + } + for (List::Element *E = set_items.back(); E; E = E->prev()) { + + const SetItem &si = E->get(); + undo_redo->add_undo_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.old_value, si.old_orientation); + } + + undo_redo->commit_action(); + } + set_items.clear(); + input_action = INPUT_NONE; + return set_items.size() > 0; + } + + if (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_SELECT) { + + undo_redo->create_action("GridMap Selection"); + undo_redo->add_do_method(this, "_set_selection", selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", last_selection.active, last_selection.begin, last_selection.end); + undo_redo->commit_action(); + } + + if (mb->get_button_index() == BUTTON_LEFT && input_action != INPUT_NONE) { + + set_items.clear(); + input_action = INPUT_NONE; + return true; + } + if (mb->get_button_index() == BUTTON_RIGHT && (input_action == INPUT_ERASE || input_action == INPUT_PASTE)) { + input_action = INPUT_NONE; + return true; + } + } + } + + Ref mm = p_event; + + if (mm.is_valid()) { + + return do_input_action(p_camera, mm->get_position(), false); + } + + Ref k = p_event; + + if (k.is_valid()) { + if (k->is_pressed()) { + if (k->get_scancode() == KEY_ESCAPE) { + + if (input_action == INPUT_PASTE) { + _clear_clipboard_data(); + input_action = INPUT_NONE; + _update_paste_indicator(); + return true; + } else if (selection.active) { + _set_selection(false); + return true; + } else { + selected_palette = -1; + mesh_library_palette->unselect_all(); + update_palette(); + _update_cursor_instance(); + return true; + } + } + + if (k->get_shift() && selection.active && input_action != INPUT_PASTE) { + + if (k->get_scancode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_PREV_LEVEL))) { + selection.click[edit_axis]--; + _validate_selection(); + return true; + } + if (k->get_scancode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_NEXT_LEVEL))) { + selection.click[edit_axis]++; + _validate_selection(); + return true; + } + } + } + } + + Ref pan_gesture = p_event; + if (pan_gesture.is_valid()) { + + if (pan_gesture->get_alt() && (pan_gesture->get_command() || pan_gesture->get_shift())) { + const real_t delta = pan_gesture->get_delta().y * 0.5; + accumulated_floor_delta += delta; + int step = 0; + if (ABS(accumulated_floor_delta) > 1.0) { + step = SGN(accumulated_floor_delta); + accumulated_floor_delta -= step; + } + if (step) { + floor->set_value(floor->get_value() + step); + } + return true; + } + } + accumulated_floor_delta = 0.0; + + return false; +} + +struct _CGMEItemSort { + + String name; + int id; + _FORCE_INLINE_ bool operator<(const _CGMEItemSort &r_it) const { return name < r_it.name; } +}; + +void GridMapEditor::_set_display_mode(int p_mode) { + if (display_mode == p_mode) { + return; + } + + if (p_mode == DISPLAY_LIST) { + mode_list->set_pressed(true); + mode_thumbnail->set_pressed(false); + } else if (p_mode == DISPLAY_THUMBNAIL) { + mode_list->set_pressed(false); + mode_thumbnail->set_pressed(true); + } + + display_mode = p_mode; + + update_palette(); +} + +void GridMapEditor::_text_changed(const String &p_text) { + update_palette(); +} + +void GridMapEditor::_sbox_input(const Ref &p_ie) { + + Ref k = p_ie; + + if (k.is_valid() && (k->get_scancode() == KEY_UP || k->get_scancode() == KEY_DOWN || k->get_scancode() == KEY_PAGEUP || k->get_scancode() == KEY_PAGEDOWN)) { + + mesh_library_palette->call("_gui_input", k); + search_box->accept_event(); + } +} + +void GridMapEditor::_icon_size_changed(float p_value) { + mesh_library_palette->set_icon_scale(p_value); + update_palette(); +} + +void GridMapEditor::update_palette() { + int selected = mesh_library_palette->get_current(); + + mesh_library_palette->clear(); + if (display_mode == DISPLAY_THUMBNAIL) { + mesh_library_palette->set_max_columns(0); + mesh_library_palette->set_icon_mode(ItemList::ICON_MODE_TOP); + } else if (display_mode == DISPLAY_LIST) { + mesh_library_palette->set_max_columns(1); + mesh_library_palette->set_icon_mode(ItemList::ICON_MODE_LEFT); + } + + float min_size = EDITOR_DEF("editors/grid_map/preview_size", 64); + min_size *= EDSCALE; + mesh_library_palette->set_fixed_icon_size(Size2(min_size, min_size)); + mesh_library_palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1.5)); + mesh_library_palette->set_max_text_lines(2); + + Ref mesh_library = node->get_mesh_library(); + + if (mesh_library.is_null()) { + last_mesh_library = NULL; + return; + } + + Vector ids; + ids = mesh_library->get_item_list(); + + List<_CGMEItemSort> il; + for (int i = 0; i < ids.size(); i++) { + + _CGMEItemSort is; + is.id = ids[i]; + is.name = mesh_library->get_item_name(ids[i]); + il.push_back(is); + } + il.sort(); + + String filter = search_box->get_text().strip_edges(); + + int item = 0; + + for (List<_CGMEItemSort>::Element *E = il.front(); E; E = E->next()) { + int id = E->get().id; + String name = mesh_library->get_item_name(id); + Ref preview = mesh_library->get_item_preview(id); + + if (name == "") { + name = "#" + itos(id); + } + + if (filter != "" && !filter.is_subsequence_ofi(name)) + continue; + + mesh_library_palette->add_item(""); + if (!preview.is_null()) { + mesh_library_palette->set_item_icon(item, preview); + mesh_library_palette->set_item_tooltip(item, name); + } + mesh_library_palette->set_item_text(item, name); + mesh_library_palette->set_item_metadata(item, id); + + item++; + } + + if (selected != -1) { + mesh_library_palette->select(selected); + } + + last_mesh_library = mesh_library.operator->(); +} + +void GridMapEditor::edit(GridMap *p_gridmap) { + + node = p_gridmap; + VS *vs = VS::get_singleton(); + + last_mouseover = Vector3(-1, -1, -1); + input_action = INPUT_NONE; + selection.active = false; + _update_selection_transform(); + _update_paste_indicator(); + + spatial_editor = Object::cast_to(editor->get_editor_plugin_screen()); + + if (!node) { + set_process(false); + for (int i = 0; i < 3; i++) { + VisualServer::get_singleton()->instance_set_visible(grid_instance[i], false); + } + + if (cursor_instance.is_valid()) { + VisualServer::get_singleton()->instance_set_visible(cursor_instance, false); + } + + return; + } + + update_palette(); + + set_process(true); + + Vector3 edited_floor = p_gridmap->has_meta("_editor_floor_") ? p_gridmap->get_meta("_editor_floor_") : Variant(); + clip_mode = p_gridmap->has_meta("_editor_clip_") ? ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()) : CLIP_DISABLED; + + for (int i = 0; i < 3; i++) { + if (vs->mesh_get_surface_count(grid[i]) > 0) + vs->mesh_remove_surface(grid[i], 0); + edit_floor[i] = edited_floor[i]; + } + + { + + //update grids + indicator_mat.instance(); + indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); + indicator_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); + indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + indicator_mat->set_albedo(Color(0.8, 0.5, 0.1)); + + Vector grid_points[3]; + Vector grid_colors[3]; + + float cell_size[3] = { p_gridmap->get_cell_size().x, p_gridmap->get_cell_size().y, p_gridmap->get_cell_size().z }; + + for (int i = 0; i < 3; i++) { + + Vector3 axis; + axis[i] = 1; + Vector3 axis_n1; + axis_n1[(i + 1) % 3] = cell_size[(i + 1) % 3]; + Vector3 axis_n2; + axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3]; + + for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) { + + for (int k = -GRID_CURSOR_SIZE; k <= GRID_CURSOR_SIZE; k++) { + + Vector3 p = axis_n1 * j + axis_n2 * k; + float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2); + + Vector3 pj = axis_n1 * (j + 1) + axis_n2 * k; + float transj = Math::pow(MAX(0, 1.0 - (Vector2(j + 1, k).length() / GRID_CURSOR_SIZE)), 2); + + Vector3 pk = axis_n1 * j + axis_n2 * (k + 1); + float transk = Math::pow(MAX(0, 1.0 - (Vector2(j, k + 1).length() / GRID_CURSOR_SIZE)), 2); + + grid_points[i].push_back(p); + grid_points[i].push_back(pk); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transk)); + + grid_points[i].push_back(p); + grid_points[i].push_back(pj); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transj)); + } + } + + Array d; + d.resize(VS::ARRAY_MAX); + d[VS::ARRAY_VERTEX] = grid_points[i]; + d[VS::ARRAY_COLOR] = grid_colors[i]; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid()); + } + } + + update_grid(); + _update_clip(); +} + +void GridMapEditor::_update_clip() { + + node->set_meta("_editor_clip_", clip_mode); + if (clip_mode == CLIP_DISABLED) + node->set_clip(false); + else + node->set_clip(true, clip_mode == CLIP_ABOVE, edit_floor[edit_axis], edit_axis); +} + +void GridMapEditor::update_grid() { + + grid_xform.origin.x -= 1; //force update in hackish way.. what do i care + + //VS *vs = VS::get_singleton(); + + grid_ofs[edit_axis] = edit_floor[edit_axis] * node->get_cell_size()[edit_axis]; + + edit_grid_xform.origin = grid_ofs; + edit_grid_xform.basis = Basis(); + + for (int i = 0; i < 3; i++) { + VisualServer::get_singleton()->instance_set_visible(grid_instance[i], i == edit_axis); + } + + updating = true; + floor->set_value(edit_floor[edit_axis]); + updating = false; +} + +void GridMapEditor::_notification(int p_what) { + + switch (p_what) { + + case NOTIFICATION_ENTER_TREE: { + mesh_library_palette->connect("item_selected", this, "_item_selected_cbk"); + for (int i = 0; i < 3; i++) { + + grid[i] = VS::get_singleton()->mesh_create(); + grid_instance[i] = VS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario()); + selection_level_instance[i] = VisualServer::get_singleton()->instance_create2(selection_level_mesh[i], get_tree()->get_root()->get_world()->get_scenario()); + } + + selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world()->get_scenario()); + paste_instance = VisualServer::get_singleton()->instance_create2(paste_mesh, get_tree()->get_root()->get_world()->get_scenario()); + + _update_selection_transform(); + _update_paste_indicator(); + } break; + + case NOTIFICATION_EXIT_TREE: { + _clear_clipboard_data(); + + for (int i = 0; i < 3; i++) { + + VS::get_singleton()->free(grid_instance[i]); + VS::get_singleton()->free(grid[i]); + grid_instance[i] = RID(); + grid[i] = RID(); + VisualServer::get_singleton()->free(selection_level_instance[i]); + } + + VisualServer::get_singleton()->free(selection_instance); + VisualServer::get_singleton()->free(paste_instance); + selection_instance = RID(); + paste_instance = RID(); + } break; + + case NOTIFICATION_PROCESS: { + if (!node) { + return; + } + + Transform xf = node->get_global_transform(); + + if (xf != grid_xform) { + for (int i = 0; i < 3; i++) { + + VS::get_singleton()->instance_set_transform(grid_instance[i], xf * edit_grid_xform); + } + grid_xform = xf; + } + Ref cgmt = node->get_mesh_library(); + if (cgmt.operator->() != last_mesh_library) + update_palette(); + + if (lock_view) { + + EditorNode *editor = Object::cast_to(get_tree()->get_root()->get_child(0)); + + Plane p; + p.normal[edit_axis] = 1.0; + p.d = edit_floor[edit_axis] * node->get_cell_size()[edit_axis]; + p = node->get_transform().xform(p); // plane to snap + + SpatialEditorPlugin *sep = Object::cast_to(editor->get_editor_plugin_screen()); + if (sep) + sep->snap_cursor_to_plane(p); + //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p); + } + } break; + + case NOTIFICATION_THEME_CHANGED: { + options->set_icon(get_icon("GridMap", "EditorIcons")); + search_box->set_right_icon(get_icon("Search", "EditorIcons")); + } break; + } +} + +void GridMapEditor::_update_cursor_instance() { + if (!node) { + return; + } + + if (cursor_instance.is_valid()) + VisualServer::get_singleton()->free(cursor_instance); + cursor_instance = RID(); + + if (selected_palette >= 0) { + + if (node && !node->get_mesh_library().is_null()) { + Ref mesh = node->get_mesh_library()->get_item_mesh(selected_palette); + if (!mesh.is_null() && mesh->get_rid().is_valid()) { + + cursor_instance = VisualServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world()->get_scenario()); + VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform); + } + } + } +} + +void GridMapEditor::_item_selected_cbk(int idx) { + selected_palette = mesh_library_palette->get_item_metadata(idx); + + _update_cursor_instance(); +} + +void GridMapEditor::_floor_changed(float p_value) { + + if (updating) + return; + + edit_floor[edit_axis] = p_value; + node->set_meta("_editor_floor_", Vector3(edit_floor[0], edit_floor[1], edit_floor[2])); + update_grid(); + _update_clip(); + _update_selection_transform(); +} + +void GridMapEditor::_floor_mouse_exited() { + floor->get_line_edit()->release_focus(); +} + +void GridMapEditor::_bind_methods() { + + ClassDB::bind_method("_text_changed", &GridMapEditor::_text_changed); + ClassDB::bind_method("_sbox_input", &GridMapEditor::_sbox_input); + ClassDB::bind_method("_icon_size_changed", &GridMapEditor::_icon_size_changed); + ClassDB::bind_method("_menu_option", &GridMapEditor::_menu_option); + ClassDB::bind_method("_configure", &GridMapEditor::_configure); + ClassDB::bind_method("_item_selected_cbk", &GridMapEditor::_item_selected_cbk); + ClassDB::bind_method("_floor_changed", &GridMapEditor::_floor_changed); + ClassDB::bind_method("_floor_mouse_exited", &GridMapEditor::_floor_mouse_exited); + ClassDB::bind_method("_set_selection", &GridMapEditor::_set_selection); + + ClassDB::bind_method(D_METHOD("_set_display_mode", "mode"), &GridMapEditor::_set_display_mode); +} + +GridMapEditor::GridMapEditor(EditorNode *p_editor) { + + input_action = INPUT_NONE; + editor = p_editor; + undo_redo = p_editor->get_undo_redo(); + + int mw = EDITOR_DEF("editors/grid_map/palette_min_width", 230); + Control *ec = memnew(Control); + ec->set_custom_minimum_size(Size2(mw, 0) * EDSCALE); + add_child(ec); + + spatial_editor_hb = memnew(HBoxContainer); + spatial_editor_hb->set_h_size_flags(SIZE_EXPAND_FILL); + spatial_editor_hb->set_alignment(BoxContainer::ALIGN_END); + SpatialEditor::get_singleton()->add_control_to_menu_panel(spatial_editor_hb); + + spin_box_label = memnew(Label); + spin_box_label->set_text(TTR("Floor:")); + spatial_editor_hb->add_child(spin_box_label); + + floor = memnew(SpinBox); + floor->set_min(-32767); + floor->set_max(32767); + floor->set_step(1); + floor->get_line_edit()->add_constant_override("minimum_spaces", 16); + + spatial_editor_hb->add_child(floor); + floor->connect("value_changed", this, "_floor_changed"); + floor->connect("mouse_exited", this, "_floor_mouse_exited"); + floor->get_line_edit()->connect("mouse_exited", this, "_floor_mouse_exited"); + + spatial_editor_hb->add_child(memnew(VSeparator)); + + options = memnew(MenuButton); + spatial_editor_hb->add_child(options); + spatial_editor_hb->hide(); + + options->set_text(TTR("Grid Map")); + options->get_popup()->add_check_item(TTR("Snap View"), MENU_OPTION_LOCK_VIEW); + options->get_popup()->add_separator(); + options->get_popup()->add_item(TTR("Previous Floor"), MENU_OPTION_PREV_LEVEL, KEY_Q); + options->get_popup()->add_item(TTR("Next Floor"), MENU_OPTION_NEXT_LEVEL, KEY_E); + options->get_popup()->add_separator(); + options->get_popup()->add_radio_check_item(TTR("Clip Disabled"), MENU_OPTION_CLIP_DISABLED); + options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true); + options->get_popup()->add_radio_check_item(TTR("Clip Above"), MENU_OPTION_CLIP_ABOVE); + options->get_popup()->add_radio_check_item(TTR("Clip Below"), MENU_OPTION_CLIP_BELOW); + options->get_popup()->add_separator(); + options->get_popup()->add_radio_check_item(TTR("Edit X Axis"), MENU_OPTION_X_AXIS, KEY_Z); + options->get_popup()->add_radio_check_item(TTR("Edit Y Axis"), MENU_OPTION_Y_AXIS, KEY_X); + options->get_popup()->add_radio_check_item(TTR("Edit Z Axis"), MENU_OPTION_Z_AXIS, KEY_C); + options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true); + options->get_popup()->add_separator(); + options->get_popup()->add_item(TTR("Cursor Rotate X"), MENU_OPTION_CURSOR_ROTATE_X, KEY_A); + options->get_popup()->add_item(TTR("Cursor Rotate Y"), MENU_OPTION_CURSOR_ROTATE_Y, KEY_S); + options->get_popup()->add_item(TTR("Cursor Rotate Z"), MENU_OPTION_CURSOR_ROTATE_Z, KEY_D); + options->get_popup()->add_item(TTR("Cursor Back Rotate X"), MENU_OPTION_CURSOR_BACK_ROTATE_X, KEY_MASK_SHIFT + KEY_A); + options->get_popup()->add_item(TTR("Cursor Back Rotate Y"), MENU_OPTION_CURSOR_BACK_ROTATE_Y, KEY_MASK_SHIFT + KEY_S); + options->get_popup()->add_item(TTR("Cursor Back Rotate Z"), MENU_OPTION_CURSOR_BACK_ROTATE_Z, KEY_MASK_SHIFT + KEY_D); + options->get_popup()->add_item(TTR("Cursor Clear Rotation"), MENU_OPTION_CURSOR_CLEAR_ROTATION, KEY_W); + options->get_popup()->add_separator(); + options->get_popup()->add_check_item("Paste Selects", MENU_OPTION_PASTE_SELECTS); + options->get_popup()->add_separator(); + options->get_popup()->add_item(TTR("Duplicate Selection"), MENU_OPTION_SELECTION_DUPLICATE, KEY_MASK_CTRL + KEY_C); + options->get_popup()->add_item(TTR("Cut Selection"), MENU_OPTION_SELECTION_CUT, KEY_MASK_CTRL + KEY_X); + options->get_popup()->add_item(TTR("Clear Selection"), MENU_OPTION_SELECTION_CLEAR, KEY_DELETE); + options->get_popup()->add_item(TTR("Fill Selection"), MENU_OPTION_SELECTION_FILL, KEY_MASK_CTRL + KEY_F); + + options->get_popup()->add_separator(); + options->get_popup()->add_item(TTR("Settings"), MENU_OPTION_GRIDMAP_SETTINGS); + + settings_dialog = memnew(ConfirmationDialog); + settings_dialog->set_title(TTR("GridMap Settings")); + add_child(settings_dialog); + settings_vbc = memnew(VBoxContainer); + settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE); + settings_dialog->add_child(settings_vbc); + + settings_pick_distance = memnew(SpinBox); + settings_pick_distance->set_max(10000.0f); + settings_pick_distance->set_min(500.0f); + settings_pick_distance->set_step(1.0f); + settings_pick_distance->set_value(EDITOR_DEF("editors/grid_map/pick_distance", 5000.0)); + settings_vbc->add_margin_child(TTR("Pick Distance:"), settings_pick_distance); + + clip_mode = CLIP_DISABLED; + options->get_popup()->connect("id_pressed", this, "_menu_option"); + + HBoxContainer *hb = memnew(HBoxContainer); + add_child(hb); + hb->set_h_size_flags(SIZE_EXPAND_FILL); + + search_box = memnew(LineEdit); + search_box->set_h_size_flags(SIZE_EXPAND_FILL); + hb->add_child(search_box); + search_box->connect("text_changed", this, "_text_changed"); + search_box->connect("gui_input", this, "_sbox_input"); + + mode_thumbnail = memnew(ToolButton); + mode_thumbnail->set_toggle_mode(true); + mode_thumbnail->set_pressed(true); + mode_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail", "EditorIcons")); + hb->add_child(mode_thumbnail); + mode_thumbnail->connect("pressed", this, "_set_display_mode", varray(DISPLAY_THUMBNAIL)); + + mode_list = memnew(ToolButton); + mode_list->set_toggle_mode(true); + mode_list->set_pressed(false); + mode_list->set_icon(p_editor->get_gui_base()->get_icon("FileList", "EditorIcons")); + hb->add_child(mode_list); + mode_list->connect("pressed", this, "_set_display_mode", varray(DISPLAY_LIST)); + + size_slider = memnew(HSlider); + size_slider->set_h_size_flags(SIZE_EXPAND_FILL); + size_slider->set_min(0.1f); + size_slider->set_max(4.0f); + size_slider->set_step(0.1f); + size_slider->set_value(1.0f); + size_slider->connect("value_changed", this, "_icon_size_changed"); + add_child(size_slider); + + EDITOR_DEF("editors/grid_map/preview_size", 64); + + display_mode = DISPLAY_THUMBNAIL; + + mesh_library_palette = memnew(ItemList); + add_child(mesh_library_palette); + mesh_library_palette->set_v_size_flags(SIZE_EXPAND_FILL); + + edit_axis = Vector3::AXIS_Y; + edit_floor[0] = -1; + edit_floor[1] = -1; + edit_floor[2] = -1; + + cursor_visible = false; + selected_palette = -1; + lock_view = false; + cursor_rot = 0; + last_mouseover = Vector3(-1, -1, -1); + + selection_mesh = VisualServer::get_singleton()->mesh_create(); + paste_mesh = VisualServer::get_singleton()->mesh_create(); + + { + //selection mesh create + + PoolVector lines; + PoolVector triangles; + PoolVector square[3]; + + for (int i = 0; i < 6; i++) { + + Vector3 face_points[4]; + + for (int j = 0; j < 4; j++) { + + float v[3]; + v[0] = 1.0; + v[1] = 1 - 2 * ((j >> 1) & 1); + v[2] = v[1] * (1 - 2 * (j & 1)); + + for (int k = 0; k < 3; k++) { + + if (i < 3) + face_points[j][(i + k) % 3] = v[k]; + else + face_points[3 - j][(i + k) % 3] = -v[k]; + } + } + + triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[1] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5)); + + triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[3] * 0.5 + Vector3(0.5, 0.5, 0.5)); + triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5)); + } + + for (int i = 0; i < 12; i++) { + + AABB base(Vector3(0, 0, 0), Vector3(1, 1, 1)); + Vector3 a, b; + base.get_edge(i, a, b); + lines.push_back(a); + lines.push_back(b); + } + + for (int i = 0; i < 3; i++) { + Vector3 points[4]; + for (int j = 0; j < 4; j++) { + + static const bool orderx[4] = { 0, 1, 1, 0 }; + static const bool ordery[4] = { 0, 0, 1, 1 }; + + Vector3 sp; + if (orderx[j]) { + sp[(i + 1) % 3] = 1.0; + } + if (ordery[j]) { + sp[(i + 2) % 3] = 1.0; + } + + points[j] = sp; + } + + for (int j = 0; j < 4; j++) { + + Vector3 ofs; + ofs[i] += 0.01; + square[i].push_back(points[j] - ofs); + square[i].push_back(points[(j + 1) % 4] - ofs); + square[i].push_back(points[j] + ofs); + square[i].push_back(points[(j + 1) % 4] + ofs); + } + } + + Array d; + d.resize(VS::ARRAY_MAX); + + inner_mat.instance(); + inner_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.2)); + //inner_mat->set_flag(SpatialMaterial::FLAG_ONTOP, true); + inner_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); + inner_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + + d[VS::ARRAY_VERTEX] = triangles; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, VS::PRIMITIVE_TRIANGLES, d); + VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 0, inner_mat->get_rid()); + + outer_mat.instance(); + outer_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.8)); + outer_mat->set_on_top_of_alpha(); + outer_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); + outer_mat->set_line_width(3.0); + outer_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + + selection_floor_mat.instance(); + selection_floor_mat->set_albedo(Color(0.80, 0.80, 1.0, 1)); + selection_floor_mat->set_on_top_of_alpha(); + selection_floor_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); + selection_floor_mat->set_line_width(3.0); + //selection_floor_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + + d[VS::ARRAY_VERTEX] = lines; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 1, outer_mat->get_rid()); + + d[VS::ARRAY_VERTEX] = triangles; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(paste_mesh, VS::PRIMITIVE_TRIANGLES, d); + VisualServer::get_singleton()->mesh_surface_set_material(paste_mesh, 0, inner_mat->get_rid()); + + d[VS::ARRAY_VERTEX] = lines; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(paste_mesh, VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(paste_mesh, 1, outer_mat->get_rid()); + + for (int i = 0; i < 3; i++) { + d[VS::ARRAY_VERTEX] = square[i]; + selection_level_mesh[i] = VS::get_singleton()->mesh_create(); + VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_level_mesh[i], VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(selection_level_mesh[i], 0, selection_floor_mat->get_rid()); + } + } + + selection.active = false; + updating = false; + accumulated_floor_delta = 0.0; +} + +GridMapEditor::~GridMapEditor() { + + _clear_clipboard_data(); + + for (int i = 0; i < 3; i++) { + + if (grid[i].is_valid()) + VisualServer::get_singleton()->free(grid[i]); + if (grid_instance[i].is_valid()) + VisualServer::get_singleton()->free(grid_instance[i]); + if (cursor_instance.is_valid()) + VisualServer::get_singleton()->free(cursor_instance); + if (selection_level_instance[i].is_valid()) + VisualServer::get_singleton()->free(selection_level_instance[i]); + if (selection_level_mesh[i].is_valid()) + VisualServer::get_singleton()->free(selection_level_mesh[i]); + } + + VisualServer::get_singleton()->free(selection_mesh); + if (selection_instance.is_valid()) + VisualServer::get_singleton()->free(selection_instance); + + VisualServer::get_singleton()->free(paste_mesh); + if (paste_instance.is_valid()) + VisualServer::get_singleton()->free(paste_instance); +} + +void GridMapEditorPlugin::_notification(int p_what) { + + if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { + + switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { + case 0: { // Left. + SpatialEditor::get_singleton()->get_palette_split()->move_child(grid_map_editor, 0); + } break; + case 1: { // Right. + SpatialEditor::get_singleton()->get_palette_split()->move_child(grid_map_editor, 1); + } break; + } + } +} + +void GridMapEditorPlugin::edit(Object *p_object) { + + grid_map_editor->edit(Object::cast_to(p_object)); +} + +bool GridMapEditorPlugin::handles(Object *p_object) const { + + return p_object->is_class("GridMap"); +} + +void GridMapEditorPlugin::make_visible(bool p_visible) { + + if (p_visible) { + grid_map_editor->show(); + grid_map_editor->spatial_editor_hb->show(); + grid_map_editor->set_process(true); + } else { + + grid_map_editor->spatial_editor_hb->hide(); + grid_map_editor->hide(); + grid_map_editor->edit(NULL); + grid_map_editor->set_process(false); + } +} + +GridMapEditorPlugin::GridMapEditorPlugin(EditorNode *p_node) { + + editor = p_node; + + EDITOR_DEF("editors/grid_map/editor_side", 1); + EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/grid_map/editor_side", PROPERTY_HINT_ENUM, "Left,Right")); + + grid_map_editor = memnew(GridMapEditor(editor)); + switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) { + case 0: { // Left. + add_control_to_container(CONTAINER_SPATIAL_EDITOR_SIDE_LEFT, grid_map_editor); + } break; + case 1: { // Right. + add_control_to_container(CONTAINER_SPATIAL_EDITOR_SIDE_RIGHT, grid_map_editor); + } break; + } + grid_map_editor->hide(); +} + +GridMapEditorPlugin::~GridMapEditorPlugin() { +} diff --git a/world/grid_map_editor_plugin.h b/world/grid_map_editor_plugin.h new file mode 100644 index 0000000..da36165 --- /dev/null +++ b/world/grid_map_editor_plugin.h @@ -0,0 +1,274 @@ +/*************************************************************************/ +/* grid_map_editor_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GRID_MAP_EDITOR_PLUGIN_H +#define GRID_MAP_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "editor/pane_drag.h" +#include "grid_map.h" +/** + @author Juan Linietsky +*/ + +class SpatialEditorPlugin; + +class GridMapEditor : public VBoxContainer { + GDCLASS(GridMapEditor, VBoxContainer); + + enum { + + GRID_CURSOR_SIZE = 50 + }; + + enum InputAction { + + INPUT_NONE, + INPUT_PAINT, + INPUT_ERASE, + INPUT_PICK, + INPUT_SELECT, + INPUT_PASTE, + }; + + enum ClipMode { + + CLIP_DISABLED, + CLIP_ABOVE, + CLIP_BELOW + }; + + enum DisplayMode { + DISPLAY_THUMBNAIL, + DISPLAY_LIST + }; + + UndoRedo *undo_redo; + InputAction input_action; + Panel *panel; + MenuButton *options; + SpinBox *floor; + double accumulated_floor_delta; + ToolButton *mode_thumbnail; + ToolButton *mode_list; + LineEdit *search_box; + HSlider *size_slider; + HBoxContainer *spatial_editor_hb; + ConfirmationDialog *settings_dialog; + VBoxContainer *settings_vbc; + SpinBox *settings_pick_distance; + Label *spin_box_label; + + struct SetItem { + + Vector3 pos; + int new_value; + int new_orientation; + int old_value; + int old_orientation; + }; + + List set_items; + + GridMap *node; + MeshLibrary *last_mesh_library; + ClipMode clip_mode; + + bool lock_view; + Transform grid_xform; + Transform edit_grid_xform; + Vector3::Axis edit_axis; + int edit_floor[3]; + Vector3 grid_ofs; + + RID grid[3]; + RID grid_instance[3]; + RID cursor_instance; + RID selection_mesh; + RID selection_instance; + RID selection_level_mesh[3]; + RID selection_level_instance[3]; + RID paste_mesh; + RID paste_instance; + + struct ClipboardItem { + int cell_item; + Vector3 grid_offset; + int orientation; + RID instance; + }; + + List clipboard_items; + + Ref indicator_mat; + Ref inner_mat; + Ref outer_mat; + Ref selection_floor_mat; + + bool updating; + + struct Selection { + + Vector3 click; + Vector3 current; + Vector3 begin; + Vector3 end; + bool active; + } selection; + Selection last_selection; + + struct PasteIndicator { + + Vector3 click; + Vector3 current; + Vector3 begin; + Vector3 end; + int orientation; + }; + PasteIndicator paste_indicator; + + bool cursor_visible; + Transform cursor_transform; + + Vector3 cursor_origin; + Vector3 last_mouseover; + + int display_mode; + int selected_palette; + int cursor_rot; + + enum Menu { + + MENU_OPTION_NEXT_LEVEL, + MENU_OPTION_PREV_LEVEL, + MENU_OPTION_LOCK_VIEW, + MENU_OPTION_CLIP_DISABLED, + MENU_OPTION_CLIP_ABOVE, + MENU_OPTION_CLIP_BELOW, + MENU_OPTION_X_AXIS, + MENU_OPTION_Y_AXIS, + MENU_OPTION_Z_AXIS, + MENU_OPTION_CURSOR_ROTATE_Y, + MENU_OPTION_CURSOR_ROTATE_X, + MENU_OPTION_CURSOR_ROTATE_Z, + MENU_OPTION_CURSOR_BACK_ROTATE_Y, + MENU_OPTION_CURSOR_BACK_ROTATE_X, + MENU_OPTION_CURSOR_BACK_ROTATE_Z, + MENU_OPTION_CURSOR_CLEAR_ROTATION, + MENU_OPTION_PASTE_SELECTS, + MENU_OPTION_SELECTION_DUPLICATE, + MENU_OPTION_SELECTION_CUT, + MENU_OPTION_SELECTION_CLEAR, + MENU_OPTION_SELECTION_FILL, + MENU_OPTION_GRIDMAP_SETTINGS + + }; + + SpatialEditorPlugin *spatial_editor; + + struct AreaDisplay { + + RID mesh; + RID instance; + }; + + void update_grid(); + void _configure(); + void _menu_option(int); + void update_palette(); + void _set_display_mode(int p_mode); + ItemList *mesh_library_palette; + void _item_selected_cbk(int idx); + void _update_cursor_transform(); + void _update_cursor_instance(); + void _update_clip(); + + void _text_changed(const String &p_text); + void _sbox_input(const Ref &p_ie); + + void _icon_size_changed(float p_value); + + void _clear_clipboard_data(); + void _set_clipboard_data(); + void _update_paste_indicator(); + void _do_paste(); + void _update_selection_transform(); + void _validate_selection(); + void _set_selection(bool p_active, const Vector3 p_begin = Vector3(), const Vector3 p_end = Vector3()); + + void _floor_changed(float p_value); + void _floor_mouse_exited(); + + void _delete_selection(); + void _fill_selection(); + + EditorNode *editor; + bool do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click); + + friend class GridMapEditorPlugin; + +protected: + void _notification(int p_what); + void _node_removed(Node *p_node); + static void _bind_methods(); + +public: + bool forward_spatial_input_event(Camera *p_camera, const Ref &p_event); + + void edit(GridMap *p_gridmap); + GridMapEditor() {} + GridMapEditor(EditorNode *p_editor); + ~GridMapEditor(); +}; + +class GridMapEditorPlugin : public EditorPlugin { + + GDCLASS(GridMapEditorPlugin, EditorPlugin); + + GridMapEditor *grid_map_editor; + EditorNode *editor; + +protected: + void _notification(int p_what); + +public: + virtual bool forward_spatial_gui_input(Camera *p_camera, const Ref &p_event) { return grid_map_editor->forward_spatial_input_event(p_camera, p_event); } + virtual String get_name() const { return "GridMap"; } + bool has_main_screen() const { return false; } + virtual void edit(Object *p_object); + virtual bool handles(Object *p_object) const; + virtual void make_visible(bool p_visible); + + GridMapEditorPlugin(EditorNode *p_node); + ~GridMapEditorPlugin(); +}; + +#endif // CUBE_GRID_MAP_EDITOR_PLUGIN_H