From dd970482c5961278034fde5fb2961e31c543e9ae Mon Sep 17 00:00:00 2001 From: jfons Date: Fri, 4 Feb 2022 16:28:18 +0100 Subject: Improvements and fixes to occluders Improvements: * Occluder3D is now an abstract type inherited by: ArrayOccluder3D, QuadOccluder3D, BoxOccluder3D, SphereOccluder3D and PolygonOccluder3D. ArrayOccluder3D serves the same purpose as the old Occluder3D (triangle mesh occluder) while the rest are primitives that can be used to manually place simple occluders. * Occluder baking can now apply simplification. The "bake_simplification_distance" property can be used to set a world-space distance as the desired maximum error, set to 0.1 by default. * Occluders can now be generated on import. Using the "occ" and "occonly" keywords (similar to "col" and "colonly" for colliders) or by enabling on MeshInstance3Ds in the scene's import window. Fixes: * Fixed saving of occluder files after bake. * Fixed a small error where occluders didn't correctly update in the rendering server. Bonus content: * Generalized "CollisionPolygon3DEditor" so it can also be used to edit Resources. Renamed it to "Polygon3DEditor" since it was already being used by other things, not just colliders. * Fixed a small bug in "EditorPropertyArray" where a call to "remove" was left after the "remove_at" rename. --- doc/classes/ArrayOccluder3D.xml | 24 + doc/classes/BoxOccluder3D.xml | 13 + doc/classes/Occluder3D.xml | 18 +- doc/classes/OccluderInstance3D.xml | 2 + doc/classes/PolygonOccluder3D.xml | 13 + doc/classes/QuadOccluder3D.xml | 13 + doc/classes/SphereOccluder3D.xml | 13 + editor/editor_node.cpp | 3 +- editor/editor_properties_array_dict.cpp | 2 +- editor/import/resource_importer_scene.cpp | 116 +++- editor/import/resource_importer_scene.h | 10 +- .../plugins/collision_polygon_3d_editor_plugin.cpp | 578 -------------------- .../plugins/collision_polygon_3d_editor_plugin.h | 116 ---- editor/plugins/node_3d_editor_gizmos.cpp | 213 ++++++++ editor/plugins/node_3d_editor_gizmos.h | 5 + .../plugins/occluder_instance_3d_editor_plugin.cpp | 8 +- editor/plugins/polygon_3d_editor_plugin.cpp | 606 +++++++++++++++++++++ editor/plugins/polygon_3d_editor_plugin.h | 119 ++++ modules/meshoptimizer/register_types.cpp | 6 + modules/raycast/raycast_occlusion_cull.cpp | 5 +- scene/3d/occluder_instance_3d.cpp | 548 ++++++++++++++++--- scene/3d/occluder_instance_3d.h | 128 ++++- scene/register_scene_types.cpp | 7 +- scene/resources/surface_tool.cpp | 79 +++ scene/resources/surface_tool.h | 12 + 25 files changed, 1833 insertions(+), 824 deletions(-) create mode 100644 doc/classes/ArrayOccluder3D.xml create mode 100644 doc/classes/BoxOccluder3D.xml create mode 100644 doc/classes/PolygonOccluder3D.xml create mode 100644 doc/classes/QuadOccluder3D.xml create mode 100644 doc/classes/SphereOccluder3D.xml delete mode 100644 editor/plugins/collision_polygon_3d_editor_plugin.cpp delete mode 100644 editor/plugins/collision_polygon_3d_editor_plugin.h create mode 100644 editor/plugins/polygon_3d_editor_plugin.cpp create mode 100644 editor/plugins/polygon_3d_editor_plugin.h diff --git a/doc/classes/ArrayOccluder3D.xml b/doc/classes/ArrayOccluder3D.xml new file mode 100644 index 0000000000..993393cf50 --- /dev/null +++ b/doc/classes/ArrayOccluder3D.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/classes/BoxOccluder3D.xml b/doc/classes/BoxOccluder3D.xml new file mode 100644 index 0000000000..8c3b597193 --- /dev/null +++ b/doc/classes/BoxOccluder3D.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/doc/classes/Occluder3D.xml b/doc/classes/Occluder3D.xml index 69fb3002e3..6c6c410bc3 100644 --- a/doc/classes/Occluder3D.xml +++ b/doc/classes/Occluder3D.xml @@ -6,10 +6,16 @@ - - - - - - + + + + + + + + + + + + diff --git a/doc/classes/OccluderInstance3D.xml b/doc/classes/OccluderInstance3D.xml index d97aa4312f..32e48f9a70 100644 --- a/doc/classes/OccluderInstance3D.xml +++ b/doc/classes/OccluderInstance3D.xml @@ -26,6 +26,8 @@ + + diff --git a/doc/classes/PolygonOccluder3D.xml b/doc/classes/PolygonOccluder3D.xml new file mode 100644 index 0000000000..a4d910c983 --- /dev/null +++ b/doc/classes/PolygonOccluder3D.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/doc/classes/QuadOccluder3D.xml b/doc/classes/QuadOccluder3D.xml new file mode 100644 index 0000000000..c1b89149f5 --- /dev/null +++ b/doc/classes/QuadOccluder3D.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/doc/classes/SphereOccluder3D.xml b/doc/classes/SphereOccluder3D.xml new file mode 100644 index 0000000000..1ffa51e170 --- /dev/null +++ b/doc/classes/SphereOccluder3D.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 3ce7fefde2..015b7d0cce 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -131,7 +131,6 @@ #include "editor/plugins/camera_3d_editor_plugin.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor/plugins/collision_polygon_2d_editor_plugin.h" -#include "editor/plugins/collision_polygon_3d_editor_plugin.h" #include "editor/plugins/collision_shape_2d_editor_plugin.h" #include "editor/plugins/cpu_particles_2d_editor_plugin.h" #include "editor/plugins/cpu_particles_3d_editor_plugin.h" @@ -162,6 +161,7 @@ #include "editor/plugins/path_3d_editor_plugin.h" #include "editor/plugins/physical_bone_3d_editor_plugin.h" #include "editor/plugins/polygon_2d_editor_plugin.h" +#include "editor/plugins/polygon_3d_editor_plugin.h" #include "editor/plugins/replication_editor_plugin.h" #include "editor/plugins/resource_preloader_editor_plugin.h" #include "editor/plugins/root_motion_editor_plugin.h" @@ -5677,6 +5677,7 @@ void EditorNode::_feature_profile_changed() { void EditorNode::_bind_methods() { GLOBAL_DEF("editor/scene/scene_naming", SCENE_NAME_CASING_SNAKE_CASE); ProjectSettings::get_singleton()->set_custom_property_info("editor/scene/scene_naming", PropertyInfo(Variant::INT, "editor/scene/scene_naming", PROPERTY_HINT_ENUM, "Auto,PascalCase,snake_case")); + ClassDB::bind_method("edit_current", &EditorNode::edit_current); ClassDB::bind_method("_editor_select", &EditorNode::_editor_select); ClassDB::bind_method("_node_renamed", &EditorNode::_node_renamed); ClassDB::bind_method("edit_node", &EditorNode::edit_node); diff --git a/editor/editor_properties_array_dict.cpp b/editor/editor_properties_array_dict.cpp index cfed86d1ae..c28c7db2cb 100644 --- a/editor/editor_properties_array_dict.cpp +++ b/editor/editor_properties_array_dict.cpp @@ -658,7 +658,7 @@ void EditorPropertyArray::_reorder_button_up() { Variant array = object->get_array(); Variant value_to_move = array.get(reorder_from_index); - array.call("remove", reorder_from_index); + array.call("remove_at", reorder_from_index); array.call("insert", reorder_to_index, value_to_move); emit_changed(get_edited_property(), array, "", false); diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp index 22a11e11cb..3eb12353b5 100644 --- a/editor/import/resource_importer_scene.cpp +++ b/editor/import/resource_importer_scene.cpp @@ -39,6 +39,7 @@ #include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/navigation_region_3d.h" +#include "scene/3d/occluder_instance_3d.h" #include "scene/3d/physics_body_3d.h" #include "scene/3d/vehicle_body_3d.h" #include "scene/animation/animation_player.h" @@ -371,10 +372,10 @@ static void _pre_gen_shape_list(Ref &mesh, Vector> &r } } -Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, List> &r_node_renames) { +Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map, Vector>> &r_collision_map, Pair *r_occluder_arrays, List> &r_node_renames) { // Children first. for (int i = 0; i < p_node->get_child_count(); i++) { - Node *r = _pre_fix_node(p_node->get_child(i), p_root, collision_map, r_node_renames); + Node *r = _pre_fix_node(p_node->get_child(i), p_root, r_collision_map, r_occluder_arrays, r_node_renames); if (!r) { i--; // Was erased. } @@ -498,14 +499,14 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map> shapes; - if (collision_map.has(mesh)) { - shapes = collision_map[mesh]; + if (r_collision_map.has(mesh)) { + shapes = r_collision_map[mesh]; } else if (_teststr(name, "colonly")) { _pre_gen_shape_list(mesh, shapes, false); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; } else if (_teststr(name, "convcolonly")) { _pre_gen_shape_list(mesh, shapes, true); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; } if (shapes.size()) { @@ -560,8 +561,8 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map> shapes; - if (collision_map.has(mesh)) { - shapes = collision_map[mesh]; + if (r_collision_map.has(mesh)) { + shapes = r_collision_map[mesh]; } else { _pre_gen_shape_list(mesh, shapes, true); } @@ -586,14 +587,14 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map> shapes; String fixed_name; - if (collision_map.has(mesh)) { - shapes = collision_map[mesh]; + if (r_collision_map.has(mesh)) { + shapes = r_collision_map[mesh]; } else if (_teststr(name, "col")) { _pre_gen_shape_list(mesh, shapes, false); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; } else if (_teststr(name, "convcol")) { _pre_gen_shape_list(mesh, shapes, true); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; } if (_teststr(name, "col")) { @@ -635,7 +636,31 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Mapreplace_by(nmi); memdelete(p_node); p_node = nmi; + } else if (_teststr(name, "occ") || _teststr(name, "occonly")) { + if (isroot) { + return p_node; + } + ImporterMeshInstance3D *mi = Object::cast_to(p_node); + if (mi) { + Ref mesh = mi->get_mesh(); + if (mesh.is_valid()) { + if (r_occluder_arrays) { + OccluderInstance3D::bake_single_node(mi, 0.0f, r_occluder_arrays->first, r_occluder_arrays->second); + } + if (_teststr(name, "occ")) { + String fixed_name = _fixstr(name, "occ"); + if (!fixed_name.is_empty()) { + if (mi->get_parent() && !mi->get_parent()->has_node(fixed_name)) { + mi->set_name(fixed_name); + } + } + } else { + memdelete(p_node); + p_node = nullptr; + } + } + } } else if (Object::cast_to(p_node)) { //last attempt, maybe collision inside the mesh data @@ -644,16 +669,21 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map mesh = mi->get_mesh(); if (!mesh.is_null()) { Vector> shapes; - if (collision_map.has(mesh)) { - shapes = collision_map[mesh]; + if (r_collision_map.has(mesh)) { + shapes = r_collision_map[mesh]; } else if (_teststr(mesh->get_name(), "col")) { _pre_gen_shape_list(mesh, shapes, false); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; mesh->set_name(_fixstr(mesh->get_name(), "col")); } else if (_teststr(mesh->get_name(), "convcol")) { _pre_gen_shape_list(mesh, shapes, true); - collision_map[mesh] = shapes; + r_collision_map[mesh] = shapes; mesh->set_name(_fixstr(mesh->get_name(), "convcol")); + } else if (_teststr(mesh->get_name(), "occ")) { + if (r_occluder_arrays) { + OccluderInstance3D::bake_single_node(mi, 0.0f, r_occluder_arrays->first, r_occluder_arrays->second); + } + mesh->set_name(_fixstr(mesh->get_name(), "occ")); } if (shapes.size()) { @@ -677,10 +707,10 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, Set> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) { +Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, Pair &r_occluder_arrays, Set> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) { // children first for (int i = 0; i < p_node->get_child_count(); i++) { - Node *r = _post_fix_node(p_node->get_child(i), p_root, collision_map, r_scanned_meshes, p_node_data, p_material_data, p_animation_data, p_animation_fps); + Node *r = _post_fix_node(p_node->get_child(i), p_root, collision_map, r_occluder_arrays, r_scanned_meshes, p_node_data, p_material_data, p_animation_data, p_animation_fps); if (!r) { i--; //was erased } @@ -883,6 +913,32 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map(p_node)) { + ImporterMeshInstance3D *mi = Object::cast_to(p_node); + + Ref m = mi->get_mesh(); + + if (m.is_valid()) { + if (node_settings.has("generate/occluder")) { + int occluder_mode = node_settings["generate/occluder"]; + + if (occluder_mode != OCCLUDER_DISABLED) { + float simplification_dist = 0.0f; + if (node_settings.has("occluder/simplification_distance")) { + simplification_dist = node_settings["occluder/simplification_distance"]; + } + + OccluderInstance3D::bake_single_node(mi, simplification_dist, r_occluder_arrays.first, r_occluder_arrays.second); + + if (occluder_mode == OCCLUDER_OCCLUDER_ONLY) { + memdelete(p_node); + p_node = nullptr; + } + } + } + } + } + if (Object::cast_to(p_node)) { AnimationPlayer *ap = Object::cast_to(p_node); @@ -1255,6 +1311,9 @@ void ResourceImporterScene::get_internal_import_options(InternalImportCategory p r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "primitive/radius", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1.0)); r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3())); r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3())); + + r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/occluder", PROPERTY_HINT_ENUM, "Disabled,Mesh + Occluder,Occluder Only", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0)); + r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "occluder/simplification_distance", PROPERTY_HINT_RANGE, "0.0,2.0,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0.1f)); } break; case INTERNAL_IMPORT_CATEGORY_MESH: { r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false)); @@ -1376,6 +1435,11 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor (physics_shape == SHAPE_TYPE_CYLINDER || physics_shape == SHAPE_TYPE_CAPSULE); } + + if (p_option == "occluder/simplification_distance") { + // Show only if occluder generation is enabled + return p_options.has("generate/occluder") && p_options["generate/occluder"].operator signed int() != OCCLUDER_DISABLED; + } } break; case INTERNAL_IMPORT_CATEGORY_MESH: { if (p_option == "save_to_file/path" || p_option == "save_to_file/make_streamable") { @@ -1869,7 +1933,7 @@ Node *ResourceImporterScene::pre_import(const String &p_source_file) { Map, Vector>> collision_map; List> node_renames; - _pre_fix_node(scene, scene, collision_map, node_renames); + _pre_fix_node(scene, scene, collision_map, nullptr, node_renames); return scene; } @@ -1944,15 +2008,16 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p Set> scanned_meshes; Map, Vector>> collision_map; + Pair occluder_arrays; List> node_renames; - _pre_fix_node(scene, scene, collision_map, node_renames); + _pre_fix_node(scene, scene, collision_map, &occluder_arrays, node_renames); for (int i = 0; i < post_importer_plugins.size(); i++) { post_importer_plugins.write[i]->pre_process(scene, p_options); } - _post_fix_node(scene, scene, collision_map, scanned_meshes, node_data, material_data, animation_data, fps); + _post_fix_node(scene, scene, collision_map, occluder_arrays, scanned_meshes, node_data, material_data, animation_data, fps); String root_type = p_options["nodes/root_type"]; root_type = root_type.split(" ")[0]; // full root_type is "ClassName (filename.gd)" for a script global class. @@ -1989,6 +2054,15 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p scene->set_name(p_save_path.get_file().get_basename()); } + if (!occluder_arrays.first.is_empty() && !occluder_arrays.second.is_empty()) { + Ref occ = memnew(ArrayOccluder3D); + occ->set_arrays(occluder_arrays.first, occluder_arrays.second); + OccluderInstance3D *occluder_instance = memnew(OccluderInstance3D); + occluder_instance->set_occluder(occ); + scene->add_child(occluder_instance, true); + occluder_instance->set_owner(scene); + } + bool gen_lods = bool(p_options["meshes/generate_lods"]); bool create_shadow_meshes = bool(p_options["meshes/create_shadow_meshes"]); int light_bake_mode = p_options["meshes/light_baking"]; diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h index 04fcc4268b..a819be682d 100644 --- a/editor/import/resource_importer_scene.h +++ b/editor/import/resource_importer_scene.h @@ -178,6 +178,12 @@ class ResourceImporterScene : public ResourceImporter { NAVMESH_NAVMESH_ONLY, }; + enum OccluderMode { + OCCLUDER_DISABLED, + OCCLUDER_MESH_AND_OCCLUDER, + OCCLUDER_OCCLUDER_ONLY, + }; + enum MeshOverride { MESH_OVERRIDE_DEFAULT, MESH_OVERRIDE_ENABLE, @@ -261,8 +267,8 @@ public: // Import scenes *after* everything else (such as textures). virtual int get_import_order() const override { return ResourceImporter::IMPORT_ORDER_SCENE; } - Node *_pre_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, List> &r_node_renames); - Node *_post_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, Set> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps); + Node *_pre_fix_node(Node *p_node, Node *p_root, Map, Vector>> &r_collision_map, Pair *r_occluder_arrays, List> &r_node_renames); + Node *_post_fix_node(Node *p_node, Node *p_root, Map, Vector>> &collision_map, Pair &r_occluder_arrays, Set> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps); Ref _save_animation_to_file(Ref anim, bool p_save_to_file, String p_save_to_path, bool p_keep_custom_tracks); void _create_clips(AnimationPlayer *anim, const Array &p_clips, bool p_bake_all); diff --git a/editor/plugins/collision_polygon_3d_editor_plugin.cpp b/editor/plugins/collision_polygon_3d_editor_plugin.cpp deleted file mode 100644 index 52651ae380..0000000000 --- a/editor/plugins/collision_polygon_3d_editor_plugin.cpp +++ /dev/null @@ -1,578 +0,0 @@ -/*************************************************************************/ -/* collision_polygon_3d_editor_plugin.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 "collision_polygon_3d_editor_plugin.h" - -#include "canvas_item_editor_plugin.h" -#include "core/input/input.h" -#include "core/io/file_access.h" -#include "core/math/geometry_2d.h" -#include "core/os/keyboard.h" -#include "editor/editor_settings.h" -#include "node_3d_editor_plugin.h" -#include "scene/3d/camera_3d.h" - -void CollisionPolygon3DEditor::_notification(int p_what) { - switch (p_what) { - case NOTIFICATION_READY: { - button_create->set_icon(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons"))); - button_edit->set_icon(get_theme_icon(SNAME("MovePoint"), SNAME("EditorIcons"))); - button_edit->set_pressed(true); - get_tree()->connect("node_removed", callable_mp(this, &CollisionPolygon3DEditor::_node_removed)); - - } break; - case NOTIFICATION_PROCESS: { - if (!node) { - return; - } - - if (_get_depth() != prev_depth) { - _polygon_draw(); - prev_depth = _get_depth(); - } - - } break; - } -} - -void CollisionPolygon3DEditor::_node_removed(Node *p_node) { - if (p_node == node) { - node = nullptr; - if (imgeom->get_parent() == p_node) { - p_node->remove_child(imgeom); - } - hide(); - set_process(false); - } -} - -void CollisionPolygon3DEditor::_menu_option(int p_option) { - switch (p_option) { - case MODE_CREATE: { - mode = MODE_CREATE; - button_create->set_pressed(true); - button_edit->set_pressed(false); - } break; - case MODE_EDIT: { - mode = MODE_EDIT; - button_create->set_pressed(false); - button_edit->set_pressed(true); - } break; - } -} - -void CollisionPolygon3DEditor::_wip_close() { - undo_redo->create_action(TTR("Create Polygon3D")); - undo_redo->add_undo_method(node, "set_polygon", node->call("get_polygon")); - undo_redo->add_do_method(node, "set_polygon", wip); - undo_redo->add_do_method(this, "_polygon_draw"); - undo_redo->add_undo_method(this, "_polygon_draw"); - wip.clear(); - wip_active = false; - mode = MODE_EDIT; - button_edit->set_pressed(true); - button_create->set_pressed(false); - edited_point = -1; - undo_redo->commit_action(); -} - -EditorPlugin::AfterGUIInput CollisionPolygon3DEditor::forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event) { - if (!node) { - return EditorPlugin::AFTER_GUI_INPUT_PASS; - } - - Transform3D gt = node->get_global_transform(); - Transform3D gi = gt.affine_inverse(); - float depth = _get_depth() * 0.5; - Vector3 n = gt.basis.get_axis(2).normalized(); - Plane p(n, gt.origin + n * depth); - - Ref mb = p_event; - - if (mb.is_valid()) { - Vector2 gpoint = mb->get_position(); - Vector3 ray_from = p_camera->project_ray_origin(gpoint); - Vector3 ray_dir = p_camera->project_ray_normal(gpoint); - - Vector3 spoint; - - if (!p.intersects_ray(ray_from, ray_dir, &spoint)) { - return EditorPlugin::AFTER_GUI_INPUT_PASS; - } - - spoint = gi.xform(spoint); - - Vector2 cpoint(spoint.x, spoint.y); - - //DO NOT snap here, it's confusing in 3D for adding points. - //Let the snap happen when the point is being moved, instead. - //cpoint = CanvasItemEditor::get_singleton()->snap_point(cpoint); - - Vector poly = node->call("get_polygon"); - - //first check if a point is to be added (segment split) - real_t grab_threshold = EDITOR_GET("editors/polygon_editor/point_grab_radius"); - - switch (mode) { - case MODE_CREATE: { - if (mb->get_button_index() == MouseButton::LEFT && mb->is_pressed()) { - if (!wip_active) { - wip.clear(); - wip.push_back(cpoint); - wip_active = true; - edited_point_pos = cpoint; - snap_ignore = false; - _polygon_draw(); - edited_point = 1; - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } else { - if (wip.size() > 1 && p_camera->unproject_position(gt.xform(Vector3(wip[0].x, wip[0].y, depth))).distance_to(gpoint) < grab_threshold) { - //wip closed - _wip_close(); - - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } else { - wip.push_back(cpoint); - edited_point = wip.size(); - snap_ignore = false; - _polygon_draw(); - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - } - } else if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed() && wip_active) { - _wip_close(); - } - - } break; - - case MODE_EDIT: { - if (mb->get_button_index() == MouseButton::LEFT) { - if (mb->is_pressed()) { - if (mb->is_ctrl_pressed()) { - if (poly.size() < 3) { - undo_redo->create_action(TTR("Edit Poly")); - undo_redo->add_undo_method(node, "set_polygon", poly); - poly.push_back(cpoint); - undo_redo->add_do_method(node, "set_polygon", poly); - undo_redo->add_do_method(this, "_polygon_draw"); - undo_redo->add_undo_method(this, "_polygon_draw"); - undo_redo->commit_action(); - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - - //search edges - int closest_idx = -1; - Vector2 closest_pos; - real_t closest_dist = 1e10; - for (int i = 0; i < poly.size(); i++) { - Vector2 points[2] = { - p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))), - p_camera->unproject_position(gt.xform(Vector3(poly[(i + 1) % poly.size()].x, poly[(i + 1) % poly.size()].y, depth))) - }; - - Vector2 cp = Geometry2D::get_closest_point_to_segment(gpoint, points); - if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2) { - continue; //not valid to reuse point - } - - real_t d = cp.distance_to(gpoint); - if (d < closest_dist && d < grab_threshold) { - closest_dist = d; - closest_pos = cp; - closest_idx = i; - } - } - - if (closest_idx >= 0) { - pre_move_edit = poly; - poly.insert(closest_idx + 1, cpoint); - edited_point = closest_idx + 1; - edited_point_pos = cpoint; - node->call("set_polygon", poly); - _polygon_draw(); - snap_ignore = true; - - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - } else { - //look for points to move - - int closest_idx = -1; - Vector2 closest_pos; - real_t closest_dist = 1e10; - for (int i = 0; i < poly.size(); i++) { - Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))); - - real_t d = cp.distance_to(gpoint); - if (d < closest_dist && d < grab_threshold) { - closest_dist = d; - closest_pos = cp; - closest_idx = i; - } - } - - if (closest_idx >= 0) { - pre_move_edit = poly; - edited_point = closest_idx; - edited_point_pos = poly[closest_idx]; - _polygon_draw(); - snap_ignore = false; - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - } - } else { - snap_ignore = false; - - if (edited_point != -1) { - //apply - - ERR_FAIL_INDEX_V(edited_point, poly.size(), EditorPlugin::AFTER_GUI_INPUT_PASS); - poly.write[edited_point] = edited_point_pos; - undo_redo->create_action(TTR("Edit Poly")); - undo_redo->add_do_method(node, "set_polygon", poly); - undo_redo->add_undo_method(node, "set_polygon", pre_move_edit); - undo_redo->add_do_method(this, "_polygon_draw"); - undo_redo->add_undo_method(this, "_polygon_draw"); - undo_redo->commit_action(); - - edited_point = -1; - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - } - } - if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed() && edited_point == -1) { - int closest_idx = -1; - Vector2 closest_pos; - real_t closest_dist = 1e10; - for (int i = 0; i < poly.size(); i++) { - Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))); - - real_t d = cp.distance_to(gpoint); - if (d < closest_dist && d < grab_threshold) { - closest_dist = d; - closest_pos = cp; - closest_idx = i; - } - } - - if (closest_idx >= 0) { - undo_redo->create_action(TTR("Edit Poly (Remove Point)")); - undo_redo->add_undo_method(node, "set_polygon", poly); - poly.remove_at(closest_idx); - undo_redo->add_do_method(node, "set_polygon", poly); - undo_redo->add_do_method(this, "_polygon_draw"); - undo_redo->add_undo_method(this, "_polygon_draw"); - undo_redo->commit_action(); - return EditorPlugin::AFTER_GUI_INPUT_STOP; - } - } - - } break; - } - } - - Ref mm = p_event; - - if (mm.is_valid()) { - if (edited_point != -1 && (wip_active || (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE)) { - Vector2 gpoint = mm->get_position(); - - Vector3 ray_from = p_camera->project_ray_origin(gpoint); - Vector3 ray_dir = p_camera->project_ray_normal(gpoint); - - Vector3 spoint; - - if (!p.intersects_ray(ray_from, ray_dir, &spoint)) { - return EditorPlugin::AFTER_GUI_INPUT_PASS; - } - - spoint = gi.xform(spoint); - - Vector2 cpoint(spoint.x, spoint.y); - - if (snap_ignore && !Input::get_singleton()->is_key_pressed(Key::CTRL)) { - snap_ignore = false; - } - - if (!snap_ignore && Node3DEditor::get_singleton()->is_snap_enabled()) { - cpoint = cpoint.snapped(Vector2( - Node3DEditor::get_singleton()->get_translate_snap(), - Node3DEditor::get_singleton()->get_translate_snap())); - } - edited_point_pos = cpoint; - - _polygon_draw(); - } - } - - return EditorPlugin::AFTER_GUI_INPUT_PASS; -} - -float CollisionPolygon3DEditor::_get_depth() { - if (bool(node->call("_has_editable_3d_polygon_no_depth"))) { - return 0; - } - - return float(node->call("get_depth")); -} - -void CollisionPolygon3DEditor::_polygon_draw() { - if (!node) { - return; - } - - Vector poly; - - if (wip_active) { - poly = wip; - } else { - poly = node->call("get_polygon"); - } - - float depth = _get_depth() * 0.5; - - m->clear_surfaces(); - imesh->clear_surfaces(); - imgeom->set_material_override(line_material); - imesh->surface_begin(Mesh::PRIMITIVE_LINES); - - Rect2 rect; - - for (int i = 0; i < poly.size(); i++) { - Vector2 p, p2; - p = i == edited_point ? edited_point_pos : poly[i]; - if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point)) { - p2 = edited_point_pos; - } else { - p2 = poly[(i + 1) % poly.size()]; - } - - if (i == 0) { - rect.position = p; - } else { - rect.expand_to(p); - } - - Vector3 point = Vector3(p.x, p.y, depth); - Vector3 next_point = Vector3(p2.x, p2.y, depth); - - imesh->surface_set_color(Color(1, 0.3, 0.1, 0.8)); - imesh->surface_add_vertex(point); - imesh->surface_set_color(Color(1, 0.3, 0.1, 0.8)); - imesh->surface_add_vertex(next_point); - - //Color col=Color(1,0.3,0.1,0.8); - //vpc->draw_line(point,next_point,col,2); - //vpc->draw_texture(handle,point-handle->get_size()*0.5); - } - - rect = rect.grow(1); - - AABB r; - r.position.x = rect.position.x; - r.position.y = rect.position.y; - r.position.z = depth; - r.size.x = rect.size.x; - r.size.y = rect.size.y; - r.size.z = 0; - - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0.3, 0, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0.0, 0.3, 0)); - - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0) - Vector3(0.3, 0, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0) + Vector3(0, 0.3, 0)); - - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0) - Vector3(0, 0.3, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0) + Vector3(0.3, 0, 0)); - - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + r.size); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + r.size - Vector3(0.3, 0, 0)); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + r.size); - imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); - imesh->surface_add_vertex(r.position + r.size - Vector3(0.0, 0.3, 0)); - - imesh->surface_end(); - - if (poly.size() == 0) { - return; - } - - Array a; - a.resize(Mesh::ARRAY_MAX); - Vector va; - { - va.resize(poly.size()); - Vector3 *w = va.ptrw(); - for (int i = 0; i < poly.size(); i++) { - Vector2 p, p2; - p = i == edited_point ? edited_point_pos : poly[i]; - - Vector3 point = Vector3(p.x, p.y, depth); - w[i] = point; - } - } - a[Mesh::ARRAY_VERTEX] = va; - m->add_surface_from_arrays(Mesh::PRIMITIVE_POINTS, a); - m->surface_set_material(0, handle_material); -} - -void CollisionPolygon3DEditor::edit(Node *p_collision_polygon) { - if (p_collision_polygon) { - node = Object::cast_to(p_collision_polygon); - //Enable the pencil tool if the polygon is empty - if (Vector(node->call("get_polygon")).size() == 0) { - _menu_option(MODE_CREATE); - } - wip.clear(); - wip_active = false; - edited_point = -1; - p_collision_polygon->add_child(imgeom); - _polygon_draw(); - set_process(true); - prev_depth = -1; - - } else { - node = nullptr; - - if (imgeom->get_parent()) { - imgeom->get_parent()->remove_child(imgeom); - } - - set_process(false); - } -} - -void CollisionPolygon3DEditor::_bind_methods() { - ClassDB::bind_method(D_METHOD("_polygon_draw"), &CollisionPolygon3DEditor::_polygon_draw); -} - -CollisionPolygon3DEditor::CollisionPolygon3DEditor(EditorNode *p_editor) { - node = nullptr; - editor = p_editor; - undo_redo = EditorNode::get_undo_redo(); - - add_child(memnew(VSeparator)); - button_create = memnew(Button); - button_create->set_flat(true); - add_child(button_create); - button_create->connect("pressed", callable_mp(this, &CollisionPolygon3DEditor::_menu_option), varray(MODE_CREATE)); - button_create->set_toggle_mode(true); - - button_edit = memnew(Button); - button_edit->set_flat(true); - add_child(button_edit); - button_edit->connect("pressed", callable_mp(this, &CollisionPolygon3DEditor::_menu_option), varray(MODE_EDIT)); - button_edit->set_toggle_mode(true); - - mode = MODE_EDIT; - wip_active = false; - imgeom = memnew(MeshInstance3D); - imesh.instantiate(); - imgeom->set_mesh(imesh); - imgeom->set_transform(Transform3D(Basis(), Vector3(0, 0, 0.00001))); - - line_material = Ref(memnew(StandardMaterial3D)); - line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); - line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); - line_material->set_albedo(Color(1, 1, 1)); - - handle_material = Ref(memnew(StandardMaterial3D)); - handle_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); - handle_material->set_flag(StandardMaterial3D::FLAG_USE_POINT_SIZE, true); - handle_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - handle_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - handle_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); - Ref handle = editor->get_gui_base()->get_theme_icon(SNAME("Editor3DHandle"), SNAME("EditorIcons")); - handle_material->set_point_size(handle->get_width()); - handle_material->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, handle); - - pointsm = memnew(MeshInstance3D); - imgeom->add_child(pointsm); - m.instantiate(); - pointsm->set_mesh(m); - pointsm->set_transform(Transform3D(Basis(), Vector3(0, 0, 0.00001))); - - snap_ignore = false; -} - -CollisionPolygon3DEditor::~CollisionPolygon3DEditor() { - memdelete(imgeom); -} - -void Polygon3DEditorPlugin::edit(Object *p_object) { - collision_polygon_editor->edit(Object::cast_to(p_object)); -} - -bool Polygon3DEditorPlugin::handles(Object *p_object) const { - return Object::cast_to(p_object) && bool(p_object->call("_is_editable_3d_polygon")); -} - -void Polygon3DEditorPlugin::make_visible(bool p_visible) { - if (p_visible) { - collision_polygon_editor->show(); - } else { - collision_polygon_editor->hide(); - collision_polygon_editor->edit(nullptr); - } -} - -Polygon3DEditorPlugin::Polygon3DEditorPlugin(EditorNode *p_node) { - editor = p_node; - collision_polygon_editor = memnew(CollisionPolygon3DEditor(p_node)); - Node3DEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor); - - collision_polygon_editor->hide(); -} - -Polygon3DEditorPlugin::~Polygon3DEditorPlugin() { -} diff --git a/editor/plugins/collision_polygon_3d_editor_plugin.h b/editor/plugins/collision_polygon_3d_editor_plugin.h deleted file mode 100644 index cd8c857398..0000000000 --- a/editor/plugins/collision_polygon_3d_editor_plugin.h +++ /dev/null @@ -1,116 +0,0 @@ -/*************************************************************************/ -/* collision_polygon_3d_editor_plugin.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 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 COLLISION_POLYGON_EDITOR_PLUGIN_H -#define COLLISION_POLYGON_EDITOR_PLUGIN_H - -#include "editor/editor_node.h" -#include "editor/editor_plugin.h" -#include "scene/3d/collision_polygon_3d.h" -#include "scene/3d/mesh_instance_3d.h" -#include "scene/resources/immediate_mesh.h" - -class CanvasItemEditor; - -class CollisionPolygon3DEditor : public HBoxContainer { - GDCLASS(CollisionPolygon3DEditor, HBoxContainer); - - UndoRedo *undo_redo; - enum Mode { - MODE_CREATE, - MODE_EDIT, - - }; - - Mode mode; - - Button *button_create; - Button *button_edit; - - Ref line_material; - Ref handle_material; - - EditorNode *editor; - Panel *panel; - Node3D *node; - Ref imesh; - MeshInstance3D *imgeom; - MeshInstance3D *pointsm; - Ref m; - - MenuButton *options; - - int edited_point; - Vector2 edited_point_pos; - Vector pre_move_edit; - Vector wip; - bool wip_active; - bool snap_ignore; - - float prev_depth; - - void _wip_close(); - void _polygon_draw(); - void _menu_option(int p_option); - - float _get_depth(); - -protected: - void _notification(int p_what); - void _node_removed(Node *p_node); - static void _bind_methods(); - -public: - virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event); - void edit(Node *p_collision_polygon); - CollisionPolygon3DEditor(EditorNode *p_editor); - ~CollisionPolygon3DEditor(); -}; - -class Polygon3DEditorPlugin : public EditorPlugin { - GDCLASS(Polygon3DEditorPlugin, EditorPlugin); - - CollisionPolygon3DEditor *collision_polygon_editor; - EditorNode *editor; - -public: - virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event) override { return collision_polygon_editor->forward_spatial_gui_input(p_camera, p_event); } - - virtual String get_name() const override { return "Polygon3DEditor"; } - bool has_main_screen() const override { return false; } - virtual void edit(Object *p_object) override; - virtual bool handles(Object *p_object) const override; - virtual void make_visible(bool p_visible) override; - - Polygon3DEditorPlugin(EditorNode *p_node); - ~Polygon3DEditorPlugin(); -}; - -#endif // COLLISION_POLYGON_EDITOR_PLUGIN_H diff --git a/editor/plugins/node_3d_editor_gizmos.cpp b/editor/plugins/node_3d_editor_gizmos.cpp index 88d2aee667..b4b1cf05ac 100644 --- a/editor/plugins/node_3d_editor_gizmos.cpp +++ b/editor/plugins/node_3d_editor_gizmos.cpp @@ -1889,6 +1889,7 @@ void MeshInstance3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { OccluderInstance3DGizmoPlugin::OccluderInstance3DGizmoPlugin() { create_material("line_material", EDITOR_DEF("editors/3d_gizmos/gizmo_colors/occluder", Color(0.8, 0.5, 1))); + create_handle_material("handles"); } bool OccluderInstance3DGizmoPlugin::has_gizmo(Node3D *p_spatial) { @@ -1903,6 +1904,189 @@ int OccluderInstance3DGizmoPlugin::get_priority() const { return -1; } +String OccluderInstance3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const { + const OccluderInstance3D *cs = Object::cast_to(p_gizmo->get_spatial_node()); + + Ref o = cs->get_occluder(); + if (o.is_null()) { + return ""; + } + + if (Object::cast_to(*o)) { + return "Radius"; + } + + if (Object::cast_to(*o) || Object::cast_to(*o)) { + return "Size"; + } + + return ""; +} + +Variant OccluderInstance3DGizmoPlugin::get_handle_value(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const { + OccluderInstance3D *oi = Object::cast_to(p_gizmo->get_spatial_node()); + + Ref o = oi->get_occluder(); + if (o.is_null()) { + return Variant(); + } + + if (Object::cast_to(*o)) { + Ref so = o; + return so->get_radius(); + } + + if (Object::cast_to(*o)) { + Ref bo = o; + return bo->get_size(); + } + + if (Object::cast_to(*o)) { + Ref qo = o; + return qo->get_size(); + } + + return Variant(); +} + +void OccluderInstance3DGizmoPlugin::set_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, Camera3D *p_camera, const Point2 &p_point) { + OccluderInstance3D *oi = Object::cast_to(p_gizmo->get_spatial_node()); + + Ref o = oi->get_occluder(); + if (o.is_null()) { + return; + } + + Transform3D gt = oi->get_global_transform(); + Transform3D gi = gt.affine_inverse(); + + Vector3 ray_from = p_camera->project_ray_origin(p_point); + Vector3 ray_dir = p_camera->project_ray_normal(p_point); + + Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 4096) }; + + bool snap_enabled = Node3DEditor::get_singleton()->is_snap_enabled(); + float snap = Node3DEditor::get_singleton()->get_translate_snap(); + + if (Object::cast_to(*o)) { + Ref so = o; + Vector3 ra, rb; + Geometry3D::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb); + float d = ra.x; + if (snap_enabled) { + d = Math::snapped(d, snap); + } + + if (d < 0.001) { + d = 0.001; + } + + so->set_radius(d); + } + + if (Object::cast_to(*o)) { + Vector3 axis; + axis[p_id] = 1.0; + Ref bo = o; + Vector3 ra, rb; + Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); + float d = ra[p_id]; + if (snap_enabled) { + d = Math::snapped(d, snap); + } + + if (d < 0.001) { + d = 0.001; + } + + Vector3 he = bo->get_size(); + he[p_id] = d * 2; + bo->set_size(he); + } + + if (Object::cast_to(*o)) { + Ref qo = o; + Plane p = Plane(Vector3(0.0f, 0.0f, 1.0f), 0.0f); + Vector3 intersection; + if (!p.intersects_segment(sg[0], sg[1], &intersection)) { + return; + } + + if (p_id == 2) { + Vector2 s = Vector2(intersection.x, intersection.y) * 2.0f; + if (snap_enabled) { + s = s.snapped(Vector2(snap, snap)); + } + s = s.max(Vector2(0.001, 0.001)); + qo->set_size(s); + } else { + float d = intersection[p_id]; + if (snap_enabled) { + d = Math::snapped(d, snap); + } + + if (d < 0.001) { + d = 0.001; + } + + Vector2 he = qo->get_size(); + he[p_id] = d * 2.0f; + qo->set_size(he); + } + } +} + +void OccluderInstance3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, const Variant &p_restore, bool p_cancel) { + OccluderInstance3D *oi = Object::cast_to(p_gizmo->get_spatial_node()); + + Ref o = oi->get_occluder(); + if (o.is_null()) { + return; + } + + if (Object::cast_to(*o)) { + Ref so = o; + if (p_cancel) { + so->set_radius(p_restore); + return; + } + + UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo(); + ur->create_action(TTR("Change Sphere Shape Radius")); + ur->add_do_method(so.ptr(), "set_radius", so->get_radius()); + ur->add_undo_method(so.ptr(), "set_radius", p_restore); + ur->commit_action(); + } + + if (Object::cast_to(*o)) { + Ref bo = o; + if (p_cancel) { + bo->set_size(p_restore); + return; + } + + UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo(); + ur->create_action(TTR("Change Box Shape Size")); + ur->add_do_method(bo.ptr(), "set_size", bo->get_size()); + ur->add_undo_method(bo.ptr(), "set_size", p_restore); + ur->commit_action(); + } + + if (Object::cast_to(*o)) { + Ref qo = o; + if (p_cancel) { + qo->set_size(p_restore); + return; + } + + UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo(); + ur->create_action(TTR("Change Box Shape Size")); + ur->add_do_method(qo.ptr(), "set_size", qo->get_size()); + ur->add_undo_method(qo.ptr(), "set_size", p_restore); + ur->commit_action(); + } +} + void OccluderInstance3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { OccluderInstance3D *occluder_instance = Object::cast_to(p_gizmo->get_spatial_node()); @@ -1920,6 +2104,35 @@ void OccluderInstance3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { p_gizmo->add_lines(lines, material); p_gizmo->add_collision_segments(lines); } + + Ref handles_material = get_material("handles"); + if (Object::cast_to(*o)) { + Ref so = o; + float r = so->get_radius(); + Vector handles = { Vector3(r, 0, 0) }; + p_gizmo->add_handles(handles, handles_material); + } + + if (Object::cast_to(*o)) { + Ref bo = o; + + Vector handles; + for (int i = 0; i < 3; i++) { + Vector3 ax; + ax[i] = bo->get_size()[i] / 2; + handles.push_back(ax); + } + + p_gizmo->add_handles(handles, handles_material); + } + + if (Object::cast_to(*o)) { + Ref qo = o; + Vector2 size = qo->get_size(); + Vector3 s = Vector3(size.x, size.y, 0.0f) / 2.0f; + Vector handles = { Vector3(s.x, 0.0f, 0.0f), Vector3(0.0f, s.y, 0.0f), Vector3(s.x, s.y, 0.0f) }; + p_gizmo->add_handles(handles, handles_material); + } } ///// diff --git a/editor/plugins/node_3d_editor_gizmos.h b/editor/plugins/node_3d_editor_gizmos.h index 66b3f02fcf..fa55651d26 100644 --- a/editor/plugins/node_3d_editor_gizmos.h +++ b/editor/plugins/node_3d_editor_gizmos.h @@ -300,6 +300,11 @@ public: int get_priority() const override; void redraw(EditorNode3DGizmo *p_gizmo) override; + String get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const override; + Variant get_handle_value(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary) const override; + void set_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, Camera3D *p_camera, const Point2 &p_point) override; + void commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id, bool p_secondary, const Variant &p_restore, bool p_cancel = false) override; + OccluderInstance3DGizmoPlugin(); }; diff --git a/editor/plugins/occluder_instance_3d_editor_plugin.cpp b/editor/plugins/occluder_instance_3d_editor_plugin.cpp index 2dd760275e..e7fe8da716 100644 --- a/editor/plugins/occluder_instance_3d_editor_plugin.cpp +++ b/editor/plugins/occluder_instance_3d_editor_plugin.cpp @@ -34,9 +34,9 @@ void OccluderInstance3DEditorPlugin::_bake_select_file(const String &p_file) { if (occluder_instance) { OccluderInstance3D::BakeError err; if (get_tree()->get_edited_scene_root() && get_tree()->get_edited_scene_root() == occluder_instance) { - err = occluder_instance->bake(occluder_instance, p_file); + err = occluder_instance->bake_scene(occluder_instance, p_file); } else { - err = occluder_instance->bake(occluder_instance->get_parent(), p_file); + err = occluder_instance->bake_scene(occluder_instance->get_parent(), p_file); } switch (err) { @@ -59,6 +59,10 @@ void OccluderInstance3DEditorPlugin::_bake_select_file(const String &p_file) { EditorNode::get_singleton()->show_warning(TTR("No meshes to bake.\nMake sure there is at least one MeshInstance3D node in the scene whose visual layers are part of the OccluderInstance3D's Bake Mask property.")); break; } + case OccluderInstance3D::BAKE_ERROR_CANT_SAVE: { + EditorNode::get_singleton()->show_warning(TTR("Could not save the new occluder at the specified path: ") + p_file); + break; + } default: { } } diff --git a/editor/plugins/polygon_3d_editor_plugin.cpp b/editor/plugins/polygon_3d_editor_plugin.cpp new file mode 100644 index 0000000000..4014da2441 --- /dev/null +++ b/editor/plugins/polygon_3d_editor_plugin.cpp @@ -0,0 +1,606 @@ +/*************************************************************************/ +/* polygon_3d_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 "polygon_3d_editor_plugin.h" + +#include "canvas_item_editor_plugin.h" +#include "core/core_string_names.h" +#include "core/input/input.h" +#include "core/io/file_access.h" +#include "core/math/geometry_2d.h" +#include "core/os/keyboard.h" +#include "editor/editor_settings.h" +#include "node_3d_editor_plugin.h" +#include "scene/3d/camera_3d.h" + +void Polygon3DEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_READY: { + button_create->set_icon(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons"))); + button_edit->set_icon(get_theme_icon(SNAME("MovePoint"), SNAME("EditorIcons"))); + button_edit->set_pressed(true); + get_tree()->connect("node_removed", callable_mp(this, &Polygon3DEditor::_node_removed)); + + } break; + case NOTIFICATION_PROCESS: { + if (!node) { + return; + } + + if (_get_depth() != prev_depth) { + _polygon_draw(); + prev_depth = _get_depth(); + } + + } break; + } +} + +void Polygon3DEditor::_node_removed(Node *p_node) { + if (p_node == node) { + node = nullptr; + if (imgeom->get_parent() == p_node) { + p_node->remove_child(imgeom); + } + hide(); + set_process(false); + } +} + +void Polygon3DEditor::_menu_option(int p_option) { + switch (p_option) { + case MODE_CREATE: { + mode = MODE_CREATE; + button_create->set_pressed(true); + button_edit->set_pressed(false); + } break; + case MODE_EDIT: { + mode = MODE_EDIT; + button_create->set_pressed(false); + button_edit->set_pressed(true); + } break; + } +} + +void Polygon3DEditor::_wip_close() { + Object *obj = node_resource.is_valid() ? (Object *)node_resource.ptr() : node; + ERR_FAIL_COND_MSG(!obj, "Edited object is not valid."); + undo_redo->create_action(TTR("Create Polygon3D")); + undo_redo->add_undo_method(obj, "set_polygon", obj->call("get_polygon")); + undo_redo->add_do_method(obj, "set_polygon", wip); + undo_redo->add_do_method(this, "_polygon_draw"); + undo_redo->add_undo_method(this, "_polygon_draw"); + wip.clear(); + wip_active = false; + mode = MODE_EDIT; + button_edit->set_pressed(true); + button_create->set_pressed(false); + edited_point = -1; + undo_redo->commit_action(); +} + +EditorPlugin::AfterGUIInput Polygon3DEditor::forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event) { + if (!node) { + return EditorPlugin::AFTER_GUI_INPUT_PASS; + } + + Object *obj = node_resource.is_valid() ? (Object *)node_resource.ptr() : node; + Transform3D gt = node->get_global_transform(); + Transform3D gi = gt.affine_inverse(); + float depth = _get_depth() * 0.5; + Vector3 n = gt.basis.get_axis(2).normalized(); + Plane p(n, gt.origin + n * depth); + + Ref mb = p_event; + + if (mb.is_valid()) { + Vector2 gpoint = mb->get_position(); + Vector3 ray_from = p_camera->project_ray_origin(gpoint); + Vector3 ray_dir = p_camera->project_ray_normal(gpoint); + + Vector3 spoint; + + if (!p.intersects_ray(ray_from, ray_dir, &spoint)) { + return EditorPlugin::AFTER_GUI_INPUT_PASS; + } + + spoint = gi.xform(spoint); + + Vector2 cpoint(spoint.x, spoint.y); + + //DO NOT snap here, it's confusing in 3D for adding points. + //Let the snap happen when the point is being moved, instead. + //cpoint = CanvasItemEditor::get_singleton()->snap_point(cpoint); + + PackedVector2Array poly = _get_polygon(); + + //first check if a point is to be added (segment split) + real_t grab_threshold = EDITOR_GET("editors/polygon_editor/point_grab_radius"); + + switch (mode) { + case MODE_CREATE: { + if (mb->get_button_index() == MouseButton::LEFT && mb->is_pressed()) { + if (!wip_active) { + wip.clear(); + wip.push_back(cpoint); + wip_active = true; + edited_point_pos = cpoint; + snap_ignore = false; + _polygon_draw(); + edited_point = 1; + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } else { + if (wip.size() > 1 && p_camera->unproject_position(gt.xform(Vector3(wip[0].x, wip[0].y, depth))).distance_to(gpoint) < grab_threshold) { + //wip closed + _wip_close(); + + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } else { + wip.push_back(cpoint); + edited_point = wip.size(); + snap_ignore = false; + _polygon_draw(); + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + } + } else if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed() && wip_active) { + _wip_close(); + } + + } break; + + case MODE_EDIT: { + if (mb->get_button_index() == MouseButton::LEFT) { + if (mb->is_pressed()) { + if (mb->is_ctrl_pressed()) { + if (poly.size() < 3) { + undo_redo->create_action(TTR("Edit Poly")); + undo_redo->add_undo_method(obj, "set_polygon", poly); + poly.push_back(cpoint); + undo_redo->add_do_method(obj, "set_polygon", poly); + undo_redo->add_do_method(this, "_polygon_draw"); + undo_redo->add_undo_method(this, "_polygon_draw"); + undo_redo->commit_action(); + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + + //search edges + int closest_idx = -1; + Vector2 closest_pos; + real_t closest_dist = 1e10; + for (int i = 0; i < poly.size(); i++) { + Vector2 points[2] = { + p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))), + p_camera->unproject_position(gt.xform(Vector3(poly[(i + 1) % poly.size()].x, poly[(i + 1) % poly.size()].y, depth))) + }; + + Vector2 cp = Geometry2D::get_closest_point_to_segment(gpoint, points); + if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2) { + continue; //not valid to reuse point + } + + real_t d = cp.distance_to(gpoint); + if (d < closest_dist && d < grab_threshold) { + closest_dist = d; + closest_pos = cp; + closest_idx = i; + } + } + + if (closest_idx >= 0) { + pre_move_edit = poly; + poly.insert(closest_idx + 1, cpoint); + edited_point = closest_idx + 1; + edited_point_pos = cpoint; + _set_polygon(poly); + _polygon_draw(); + snap_ignore = true; + + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + } else { + //look for points to move + + int closest_idx = -1; + Vector2 closest_pos; + real_t closest_dist = 1e10; + for (int i = 0; i < poly.size(); i++) { + Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))); + + real_t d = cp.distance_to(gpoint); + if (d < closest_dist && d < grab_threshold) { + closest_dist = d; + closest_pos = cp; + closest_idx = i; + } + } + + if (closest_idx >= 0) { + pre_move_edit = poly; + edited_point = closest_idx; + edited_point_pos = poly[closest_idx]; + _polygon_draw(); + snap_ignore = false; + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + } + } else { + snap_ignore = false; + + if (edited_point != -1) { + //apply + + ERR_FAIL_INDEX_V(edited_point, poly.size(), EditorPlugin::AFTER_GUI_INPUT_PASS); + poly.write[edited_point] = edited_point_pos; + undo_redo->create_action(TTR("Edit Poly")); + undo_redo->add_do_method(obj, "set_polygon", poly); + undo_redo->add_undo_method(obj, "set_polygon", pre_move_edit); + undo_redo->add_do_method(this, "_polygon_draw"); + undo_redo->add_undo_method(this, "_polygon_draw"); + undo_redo->commit_action(); + + edited_point = -1; + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + } + } + if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed() && edited_point == -1) { + int closest_idx = -1; + Vector2 closest_pos; + real_t closest_dist = 1e10; + for (int i = 0; i < poly.size(); i++) { + Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x, poly[i].y, depth))); + + real_t d = cp.distance_to(gpoint); + if (d < closest_dist && d < grab_threshold) { + closest_dist = d; + closest_pos = cp; + closest_idx = i; + } + } + + if (closest_idx >= 0) { + undo_redo->create_action(TTR("Edit Poly (Remove Point)")); + undo_redo->add_undo_method(obj, "set_polygon", poly); + poly.remove_at(closest_idx); + undo_redo->add_do_method(obj, "set_polygon", poly); + undo_redo->add_do_method(this, "_polygon_draw"); + undo_redo->add_undo_method(this, "_polygon_draw"); + undo_redo->commit_action(); + return EditorPlugin::AFTER_GUI_INPUT_STOP; + } + } + + } break; + } + } + + Ref mm = p_event; + + if (mm.is_valid()) { + if (edited_point != -1 && (wip_active || (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE)) { + Vector2 gpoint = mm->get_position(); + + Vector3 ray_from = p_camera->project_ray_origin(gpoint); + Vector3 ray_dir = p_camera->project_ray_normal(gpoint); + + Vector3 spoint; + + if (!p.intersects_ray(ray_from, ray_dir, &spoint)) { + return EditorPlugin::AFTER_GUI_INPUT_PASS; + } + + spoint = gi.xform(spoint); + + Vector2 cpoint(spoint.x, spoint.y); + + if (snap_ignore && !Input::get_singleton()->is_key_pressed(Key::CTRL)) { + snap_ignore = false; + } + + if (!snap_ignore && Node3DEditor::get_singleton()->is_snap_enabled()) { + cpoint = cpoint.snapped(Vector2( + Node3DEditor::get_singleton()->get_translate_snap(), + Node3DEditor::get_singleton()->get_translate_snap())); + } + edited_point_pos = cpoint; + + _polygon_draw(); + } + } + + return EditorPlugin::AFTER_GUI_INPUT_PASS; +} + +float Polygon3DEditor::_get_depth() { + Object *obj = node_resource.is_valid() ? (Object *)node_resource.ptr() : node; + ERR_FAIL_COND_V_MSG(!obj, 0.0f, "Edited object is not valid."); + + if (bool(obj->call("_has_editable_3d_polygon_no_depth"))) { + return 0.0f; + } + + return float(obj->call("get_depth")); +} + +PackedVector2Array Polygon3DEditor::_get_polygon() { + Object *obj = node_resource.is_valid() ? (Object *)node_resource.ptr() : node; + ERR_FAIL_COND_V_MSG(!obj, PackedVector2Array(), "Edited object is not valid."); + return PackedVector2Array(obj->call("get_polygon")); +} + +void Polygon3DEditor::_set_polygon(PackedVector2Array p_poly) { + Object *obj = node_resource.is_valid() ? (Object *)node_resource.ptr() : node; + ERR_FAIL_COND_MSG(!obj, "Edited object is not valid."); + obj->call("set_polygon", p_poly); +} + +void Polygon3DEditor::_polygon_draw() { + if (!node) { + return; + } + + PackedVector2Array poly; + + if (wip_active) { + poly = wip; + } else { + poly = _get_polygon(); + } + + float depth = _get_depth() * 0.5; + + m->clear_surfaces(); + imesh->clear_surfaces(); + imgeom->set_material_override(line_material); + imesh->surface_begin(Mesh::PRIMITIVE_LINES); + + Rect2 rect; + + for (int i = 0; i < poly.size(); i++) { + Vector2 p, p2; + p = i == edited_point ? edited_point_pos : poly[i]; + if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point)) { + p2 = edited_point_pos; + } else { + p2 = poly[(i + 1) % poly.size()]; + } + + if (i == 0) { + rect.position = p; + } else { + rect.expand_to(p); + } + + Vector3 point = Vector3(p.x, p.y, depth); + Vector3 next_point = Vector3(p2.x, p2.y, depth); + + imesh->surface_set_color(Color(1, 0.3, 0.1, 0.8)); + imesh->surface_add_vertex(point); + imesh->surface_set_color(Color(1, 0.3, 0.1, 0.8)); + imesh->surface_add_vertex(next_point); + + //Color col=Color(1,0.3,0.1,0.8); + //vpc->draw_line(point,next_point,col,2); + //vpc->draw_texture(handle,point-handle->get_size()*0.5); + } + + rect = rect.grow(1); + + AABB r; + r.position.x = rect.position.x; + r.position.y = rect.position.y; + r.position.z = depth; + r.size.x = rect.size.x; + r.size.y = rect.size.y; + r.size.z = 0; + + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0.3, 0, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0.0, 0.3, 0)); + + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0) - Vector3(0.3, 0, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(r.size.x, 0, 0) + Vector3(0, 0.3, 0)); + + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0) - Vector3(0, 0.3, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + Vector3(0, r.size.y, 0) + Vector3(0.3, 0, 0)); + + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + r.size); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + r.size - Vector3(0.3, 0, 0)); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + r.size); + imesh->surface_set_color(Color(0.8, 0.8, 0.8, 0.2)); + imesh->surface_add_vertex(r.position + r.size - Vector3(0.0, 0.3, 0)); + + imesh->surface_end(); + + if (poly.size() == 0) { + return; + } + + Array a; + a.resize(Mesh::ARRAY_MAX); + Vector va; + { + va.resize(poly.size()); + Vector3 *w = va.ptrw(); + for (int i = 0; i < poly.size(); i++) { + Vector2 p, p2; + p = i == edited_point ? edited_point_pos : poly[i]; + + Vector3 point = Vector3(p.x, p.y, depth); + w[i] = point; + } + } + a[Mesh::ARRAY_VERTEX] = va; + m->add_surface_from_arrays(Mesh::PRIMITIVE_POINTS, a); + m->surface_set_material(0, handle_material); +} + +void Polygon3DEditor::edit(Node *p_node) { + if (p_node) { + node = Object::cast_to(p_node); + node_resource = node->call("_get_editable_3d_polygon_resource"); + + if (node_resource.is_valid()) { + node_resource->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &Polygon3DEditor::_polygon_draw)); + } + //Enable the pencil tool if the polygon is empty + if (_get_polygon().is_empty()) { + _menu_option(MODE_CREATE); + } + wip.clear(); + wip_active = false; + edited_point = -1; + p_node->add_child(imgeom); + _polygon_draw(); + set_process(true); + prev_depth = -1; + + } else { + node = nullptr; + if (node_resource.is_valid()) { + node_resource->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &Polygon3DEditor::_polygon_draw)); + } + node_resource.unref(); + + if (imgeom->get_parent()) { + imgeom->get_parent()->remove_child(imgeom); + } + + set_process(false); + } +} + +void Polygon3DEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_polygon_draw"), &Polygon3DEditor::_polygon_draw); +} + +Polygon3DEditor::Polygon3DEditor(EditorNode *p_editor) { + node = nullptr; + editor = p_editor; + undo_redo = EditorNode::get_undo_redo(); + + add_child(memnew(VSeparator)); + button_create = memnew(Button); + button_create->set_flat(true); + add_child(button_create); + button_create->connect("pressed", callable_mp(this, &Polygon3DEditor::_menu_option), varray(MODE_CREATE)); + button_create->set_toggle_mode(true); + + button_edit = memnew(Button); + button_edit->set_flat(true); + add_child(button_edit); + button_edit->connect("pressed", callable_mp(this, &Polygon3DEditor::_menu_option), varray(MODE_EDIT)); + button_edit->set_toggle_mode(true); + + mode = MODE_EDIT; + wip_active = false; + imgeom = memnew(MeshInstance3D); + imesh.instantiate(); + imgeom->set_mesh(imesh); + imgeom->set_transform(Transform3D(Basis(), Vector3(0, 0, 0.00001))); + + line_material = Ref(memnew(StandardMaterial3D)); + line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); + line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); + line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); + line_material->set_albedo(Color(1, 1, 1)); + + handle_material = Ref(memnew(StandardMaterial3D)); + handle_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); + handle_material->set_flag(StandardMaterial3D::FLAG_USE_POINT_SIZE, true); + handle_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); + handle_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + handle_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); + Ref handle = editor->get_gui_base()->get_theme_icon(SNAME("Editor3DHandle"), SNAME("EditorIcons")); + handle_material->set_point_size(handle->get_width()); + handle_material->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, handle); + + pointsm = memnew(MeshInstance3D); + imgeom->add_child(pointsm); + m.instantiate(); + pointsm->set_mesh(m); + pointsm->set_transform(Transform3D(Basis(), Vector3(0, 0, 0.00001))); + + snap_ignore = false; +} + +Polygon3DEditor::~Polygon3DEditor() { + memdelete(imgeom); +} + +void Polygon3DEditorPlugin::edit(Object *p_object) { + polygon_editor->edit(Object::cast_to(p_object)); +} + +bool Polygon3DEditorPlugin::handles(Object *p_object) const { + return Object::cast_to(p_object) && bool(p_object->call("_is_editable_3d_polygon")); +} + +void Polygon3DEditorPlugin::make_visible(bool p_visible) { + if (p_visible) { + polygon_editor->show(); + } else { + polygon_editor->hide(); + polygon_editor->edit(nullptr); + } +} + +Polygon3DEditorPlugin::Polygon3DEditorPlugin(EditorNode *p_node) { + editor = p_node; + polygon_editor = memnew(Polygon3DEditor(p_node)); + Node3DEditor::get_singleton()->add_control_to_menu_panel(polygon_editor); + + polygon_editor->hide(); +} + +Polygon3DEditorPlugin::~Polygon3DEditorPlugin() { +} diff --git a/editor/plugins/polygon_3d_editor_plugin.h b/editor/plugins/polygon_3d_editor_plugin.h new file mode 100644 index 0000000000..6b0370541e --- /dev/null +++ b/editor/plugins/polygon_3d_editor_plugin.h @@ -0,0 +1,119 @@ +/*************************************************************************/ +/* polygon_3d_editor_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 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 POLYGON_3D_EDITOR_PLUGIN_H +#define POLYGON_3D_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "scene/3d/collision_polygon_3d.h" +#include "scene/3d/mesh_instance_3d.h" +#include "scene/resources/immediate_mesh.h" + +class CanvasItemEditor; + +class Polygon3DEditor : public HBoxContainer { + GDCLASS(Polygon3DEditor, HBoxContainer); + + UndoRedo *undo_redo; + enum Mode { + MODE_CREATE, + MODE_EDIT, + + }; + + Mode mode; + + Button *button_create; + Button *button_edit; + + Ref line_material; + Ref handle_material; + + EditorNode *editor; + Panel *panel; + Node3D *node; + Ref node_resource; + Ref imesh; + MeshInstance3D *imgeom; + MeshInstance3D *pointsm; + Ref m; + + MenuButton *options; + + int edited_point; + Vector2 edited_point_pos; + PackedVector2Array pre_move_edit; + PackedVector2Array wip; + bool wip_active; + bool snap_ignore; + + float prev_depth; + + void _wip_close(); + void _polygon_draw(); + void _menu_option(int p_option); + + float _get_depth(); + PackedVector2Array _get_polygon(); + void _set_polygon(PackedVector2Array p_poly); + +protected: + void _notification(int p_what); + void _node_removed(Node *p_node); + static void _bind_methods(); + +public: + virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event); + void edit(Node *p_node); + Polygon3DEditor(EditorNode *p_editor); + ~Polygon3DEditor(); +}; + +class Polygon3DEditorPlugin : public EditorPlugin { + GDCLASS(Polygon3DEditorPlugin, EditorPlugin); + + Polygon3DEditor *polygon_editor; + EditorNode *editor; + +public: + virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref &p_event) override { return polygon_editor->forward_spatial_gui_input(p_camera, p_event); } + + virtual String get_name() const override { return "Polygon3DEditor"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + + Polygon3DEditorPlugin(EditorNode *p_node); + ~Polygon3DEditorPlugin(); +}; + +#endif // POLYGON_3D_EDITOR_PLUGIN_H diff --git a/modules/meshoptimizer/register_types.cpp b/modules/meshoptimizer/register_types.cpp index 57a1b697be..597c12ed23 100644 --- a/modules/meshoptimizer/register_types.cpp +++ b/modules/meshoptimizer/register_types.cpp @@ -38,6 +38,9 @@ void register_meshoptimizer_types() { SurfaceTool::simplify_with_attrib_func = meshopt_simplifyWithAttributes; SurfaceTool::simplify_scale_func = meshopt_simplifyScale; SurfaceTool::simplify_sloppy_func = meshopt_simplifySloppy; + SurfaceTool::generate_remap_func = meshopt_generateVertexRemap; + SurfaceTool::remap_vertex_func = meshopt_remapVertexBuffer; + SurfaceTool::remap_index_func = meshopt_remapIndexBuffer; } void unregister_meshoptimizer_types() { @@ -45,4 +48,7 @@ void unregister_meshoptimizer_types() { SurfaceTool::simplify_func = nullptr; SurfaceTool::simplify_scale_func = nullptr; SurfaceTool::simplify_sloppy_func = nullptr; + SurfaceTool::generate_remap_func = nullptr; + SurfaceTool::remap_vertex_func = nullptr; + SurfaceTool::remap_index_func = nullptr; } diff --git a/modules/raycast/raycast_occlusion_cull.cpp b/modules/raycast/raycast_occlusion_cull.cpp index dd5eef8b2b..2e0d17fb28 100644 --- a/modules/raycast/raycast_occlusion_cull.cpp +++ b/modules/raycast/raycast_occlusion_cull.cpp @@ -270,13 +270,14 @@ void RaycastOcclusionCull::scenario_set_instance(RID p_scenario, RID p_instance, OccluderInstance &instance = scenario.instances[p_instance]; + bool changed = false; + if (instance.removed) { instance.removed = false; scenario.removed_instances.erase(p_instance); + changed = true; // It was removed and re-added, we might have missed some changes } - bool changed = false; - if (instance.occluder != p_occluder) { Occluder *old_occluder = occluder_owner.get_or_null(instance.occluder); if (old_occluder) { diff --git a/scene/3d/occluder_instance_3d.cpp b/scene/3d/occluder_instance_3d.cpp index e0e2eae4a5..0277171922 100644 --- a/scene/3d/occluder_instance_3d.cpp +++ b/scene/3d/occluder_instance_3d.cpp @@ -30,41 +30,24 @@ #include "occluder_instance_3d.h" #include "core/core_string_names.h" +#include "core/math/geometry_2d.h" +#include "core/math/triangulate.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" +#include "scene/resources/importer_mesh.h" +#include "scene/resources/surface_tool.h" + +#ifdef TOOLS_ENABLED +#include "editor/editor_node.h" +#endif RID Occluder3D::get_rid() const { - if (!occluder.is_valid()) { - occluder = RS::get_singleton()->occluder_create(); - RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices); - } return occluder; } -void Occluder3D::set_vertices(PackedVector3Array p_vertices) { - vertices = p_vertices; - if (occluder.is_valid()) { - RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices); - } - _update_changes(); -} - -PackedVector3Array Occluder3D::get_vertices() const { - return vertices; -} - -void Occluder3D::set_indices(PackedInt32Array p_indices) { - indices = p_indices; - if (occluder.is_valid()) { - RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices); - } - _update_changes(); -} +void Occluder3D::_update() { + _update_arrays(vertices, indices); -PackedInt32Array Occluder3D::get_indices() const { - return indices; -} - -void Occluder3D::_update_changes() { aabb = AABB(); const Vector3 *ptr = vertices.ptr(); @@ -75,9 +58,18 @@ void Occluder3D::_update_changes() { debug_lines.clear(); debug_mesh.unref(); + RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices); emit_changed(); } +PackedVector3Array Occluder3D::get_vertices() const { + return vertices; +} + +PackedInt32Array Occluder3D::get_indices() const { + return indices; +} + Vector Occluder3D::get_debug_lines() const { if (!debug_lines.is_empty()) { return debug_lines; @@ -87,14 +79,18 @@ Vector Occluder3D::get_debug_lines() const { return Vector(); } + const Vector3 *vertices_ptr = vertices.ptr(); + debug_lines.resize(indices.size() / 3 * 6); + Vector3 *line_ptr = debug_lines.ptrw(); + int line_i = 0; for (int i = 0; i < indices.size() / 3; i++) { for (int j = 0; j < 3; j++) { int a = indices[i * 3 + j]; int b = indices[i * 3 + (j + 1) % 3]; ERR_FAIL_INDEX_V_MSG(a, vertices.size(), Vector(), "Occluder indices are out of range."); ERR_FAIL_INDEX_V_MSG(b, vertices.size(), Vector(), "Occluder indices are out of range."); - debug_lines.push_back(vertices[a]); - debug_lines.push_back(vertices[b]); + line_ptr[line_i++] = vertices_ptr[a]; + line_ptr[line_i++] = vertices_ptr[b]; } } return debug_lines; @@ -105,7 +101,7 @@ Ref Occluder3D::get_debug_mesh() const { return debug_mesh; } - if (indices.size() % 3 != 0) { + if (vertices.is_empty() || indices.is_empty() || indices.size() % 3 != 0) { return debug_mesh; } @@ -123,18 +119,17 @@ AABB Occluder3D::get_aabb() const { return aabb; } -void Occluder3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &Occluder3D::set_vertices); - ClassDB::bind_method(D_METHOD("get_vertices"), &Occluder3D::get_vertices); - - ClassDB::bind_method(D_METHOD("set_indices", "indices"), &Occluder3D::set_indices); - ClassDB::bind_method(D_METHOD("get_indices"), &Occluder3D::get_indices); +void Occluder3D::_notification(int p_what) { + if (p_what == NOTIFICATION_POSTINITIALIZE) { + _update(); + } +} - ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_vertices", "get_vertices"); - ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "indices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_indices", "get_indices"); +void Occluder3D::_bind_methods() { } Occluder3D::Occluder3D() { + occluder = RS::get_singleton()->occluder_create(); } Occluder3D::~Occluder3D() { @@ -142,6 +137,291 @@ Occluder3D::~Occluder3D() { RS::get_singleton()->free(occluder); } } + +///////////////////////////////////////////////// + +void ArrayOccluder3D::set_arrays(PackedVector3Array p_vertices, PackedInt32Array p_indices) { + vertices = p_vertices; + indices = p_indices; + _update(); +} + +void ArrayOccluder3D::set_vertices(PackedVector3Array p_vertices) { + vertices = p_vertices; + _update(); +} + +void ArrayOccluder3D::set_indices(PackedInt32Array p_indices) { + indices = p_indices; + _update(); +} + +void ArrayOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + r_vertices = vertices; + r_indices = indices; +} + +void ArrayOccluder3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_arrays", "vertices", "indices"), &ArrayOccluder3D::set_arrays); + + ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &ArrayOccluder3D::set_vertices); + ClassDB::bind_method(D_METHOD("get_vertices"), &ArrayOccluder3D::get_vertices); + + ClassDB::bind_method(D_METHOD("set_indices", "indices"), &ArrayOccluder3D::set_indices); + ClassDB::bind_method(D_METHOD("get_indices"), &ArrayOccluder3D::get_indices); + + ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_vertices", "get_vertices"); + ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "indices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_indices", "get_indices"); +} + +ArrayOccluder3D::ArrayOccluder3D() { +} + +ArrayOccluder3D::~ArrayOccluder3D() { +} + +///////////////////////////////////////////////// + +void QuadOccluder3D::set_size(const Vector2 &p_size) { + if (size == p_size) { + return; + } + + size = p_size.max(Vector2()); + ; + _update(); +} + +Vector2 QuadOccluder3D::get_size() const { + return size; +} + +void QuadOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + Vector2 _size = Vector2(size.x / 2.0f, size.y / 2.0f); + + r_vertices = { + Vector3(-_size.x, -_size.y, 0), + Vector3(-_size.x, _size.y, 0), + Vector3(_size.x, _size.y, 0), + Vector3(_size.x, -_size.y, 0), + }; + + r_indices = { + 0, 1, 2, + 0, 2, 3 + }; +} + +void QuadOccluder3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_size", "size"), &QuadOccluder3D::set_size); + ClassDB::bind_method(D_METHOD("get_size"), &QuadOccluder3D::get_size); + + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size"); +} + +QuadOccluder3D::QuadOccluder3D() { +} + +QuadOccluder3D::~QuadOccluder3D() { +} + +///////////////////////////////////////////////// + +void BoxOccluder3D::set_size(const Vector3 &p_size) { + if (size == p_size) { + return; + } + + size = Vector3(MAX(p_size.x, 0.0f), MAX(p_size.y, 0.0f), MAX(p_size.z, 0.0f)); + ; + _update(); +} + +Vector3 BoxOccluder3D::get_size() const { + return size; +} + +void BoxOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + Vector3 _size = Vector3(size.x / 2.0f, size.y / 2.0f, size.z / 2.0f); + + r_vertices = { + // front + Vector3(-_size.x, -_size.y, _size.z), + Vector3(_size.x, -_size.y, _size.z), + Vector3(_size.x, _size.y, _size.z), + Vector3(-_size.x, _size.y, _size.z), + // back + Vector3(-_size.x, -_size.y, -_size.z), + Vector3(_size.x, -_size.y, -_size.z), + Vector3(_size.x, _size.y, -_size.z), + Vector3(-_size.x, _size.y, -_size.z), + }; + + r_indices = { + // front + 0, 1, 2, + 2, 3, 0, + // right + 1, 5, 6, + 6, 2, 1, + // back + 7, 6, 5, + 5, 4, 7, + // left + 4, 0, 3, + 3, 7, 4, + // bottom + 4, 5, 1, + 1, 0, 4, + // top + 3, 2, 6, + 6, 7, 3 + }; +} + +void BoxOccluder3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_size", "size"), &BoxOccluder3D::set_size); + ClassDB::bind_method(D_METHOD("get_size"), &BoxOccluder3D::get_size); + + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size"), "set_size", "get_size"); +} + +BoxOccluder3D::BoxOccluder3D() { +} + +BoxOccluder3D::~BoxOccluder3D() { +} + +///////////////////////////////////////////////// + +void SphereOccluder3D::set_radius(float p_radius) { + if (radius == p_radius) { + return; + } + + radius = MAX(p_radius, 0.0f); + _update(); +} + +float SphereOccluder3D::get_radius() const { + return radius; +} + +void SphereOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + r_vertices.resize((RINGS + 2) * (RADIAL_SEGMENTS + 1)); + int vertex_i = 0; + Vector3 *vertex_ptr = r_vertices.ptrw(); + + r_indices.resize((RINGS + 1) * RADIAL_SEGMENTS * 6); + int idx_i = 0; + int *idx_ptr = r_indices.ptrw(); + + int current_row = 0; + int previous_row = 0; + int point = 0; + for (int j = 0; j <= (RINGS + 1); j++) { + float v = j / float(RINGS + 1); + float w = Math::sin(Math_PI * v); + float y = Math::cos(Math_PI * v); + for (int i = 0; i <= RADIAL_SEGMENTS; i++) { + float u = i / float(RADIAL_SEGMENTS); + + float x = Math::cos(u * Math_TAU); + float z = Math::sin(u * Math_TAU); + vertex_ptr[vertex_i++] = Vector3(x * w, y, z * w) * radius; + + if (i > 0 && j > 0) { + idx_ptr[idx_i++] = previous_row + i - 1; + idx_ptr[idx_i++] = previous_row + i; + idx_ptr[idx_i++] = current_row + i - 1; + + idx_ptr[idx_i++] = previous_row + i; + idx_ptr[idx_i++] = current_row + i; + idx_ptr[idx_i++] = current_row + i - 1; + } + + point++; + } + + previous_row = current_row; + current_row = point; + } +} + +void SphereOccluder3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &SphereOccluder3D::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &SphereOccluder3D::get_radius); + + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius"), "set_radius", "get_radius"); +} + +SphereOccluder3D::SphereOccluder3D() { +} + +SphereOccluder3D::~SphereOccluder3D() { +} + +///////////////////////////////////////////////// + +void PolygonOccluder3D::set_polygon(const Vector &p_polygon) { + polygon = p_polygon; + _update(); +} + +Vector PolygonOccluder3D::get_polygon() const { + return polygon; +} + +void PolygonOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + if (polygon.size() < 3) { + r_vertices.clear(); + r_indices.clear(); + return; + } + + Vector occluder_polygon = polygon; + if (Triangulate::get_area(occluder_polygon) > 0) { + occluder_polygon.reverse(); + } + + Vector occluder_indices = Geometry2D::triangulate_polygon(occluder_polygon); + + if (occluder_indices.size() < 3) { + r_vertices.clear(); + r_indices.clear(); + ERR_FAIL_MSG("Failed to triangulate PolygonOccluder3D. Make sure the polygon doesn't have any intersecting edges."); + } + + r_vertices.resize(occluder_polygon.size()); + Vector3 *vertex_ptr = r_vertices.ptrw(); + const Vector2 *polygon_ptr = occluder_polygon.ptr(); + for (int i = 0; i < occluder_polygon.size(); i++) { + vertex_ptr[i] = Vector3(polygon_ptr[i].x, polygon_ptr[i].y, 0.0); + } + + r_indices.resize(occluder_indices.size()); + memcpy(r_indices.ptrw(), occluder_indices.ptr(), occluder_indices.size() * sizeof(int)); +} + +bool PolygonOccluder3D::_has_editable_3d_polygon_no_depth() const { + return false; +} + +void PolygonOccluder3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &PolygonOccluder3D::set_polygon); + ClassDB::bind_method(D_METHOD("get_polygon"), &PolygonOccluder3D::get_polygon); + + ClassDB::bind_method(D_METHOD("_has_editable_3d_polygon_no_depth"), &PolygonOccluder3D::_has_editable_3d_polygon_no_depth); + + ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); +} + +PolygonOccluder3D::PolygonOccluder3D() { +} + +PolygonOccluder3D::~PolygonOccluder3D() { +} + ///////////////////////////////////////////////// AABB OccluderInstance3D::get_aabb() const { @@ -175,6 +455,13 @@ void OccluderInstance3D::set_occluder(const Ref &p_occluder) { update_gizmos(); update_configuration_warnings(); + +#ifdef TOOLS_ENABLED + // PolygonOccluder3D is edited via an editor plugin, this ensures the plugin is shown/hidden when necessary + if (Engine::get_singleton()->is_editor_hint()) { + EditorNode::get_singleton()->call_deferred(SNAME("edit_current")); + } +#endif } void OccluderInstance3D::_occluder_changed() { @@ -195,6 +482,14 @@ uint32_t OccluderInstance3D::get_bake_mask() const { return bake_mask; } +void OccluderInstance3D::set_bake_simplification_distance(float p_dist) { + bake_simplification_dist = MAX(p_dist, 0.0f); +} + +float OccluderInstance3D::get_bake_simplification_distance() const { + return bake_simplification_dist; +} + void OccluderInstance3D::set_bake_mask_value(int p_layer_number, bool p_value) { ERR_FAIL_COND_MSG(p_layer_number < 1, "Render layer number must be between 1 and 20 inclusive."); ERR_FAIL_COND_MSG(p_layer_number > 20, "Render layer number must be between 1 and 20 inclusive."); @@ -221,6 +516,47 @@ bool OccluderInstance3D::_bake_material_check(Ref p_material) { return true; } +void OccluderInstance3D::_bake_surface(const Transform3D &p_transform, Array p_surface_arrays, Ref p_material, float p_simplification_dist, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + if (!_bake_material_check(p_material)) { + return; + } + ERR_FAIL_COND_MSG(p_surface_arrays.size() != Mesh::ARRAY_MAX, "Invalid surface array."); + + PackedVector3Array vertices = p_surface_arrays[Mesh::ARRAY_VERTEX]; + PackedInt32Array indices = p_surface_arrays[Mesh::ARRAY_INDEX]; + + if (vertices.size() == 0 || indices.size() == 0) { + return; + } + + Vector3 *vertices_ptr = vertices.ptrw(); + for (int j = 0; j < vertices.size(); j++) { + vertices_ptr[j] = p_transform.xform(vertices_ptr[j]); + } + + if (!Math::is_zero_approx(p_simplification_dist) && SurfaceTool::simplify_func) { + float error_scale = SurfaceTool::simplify_scale_func((float *)vertices.ptr(), vertices.size(), sizeof(Vector3)); + float target_error = p_simplification_dist / error_scale; + float error = -1.0f; + int target_index_count = MIN(indices.size(), 36); + uint32_t index_count = SurfaceTool::simplify_func((unsigned int *)indices.ptrw(), (unsigned int *)indices.ptr(), indices.size(), (float *)vertices.ptr(), vertices.size(), sizeof(Vector3), target_index_count, target_error, &error); + indices.resize(index_count); + } + + SurfaceTool::strip_mesh_arrays(vertices, indices); + + int vertex_offset = r_vertices.size(); + r_vertices.resize(vertex_offset + vertices.size()); + memcpy(r_vertices.ptrw() + vertex_offset, vertices.ptr(), vertices.size() * sizeof(Vector3)); + + int index_offset = r_indices.size(); + r_indices.resize(index_offset + indices.size()); + int *idx_ptr = r_indices.ptrw(); + for (int j = 0; j < indices.size(); j++) { + idx_ptr[index_offset + j] = vertex_offset + indices[j]; + } +} + void OccluderInstance3D::_bake_node(Node *p_node, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { MeshInstance3D *mi = Object::cast_to(p_node); if (mi && mi->is_visible_in_tree()) { @@ -243,58 +579,76 @@ void OccluderInstance3D::_bake_node(Node *p_node, PackedVector3Array &r_vertices Transform3D global_to_local = get_global_transform().affine_inverse() * mi->get_global_transform(); for (int i = 0; i < mesh->get_surface_count(); i++) { - if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) { - continue; - } + _bake_surface(global_to_local, mesh->surface_get_arrays(i), mi->get_active_material(i), bake_simplification_dist, r_vertices, r_indices); + } + } + } - if (mi->get_surface_override_material(i).is_valid()) { - if (!_bake_material_check(mi->get_surface_override_material(i))) { - continue; - } - } else { - if (!_bake_material_check(mesh->surface_get_material(i))) { - continue; - } - } + for (int i = 0; i < p_node->get_child_count(); i++) { + Node *child = p_node->get_child(i); + if (!child->get_owner()) { + continue; // may be a helper + } - Array arrays = mesh->surface_get_arrays(i); + _bake_node(child, r_vertices, r_indices); + } +} - int vertex_offset = r_vertices.size(); - PackedVector3Array vertices = arrays[Mesh::ARRAY_VERTEX]; - r_vertices.resize(r_vertices.size() + vertices.size()); +void OccluderInstance3D::bake_single_node(const Node3D *p_node, float p_simplification_distance, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + ERR_FAIL_COND(!p_node); - Vector3 *vtx_ptr = r_vertices.ptrw(); - for (int j = 0; j < vertices.size(); j++) { - vtx_ptr[vertex_offset + j] = global_to_local.xform(vertices[j]); - } + Transform3D xform = p_node->is_inside_tree() ? p_node->get_global_transform() : p_node->get_transform(); - int index_offset = r_indices.size(); - PackedInt32Array indices = arrays[Mesh::ARRAY_INDEX]; - r_indices.resize(r_indices.size() + indices.size()); + const MeshInstance3D *mi = Object::cast_to(p_node); + if (mi) { + Ref mesh = mi->get_mesh(); + bool valid = true; - int *idx_ptr = r_indices.ptrw(); - for (int j = 0; j < indices.size(); j++) { - idx_ptr[index_offset + j] = vertex_offset + indices[j]; - } + if (mesh.is_null()) { + valid = false; + } + + if (valid && !_bake_material_check(mi->get_material_override())) { + valid = false; + } + + if (valid) { + for (int i = 0; i < mesh->get_surface_count(); i++) { + _bake_surface(xform, mesh->surface_get_arrays(i), mi->get_active_material(i), p_simplification_distance, r_vertices, r_indices); } } } - for (int i = 0; i < p_node->get_child_count(); i++) { - Node *child = p_node->get_child(i); - if (!child->get_owner()) { - continue; //maybe a helper + const ImporterMeshInstance3D *imi = Object::cast_to(p_node); + if (imi) { + Ref mesh = imi->get_mesh(); + bool valid = true; + + if (mesh.is_null()) { + valid = false; } - _bake_node(child, r_vertices, r_indices); + if (valid) { + for (int i = 0; i < mesh->get_surface_count(); i++) { + Ref material = imi->get_surface_material(i); + if (material.is_null()) { + material = mesh->get_surface_material(i); + } + _bake_surface(xform, mesh->get_surface_arrays(i), material, p_simplification_distance, r_vertices, r_indices); + } + } } } -OccluderInstance3D::BakeError OccluderInstance3D::bake(Node *p_from_node, String p_occluder_path) { +OccluderInstance3D::BakeError OccluderInstance3D::bake_scene(Node *p_from_node, String p_occluder_path) { if (p_occluder_path.is_empty()) { if (get_occluder().is_null()) { return BAKE_ERROR_NO_SAVE_PATH; } + p_occluder_path = get_occluder()->get_path(); + if (!p_occluder_path.is_resource_file()) { + return BAKE_ERROR_NO_SAVE_PATH; + } } PackedVector3Array vertices; @@ -306,16 +660,25 @@ OccluderInstance3D::BakeError OccluderInstance3D::bake(Node *p_from_node, String return BAKE_ERROR_NO_MESHES; } - Ref occ; + Ref occ; if (get_occluder().is_valid()) { occ = get_occluder(); - } else { + set_occluder(Ref()); // clear + } + + if (occ.is_null()) { occ.instantiate(); - occ->set_path(p_occluder_path); } - occ->set_vertices(vertices); - occ->set_indices(indices); + occ->set_arrays(vertices, indices); + + Error err = ResourceSaver::save(p_occluder_path, occ); + + if (err != OK) { + return BAKE_ERROR_CANT_SAVE; + } + + occ->set_path(p_occluder_path); set_occluder(occ); return BAKE_ERROR_OK; @@ -333,28 +696,49 @@ TypedArray OccluderInstance3D::get_configuration_warnings() const { } if (occluder.is_null()) { - warnings.push_back(TTR("No occluder mesh is defined in the Occluder property, so no occlusion culling will be performed using this OccluderInstance3D.\nTo resolve this, select the OccluderInstance3D then use the Bake Occluders button at the top of the 3D editor viewport.")); - } else if (occluder->get_vertices().size() < 3) { - // Using the "New Occluder" dropdown button won't result in a correct occluder, - // so warn the user about this. - warnings.push_back(TTR("The occluder mesh has less than 3 vertices, so no occlusion culling will be performed using this OccluderInstance3D.\nTo generate a proper occluder mesh, select the OccluderInstance3D then use the Bake Occluders button at the top of the 3D editor viewport.")); + warnings.push_back(TTR("No occluder mesh is defined in the Occluder property, so no occlusion culling will be performed using this OccluderInstance3D.\nTo resolve this, set the Occluder property to one of the primitive occluder types or bake the scene meshes by selecting the OccluderInstance3D and pressing the Bake Occluders button at the top of the 3D editor viewport.")); + } else { + Ref arr_occluder = occluder; + if (arr_occluder.is_valid() && arr_occluder->get_indices().size() < 3) { + // Setting a new ArrayOccluder3D from the inspector will create an empty occluder, + // so warn the user about this. + warnings.push_back(TTR("The occluder mesh has less than 3 vertices, so no occlusion culling will be performed using this OccluderInstance3D.\nTo generate a proper occluder mesh, select the OccluderInstance3D then use the Bake Occluders button at the top of the 3D editor viewport.")); + } + Ref poly_occluder = occluder; + if (poly_occluder.is_valid() && poly_occluder->get_polygon().size() < 3) { + warnings.push_back(TTR("The polygon occluder has less than 3 vertices, so no occlusion culling will be performed using this OccluderInstance3D.\nVertices can be added in the inspector or using the polygon editing tools at the top of the 3D editor viewport.")); + } } return warnings; } +bool OccluderInstance3D::_is_editable_3d_polygon() const { + return Ref(occluder).is_valid(); +} + +Ref OccluderInstance3D::_get_editable_3d_polygon_resource() const { + return occluder; +} + void OccluderInstance3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bake_mask", "mask"), &OccluderInstance3D::set_bake_mask); ClassDB::bind_method(D_METHOD("get_bake_mask"), &OccluderInstance3D::get_bake_mask); ClassDB::bind_method(D_METHOD("set_bake_mask_value", "layer_number", "value"), &OccluderInstance3D::set_bake_mask_value); ClassDB::bind_method(D_METHOD("get_bake_mask_value", "layer_number"), &OccluderInstance3D::get_bake_mask_value); + ClassDB::bind_method(D_METHOD("set_bake_simplification_distance", "simplification_distance"), &OccluderInstance3D::set_bake_simplification_distance); + ClassDB::bind_method(D_METHOD("get_bake_simplification_distance"), &OccluderInstance3D::get_bake_simplification_distance); ClassDB::bind_method(D_METHOD("set_occluder", "occluder"), &OccluderInstance3D::set_occluder); ClassDB::bind_method(D_METHOD("get_occluder"), &OccluderInstance3D::get_occluder); + ClassDB::bind_method(D_METHOD("_is_editable_3d_polygon"), &OccluderInstance3D::_is_editable_3d_polygon); + ClassDB::bind_method(D_METHOD("_get_editable_3d_polygon_resource"), &OccluderInstance3D::_get_editable_3d_polygon_resource); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "occluder", PROPERTY_HINT_RESOURCE_TYPE, "Occluder3D"), "set_occluder", "get_occluder"); ADD_GROUP("Bake", "bake_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "bake_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_bake_mask", "get_bake_mask"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bake_simplification_distance", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"), "set_bake_simplification_distance", "get_bake_simplification_distance"); } OccluderInstance3D::OccluderInstance3D() { diff --git a/scene/3d/occluder_instance_3d.h b/scene/3d/occluder_instance_3d.h index 8a8d4c9af4..669ddba775 100644 --- a/scene/3d/occluder_instance_3d.h +++ b/scene/3d/occluder_instance_3d.h @@ -37,24 +37,23 @@ class Occluder3D : public Resource { GDCLASS(Occluder3D, Resource); RES_BASE_EXTENSION("occ"); - mutable RID occluder; - mutable Ref debug_mesh; - mutable Vector debug_lines; - AABB aabb; - + RID occluder; PackedVector3Array vertices; PackedInt32Array indices; + AABB aabb; - void _update_changes(); + mutable Ref debug_mesh; + mutable Vector debug_lines; protected: + void _update(); + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) = 0; + static void _bind_methods(); + void _notification(int p_what); public: - void set_vertices(PackedVector3Array p_vertices); PackedVector3Array get_vertices() const; - - void set_indices(PackedInt32Array p_indices); PackedInt32Array get_indices() const; Vector get_debug_lines() const; @@ -63,7 +62,102 @@ public: virtual RID get_rid() const override; Occluder3D(); - ~Occluder3D(); + virtual ~Occluder3D(); +}; + +class ArrayOccluder3D : public Occluder3D { + GDCLASS(ArrayOccluder3D, Occluder3D); + + PackedVector3Array vertices; + PackedInt32Array indices; + +protected: + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override; + static void _bind_methods(); + +public: + void set_arrays(PackedVector3Array p_vertices, PackedInt32Array p_indices); + void set_vertices(PackedVector3Array p_vertices); + void set_indices(PackedInt32Array p_indices); + + ArrayOccluder3D(); + ~ArrayOccluder3D(); +}; + +class QuadOccluder3D : public Occluder3D { + GDCLASS(QuadOccluder3D, Occluder3D); + +private: + Vector2 size = Vector2(1.0f, 1.0f); + +protected: + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override; + static void _bind_methods(); + +public: + Vector2 get_size() const; + void set_size(const Vector2 &p_size); + + QuadOccluder3D(); + ~QuadOccluder3D(); +}; + +class BoxOccluder3D : public Occluder3D { + GDCLASS(BoxOccluder3D, Occluder3D); + +private: + Vector3 size = Vector3(1.0f, 1.0f, 1.0f); + +protected: + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override; + static void _bind_methods(); + +public: + Vector3 get_size() const; + void set_size(const Vector3 &p_size); + + BoxOccluder3D(); + ~BoxOccluder3D(); +}; + +class SphereOccluder3D : public Occluder3D { + GDCLASS(SphereOccluder3D, Occluder3D); + +private: + static constexpr int RINGS = 7; + static constexpr int RADIAL_SEGMENTS = 7; + float radius = 1.0f; + +protected: + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override; + static void _bind_methods(); + +public: + float get_radius() const; + void set_radius(float p_radius); + + SphereOccluder3D(); + ~SphereOccluder3D(); +}; + +class PolygonOccluder3D : public Occluder3D { + GDCLASS(PolygonOccluder3D, Occluder3D); + +private: + Vector polygon; + + bool _has_editable_3d_polygon_no_depth() const; + +protected: + virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override; + static void _bind_methods(); + +public: + void set_polygon(const Vector &p_polygon); + Vector get_polygon() const; + + PolygonOccluder3D(); + ~PolygonOccluder3D(); }; class OccluderInstance3D : public VisualInstance3D { @@ -72,12 +166,17 @@ class OccluderInstance3D : public VisualInstance3D { private: Ref occluder; uint32_t bake_mask = 0xFFFFFFFF; + float bake_simplification_dist = 0.1f; void _occluder_changed(); - bool _bake_material_check(Ref p_material); + static bool _bake_material_check(Ref p_material); + static void _bake_surface(const Transform3D &p_transform, Array p_surface_arrays, Ref p_material, float p_simplification_dist, PackedVector3Array &r_vertices, PackedInt32Array &r_indices); void _bake_node(Node *p_node, PackedVector3Array &r_vertices, PackedInt32Array &r_indices); + bool _is_editable_3d_polygon() const; + Ref _get_editable_3d_polygon_resource() const; + protected: static void _bind_methods(); @@ -88,6 +187,7 @@ public: BAKE_ERROR_OK, BAKE_ERROR_NO_SAVE_PATH, BAKE_ERROR_NO_MESHES, + BAKE_ERROR_CANT_SAVE, }; void set_occluder(const Ref &p_occluder); @@ -99,10 +199,14 @@ public: void set_bake_mask(uint32_t p_mask); uint32_t get_bake_mask() const; + void set_bake_simplification_distance(float p_dist); + float get_bake_simplification_distance() const; + void set_bake_mask_value(int p_layer_number, bool p_enable); bool get_bake_mask_value(int p_layer_number) const; - BakeError bake(Node *p_from_node, String p_occluder_path = ""); + BakeError bake_scene(Node *p_from_node, String p_occluder_path = ""); + static void bake_single_node(const Node3D *p_node, float p_simplification_distance, PackedVector3Array &r_vertices, PackedInt32Array &r_indices); OccluderInstance3D(); ~OccluderInstance3D(); diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 9ed83eb8c3..87e9bd023b 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -470,7 +470,12 @@ void register_scene_types() { GDREGISTER_CLASS(XROrigin3D); GDREGISTER_CLASS(MeshInstance3D); GDREGISTER_CLASS(OccluderInstance3D); - GDREGISTER_CLASS(Occluder3D); + GDREGISTER_VIRTUAL_CLASS(Occluder3D); + GDREGISTER_CLASS(ArrayOccluder3D); + GDREGISTER_CLASS(QuadOccluder3D); + GDREGISTER_CLASS(BoxOccluder3D); + GDREGISTER_CLASS(SphereOccluder3D); + GDREGISTER_CLASS(PolygonOccluder3D); GDREGISTER_VIRTUAL_CLASS(SpriteBase3D); GDREGISTER_CLASS(Sprite3D); GDREGISTER_CLASS(AnimatedSprite3D); diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp index 0677d9c1a8..52151ae846 100644 --- a/scene/resources/surface_tool.cpp +++ b/scene/resources/surface_tool.cpp @@ -37,6 +37,44 @@ SurfaceTool::SimplifyFunc SurfaceTool::simplify_func = nullptr; SurfaceTool::SimplifyWithAttribFunc SurfaceTool::simplify_with_attrib_func = nullptr; SurfaceTool::SimplifyScaleFunc SurfaceTool::simplify_scale_func = nullptr; SurfaceTool::SimplifySloppyFunc SurfaceTool::simplify_sloppy_func = nullptr; +SurfaceTool::GenerateRemapFunc SurfaceTool::generate_remap_func = nullptr; +SurfaceTool::RemapVertexFunc SurfaceTool::remap_vertex_func = nullptr; +SurfaceTool::RemapIndexFunc SurfaceTool::remap_index_func = nullptr; + +void SurfaceTool::strip_mesh_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) { + ERR_FAIL_COND_MSG(!generate_remap_func || !remap_vertex_func || !remap_index_func, "Meshoptimizer library is not initialized."); + + Vector remap; + remap.resize(r_vertices.size()); + uint32_t new_vertex_count = generate_remap_func(remap.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), (float *)r_vertices.ptr(), r_vertices.size(), sizeof(Vector3)); + remap_vertex_func(r_vertices.ptrw(), r_vertices.ptr(), r_vertices.size(), sizeof(Vector3), remap.ptr()); + r_vertices.resize(new_vertex_count); + remap_index_func((unsigned int *)r_indices.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), remap.ptr()); + + HashMap found_triangles; + int *idx_ptr = r_indices.ptrw(); + + int filtered_indices_count = 0; + for (int i = 0; i < r_indices.size() / 3; i++) { + const int *tri = idx_ptr + (i * 3); + + if (tri[0] == tri[1] || tri[1] == tri[2] || tri[2] == tri[0]) { + continue; + } + + if (found_triangles.has(tri)) { + continue; + } + + if (i != filtered_indices_count) { + memcpy(idx_ptr + (filtered_indices_count * 3), tri, sizeof(int) * 3); + } + + found_triangles[tri] = true; + filtered_indices_count++; + } + r_indices.resize(filtered_indices_count * 3); +} bool SurfaceTool::Vertex::operator==(const Vertex &p_vertex) const { if (vertex != p_vertex.vertex) { @@ -107,6 +145,47 @@ uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) { return h; } +uint32_t SurfaceTool::TriangleHasher::hash(const int *p_triangle) { + int t0 = p_triangle[0]; + int t1 = p_triangle[1]; + int t2 = p_triangle[2]; + + if (t0 > t1) + SWAP(t0, t1); + if (t1 > t2) + SWAP(t1, t2); + if (t0 > t1) + SWAP(t0, t1); + + return (t0 * 73856093) ^ (t1 * 19349663) ^ (t2 * 83492791); +} + +bool SurfaceTool::TriangleHasher::compare(const int *p_lhs, const int *p_rhs) { + int r0 = p_rhs[0]; + int r1 = p_rhs[1]; + int r2 = p_rhs[2]; + + if (r0 > r1) + SWAP(r0, r1); + if (r1 > r2) + SWAP(r1, r2); + if (r0 > r1) + SWAP(r0, r1); + + int l0 = p_lhs[0]; + int l1 = p_lhs[1]; + int l2 = p_lhs[2]; + + if (l0 > l1) + SWAP(l0, l1); + if (l1 > l2) + SWAP(l1, l2); + if (l0 > l1) + SWAP(l0, l1); + + return l0 == r0 && l1 == r1 && l2 == r2; +} + void SurfaceTool::begin(Mesh::PrimitiveType p_primitive) { clear(); diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.h index 9cb83e0e68..bf4332ad2a 100644 --- a/scene/resources/surface_tool.h +++ b/scene/resources/surface_tool.h @@ -84,12 +84,24 @@ public: static SimplifyScaleFunc simplify_scale_func; typedef size_t (*SimplifySloppyFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const float *vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float *out_result_error); static SimplifySloppyFunc simplify_sloppy_func; + typedef size_t (*GenerateRemapFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const void *vertices, size_t vertex_count, size_t vertex_size); + static GenerateRemapFunc generate_remap_func; + typedef void (*RemapVertexFunc)(void *destination, const void *vertices, size_t vertex_count, size_t vertex_size, const unsigned int *remap); + static RemapVertexFunc remap_vertex_func; + typedef void (*RemapIndexFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const unsigned int *remap); + static RemapIndexFunc remap_index_func; + static void strip_mesh_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices); private: struct VertexHasher { static _FORCE_INLINE_ uint32_t hash(const Vertex &p_vtx); }; + struct TriangleHasher { + static _FORCE_INLINE_ uint32_t hash(const int *p_triangle); + static _FORCE_INLINE_ bool compare(const int *p_lhs, const int *p_rhs); + }; + struct WeightSort { int index = 0; float weight = 0.0; -- cgit v1.2.3