diff options
248 files changed, 3525 insertions, 6398 deletions
diff --git a/.github/workflows/static_checks.yml b/.github/workflows/static_checks.yml index 6c9d8d30f2..d10156c04e 100644 --- a/.github/workflows/static_checks.yml +++ b/.github/workflows/static_checks.yml @@ -24,7 +24,7 @@ jobs: - name: Install dependencies run: | - sudo apt-get install -qq dos2unix recode clang-format-15 libxml2-utils python3-pip moreutils + sudo apt-get install -qq dos2unix clang-format-15 libxml2-utils python3-pip moreutils sudo update-alternatives --remove-all clang-format || true sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-15 100 sudo pip3 install black==22.3.0 pygments pytest==7.1.2 mypy==0.971 diff --git a/CHANGELOG.md b/CHANGELOG.md index f59c0e645d..de0037d5e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,11 +37,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - [New and improved IK in Skeleton2D](https://github.com/godotengine/godot/pull/40347). - New classes: SkeletonModifier2D, SkeletonModifierStack2D, SkeletonModification2DLookAt, SkeletonModification2DCCDIK, SkeletonModification2DFABRIK, SkeletonModification2DJiggle, SkeletonModification2DTwoBoneIK, PhysicalBone2D, SkeletonModification2DPhysicalBones, SkeletonModification2DStackHolder. - New `Transform2D.looking_at()` function. -- [New and improved IK in Skeleton3D](https://github.com/godotengine/godot/pull/39353). - - New classes: SkeletonModifier3D, SkeletonModifierStack3D, SkeletonModifier3DLookAt, SkeletonModification3DCCDIK, SkeletonModification3DFABRIK, SkeletonModification3DJiggle, SkeletonModification3DTwoBoneIK, SkeletonModification3DStackHolder. - - The Bone struct now includes a local_pose_override. +- [Improvements to Skeleton3D](https://github.com/godotengine/godot/pull/39353). - The Bone struct now keeps track of its children bones, if it has any. - - Added functions to Skeleton3D for getting the forward vector using the information stored in the rest pose for the bones. - New `Basis.rotate_to_align()` function. - Refactored the BoneAttachment3D node. - Removed the `process_list` functions. @@ -41,7 +41,7 @@ Official binaries for the Godot editor and the export templates can be found ### Compiling from source -[See the official docs](https://docs.godotengine.org/en/latest/development/compiling/) +[See the official docs](https://docs.godotengine.org/en/latest/contributing/development/compiling) for compilation instructions for every supported platform. ## Community and contributing diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp index 0bf7430d84..73d7d7420f 100644 --- a/core/config/project_settings.cpp +++ b/core/config/project_settings.cpp @@ -291,31 +291,26 @@ bool ProjectSettings::_set(const StringName &p_name, const Variant &p_value) { return true; } - if (!disable_feature_overrides) { + { // Feature overrides. int dot = p_name.operator String().find("."); if (dot != -1) { Vector<String> s = p_name.operator String().split("."); - bool override_valid = false; for (int i = 1; i < s.size(); i++) { String feature = s[i].strip_edges(); - if (OS::get_singleton()->has_feature(feature) || custom_features.has(feature)) { - override_valid = true; - break; + Pair<StringName, StringName> fo(feature, p_name); + + if (!feature_overrides.has(s[0])) { + feature_overrides[s[0]] = LocalVector<Pair<StringName, StringName>>(); } - } - if (override_valid) { - feature_overrides[s[0]] = p_name; + feature_overrides[s[0]].push_back(fo); } } } if (props.has(p_name)) { - if (!props[p_name].overridden) { - props[p_name].variant = p_value; - } - + props[p_name].variant = p_value; } else { props[p_name] = VariantContainer(p_value, last_order++); } @@ -340,16 +335,35 @@ bool ProjectSettings::_set(const StringName &p_name, const Variant &p_value) { bool ProjectSettings::_get(const StringName &p_name, Variant &r_ret) const { _THREAD_SAFE_METHOD_ + if (!props.has(p_name)) { + WARN_PRINT("Property not found: " + String(p_name)); + return false; + } + r_ret = props[p_name].variant; + return true; +} + +Variant ProjectSettings::get_setting_with_override(const StringName &p_name) const { + _THREAD_SAFE_METHOD_ + StringName name = p_name; - if (!disable_feature_overrides && feature_overrides.has(name)) { - name = feature_overrides[name]; + if (feature_overrides.has(name)) { + const LocalVector<Pair<StringName, StringName>> &overrides = feature_overrides[name]; + for (uint32_t i = 0; i < overrides.size(); i++) { + if (OS::get_singleton()->has_feature(overrides[i].first)) { // Custom features are checked in OS.has_feature() already. No need to check twice. + if (props.has(overrides[i].second)) { + name = overrides[i].second; + break; + } + } + } } + if (!props.has(name)) { WARN_PRINT("Property not found: " + String(name)); - return false; + return Variant(); } - r_ret = props[name].variant; - return true; + return props[name].variant; } struct _VCSort { @@ -1101,10 +1115,6 @@ const HashMap<StringName, PropertyInfo> &ProjectSettings::get_custom_property_in return custom_prop_info; } -void ProjectSettings::set_disable_feature_overrides(bool p_disable) { - disable_feature_overrides = p_disable; -} - bool ProjectSettings::is_using_datapack() const { return using_datapack; } @@ -1169,6 +1179,7 @@ void ProjectSettings::_bind_methods() { ClassDB::bind_method(D_METHOD("has_setting", "name"), &ProjectSettings::has_setting); ClassDB::bind_method(D_METHOD("set_setting", "name", "value"), &ProjectSettings::set_setting); ClassDB::bind_method(D_METHOD("get_setting", "name", "default_value"), &ProjectSettings::get_setting, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("get_setting_with_override", "name"), &ProjectSettings::get_setting_with_override); ClassDB::bind_method(D_METHOD("set_order", "name", "position"), &ProjectSettings::set_order); ClassDB::bind_method(D_METHOD("get_order", "name"), &ProjectSettings::get_order); ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value"), &ProjectSettings::set_initial_value); diff --git a/core/config/project_settings.h b/core/config/project_settings.h index 2aca1e7691..353e298919 100644 --- a/core/config/project_settings.h +++ b/core/config/project_settings.h @@ -34,6 +34,7 @@ #include "core/object/class_db.h" #include "core/os/thread_safe.h" #include "core/templates/hash_map.h" +#include "core/templates/local_vector.h" #include "core/templates/rb_set.h" class ProjectSettings : public Object { @@ -69,7 +70,6 @@ protected: Variant variant; Variant initial; bool hide_from_editor = false; - bool overridden = false; bool restart_if_changed = false; #ifdef DEBUG_METHODS_ENABLED bool ignore_value_in_docs = false; @@ -91,12 +91,11 @@ protected: RBMap<StringName, VariantContainer> props; // NOTE: Key order is used e.g. in the save_custom method. String resource_path; HashMap<StringName, PropertyInfo> custom_prop_info; - bool disable_feature_overrides = false; bool using_datapack = false; List<String> input_presets; HashSet<String> custom_features; - HashMap<StringName, StringName> feature_overrides; + HashMap<StringName, LocalVector<Pair<StringName, StringName>>> feature_overrides; HashMap<StringName, AutoloadInfo> autoloads; @@ -181,7 +180,7 @@ public: List<String> get_input_presets() const { return input_presets; } - void set_disable_feature_overrides(bool p_disable); + Variant get_setting_with_override(const StringName &p_name) const; bool is_using_datapack() const; @@ -205,7 +204,7 @@ Variant _GLOBAL_DEF(const PropertyInfo &p_info, const Variant &p_default, bool p #define GLOBAL_DEF_RST(m_var, m_value) _GLOBAL_DEF(m_var, m_value, true) #define GLOBAL_DEF_NOVAL(m_var, m_value) _GLOBAL_DEF(m_var, m_value, false, true) #define GLOBAL_DEF_RST_NOVAL(m_var, m_value) _GLOBAL_DEF(m_var, m_value, true, true) -#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) +#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get_setting_with_override(m_var) #define GLOBAL_DEF_BASIC(m_var, m_value) _GLOBAL_DEF(m_var, m_value, false, false, true) #define GLOBAL_DEF_RST_BASIC(m_var, m_value) _GLOBAL_DEF(m_var, m_value, true, false, true) diff --git a/core/core_bind.cpp b/core/core_bind.cpp index 0ed05a20a2..ab433bd8f1 100644 --- a/core/core_bind.cpp +++ b/core/core_bind.cpp @@ -257,8 +257,8 @@ Error OS::shell_open(String p_uri) { return ::OS::get_singleton()->shell_open(p_uri); } -String OS::read_string_from_stdin(bool p_block) { - return ::OS::get_singleton()->get_stdin_string(true); +String OS::read_string_from_stdin() { + return ::OS::get_singleton()->get_stdin_string(); } int OS::execute(const String &p_path, const Vector<String> &p_arguments, Array r_output, bool p_read_stderr, bool p_open_console) { @@ -539,7 +539,7 @@ void OS::_bind_methods() { ClassDB::bind_method(D_METHOD("get_system_font_path", "font_name", "weight", "stretch", "italic"), &OS::get_system_font_path, DEFVAL(400), DEFVAL(100), DEFVAL(false)); ClassDB::bind_method(D_METHOD("get_system_font_path_for_text", "font_name", "text", "locale", "script", "weight", "stretch", "italic"), &OS::get_system_font_path_for_text, DEFVAL(String()), DEFVAL(String()), DEFVAL(400), DEFVAL(100), DEFVAL(false)); ClassDB::bind_method(D_METHOD("get_executable_path"), &OS::get_executable_path); - ClassDB::bind_method(D_METHOD("read_string_from_stdin", "block"), &OS::read_string_from_stdin, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("read_string_from_stdin"), &OS::read_string_from_stdin); ClassDB::bind_method(D_METHOD("execute", "path", "arguments", "output", "read_stderr", "open_console"), &OS::execute, DEFVAL(Array()), DEFVAL(false), DEFVAL(false)); ClassDB::bind_method(D_METHOD("create_process", "path", "arguments", "open_console"), &OS::create_process, DEFVAL(false)); ClassDB::bind_method(D_METHOD("create_instance", "arguments"), &OS::create_instance); diff --git a/core/core_bind.h b/core/core_bind.h index e8c59866e3..7ef346d1c4 100644 --- a/core/core_bind.h +++ b/core/core_bind.h @@ -146,7 +146,7 @@ public: String get_system_font_path(const String &p_font_name, int p_weight = 400, int p_stretch = 100, bool p_italic = false) const; Vector<String> get_system_font_path_for_text(const String &p_font_name, const String &p_text, const String &p_locale = String(), const String &p_script = String(), int p_weight = 400, int p_stretch = 100, bool p_italic = false) const; String get_executable_path() const; - String read_string_from_stdin(bool p_block = true); + String read_string_from_stdin(); int execute(const String &p_path, const Vector<String> &p_arguments, Array r_output = Array(), bool p_read_stderr = false, bool p_open_console = false); int create_process(const String &p_path, const Vector<String> &p_arguments, bool p_open_console = false); int create_instance(const Vector<String> &p_arguments); diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp index f2cd3ba4d9..98f8c3de41 100644 --- a/core/io/config_file.cpp +++ b/core/io/config_file.cpp @@ -208,7 +208,7 @@ Error ConfigFile::_internal_save(Ref<FileAccess> file) { file->store_string("\n"); } if (!E.key.is_empty()) { - file->store_string("[" + E.key + "]\n\n"); + file->store_string("[" + E.key.replace("]", "\\]") + "]\n\n"); } for (const KeyValue<String, Variant> &F : E.value) { @@ -308,7 +308,7 @@ Error ConfigFile::_parse(const String &p_path, VariantParser::Stream *p_stream) if (!assign.is_empty()) { set_value(section, assign, value); } else if (!next_tag.name.is_empty()) { - section = next_tag.name; + section = next_tag.name.replace("\\]", "]"); } } diff --git a/core/os/os.h b/core/os/os.h index 3c0c05f575..b80efa47b7 100644 --- a/core/os/os.h +++ b/core/os/os.h @@ -131,7 +131,7 @@ public: void print_rich(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3; void printerr(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3; - virtual String get_stdin_string(bool p_block = true) = 0; + virtual String get_stdin_string() = 0; virtual Error get_entropy(uint8_t *r_buffer, int p_bytes) = 0; // Should return cryptographically-safe random bytes. diff --git a/core/variant/variant_parser.cpp b/core/variant/variant_parser.cpp index 39a039ffe8..87874deb8d 100644 --- a/core/variant/variant_parser.cpp +++ b/core/variant/variant_parser.cpp @@ -1358,6 +1358,7 @@ Error VariantParser::_parse_tag(Token &token, Stream *p_stream, int &line, Strin if (p_simple_tag) { r_tag.name = ""; r_tag.fields.clear(); + bool escaping = false; if (p_stream->is_utf8()) { CharString cs; @@ -1368,7 +1369,15 @@ Error VariantParser::_parse_tag(Token &token, Stream *p_stream, int &line, Strin return ERR_PARSE_ERROR; } if (c == ']') { - break; + if (escaping) { + escaping = false; + } else { + break; + } + } else if (c == '\\') { + escaping = true; + } else { + escaping = false; } cs += c; } @@ -1381,7 +1390,15 @@ Error VariantParser::_parse_tag(Token &token, Stream *p_stream, int &line, Strin return ERR_PARSE_ERROR; } if (c == ']') { - break; + if (escaping) { + escaping = false; + } else { + break; + } + } else if (c == '\\') { + escaping = true; + } else { + escaping = false; } r_tag.name += String::chr(c); } diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index 41836650cd..7e7cb07cef 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -494,7 +494,7 @@ <return type="bool" /> <param index="0" name="x" type="float" /> <description> - Returns whether [code]x[/code] is a finite value, i.e. it is not [constant @GDScript.NAN], positive infinity, or negative infinity. + Returns whether [param x] is a finite value, i.e. it is not [constant @GDScript.NAN], positive infinity, or negative infinity. </description> </method> <method name="is_inf"> @@ -529,7 +529,7 @@ <return type="bool" /> <param index="0" name="x" type="float" /> <description> - Returns [code]true[/code] if [param x] is zero or almost zero. + Returns [code]true[/code] if [param x] is zero or almost zero. The comparison is done using a tolerance calculation with a small internal epsilon. This function is faster than using [method is_equal_approx] with one value as zero. </description> </method> diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml index 9efd3ac939..ca0cbf0ca1 100644 --- a/doc/classes/AnimationPlayer.xml +++ b/doc/classes/AnimationPlayer.xml @@ -137,6 +137,13 @@ Returns [code]true[/code] if playing an animation. </description> </method> + <method name="pause"> + <return type="void" /> + <description> + Pauses the currently playing animation. The [member current_animation_position] will be kept and calling [method play] or [method play_backwards] without arguments or with the same animation name as [member assigned_animation] will resume the animation. + See also [method stop]. + </description> + </method> <method name="play"> <return type="void" /> <param index="0" name="name" type="StringName" default="""" /> @@ -201,10 +208,9 @@ </method> <method name="stop"> <return type="void" /> - <param index="0" name="reset" type="bool" default="true" /> <description> - Stops or pauses the currently playing animation. If [param reset] is [code]true[/code], the animation position is reset to [code]0[/code] and the playback speed is reset to [code]1.0[/code]. - If [param reset] is [code]false[/code], the [member current_animation_position] will be kept and calling [method play] or [method play_backwards] without arguments or with the same animation name as [member assigned_animation] will resume the animation. + Stops the currently playing animation. The animation position is reset to [code]0[/code] and the playback speed is reset to [code]1.0[/code]. + See also [method pause]. </description> </method> </methods> diff --git a/doc/classes/BaseButton.xml b/doc/classes/BaseButton.xml index aedb8f4420..68f62d1c00 100644 --- a/doc/classes/BaseButton.xml +++ b/doc/classes/BaseButton.xml @@ -70,7 +70,7 @@ [Shortcut] associated to the button. </member> <member name="shortcut_feedback" type="bool" setter="set_shortcut_feedback" getter="is_shortcut_feedback" default="true"> - If [code]true[/code], the button will appear pressed when its shortcut is activated. If [code]false[/code] and [member toggle_mode] is [code]false[/code], the shortcut will activate the button without appearing to press the button. + If [code]true[/code], the button will highlight for a short amount of time when its shortcut is activated. If [code]false[/code] and [member toggle_mode] is [code]false[/code], the shortcut will activate without any visual feedback. </member> <member name="shortcut_in_tooltip" type="bool" setter="set_shortcut_in_tooltip" getter="is_shortcut_in_tooltip_enabled" default="true"> If [code]true[/code], the button will add information about its shortcut in the tooltip. diff --git a/doc/classes/BoneAttachment3D.xml b/doc/classes/BoneAttachment3D.xml index f29525038e..dd01de3607 100644 --- a/doc/classes/BoneAttachment3D.xml +++ b/doc/classes/BoneAttachment3D.xml @@ -16,19 +16,6 @@ Returns the [NodePath] to the external [Skeleton3D] node, if one has been set. </description> </method> - <method name="get_override_mode" qualifiers="const" is_deprecated="true"> - <return type="int" /> - <description> - Deprecated. Local pose overrides will be removed. - Returns the override mode for the BoneAttachment3D node (0=global / 1=local). - </description> - </method> - <method name="get_override_pose" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the BoneAttachment3D node is overriding the bone pose of the bone it's attached to. - </description> - </method> <method name="get_use_external_skeleton" qualifiers="const"> <return type="bool" /> <description> @@ -49,21 +36,6 @@ Sets the [NodePath] to the external skeleton that the BoneAttachment3D node should use. The external [Skeleton3D] node is only used when [code]use_external_skeleton[/code] is set to [code]true[/code]. </description> </method> - <method name="set_override_mode" is_deprecated="true"> - <return type="void" /> - <param index="0" name="override_mode" type="int" /> - <description> - Deprecated. Local pose overrides will be removed. - Sets the override mode for the BoneAttachment3D node (0=global / 1=local). The override mode defines which of the bone poses the BoneAttachment3D node will override. - </description> - </method> - <method name="set_override_pose"> - <return type="void" /> - <param index="0" name="override_pose" type="bool" /> - <description> - Sets whether the BoneAttachment3D node will override the bone pose of the bone it is attached to. When set to [code]true[/code], the BoneAttachment3D node can change the pose of the bone. - </description> - </method> <method name="set_use_external_skeleton"> <return type="void" /> <param index="0" name="use_external_skeleton" type="bool" /> @@ -79,5 +51,8 @@ <member name="bone_name" type="String" setter="set_bone_name" getter="get_bone_name" default=""""> The name of the attached bone. </member> + <member name="override_pose" type="bool" setter="set_override_pose" getter="get_override_pose" default="false"> + Whether the BoneAttachment3D node will override the bone pose of the bone it is attached to. When set to [code]true[/code], the BoneAttachment3D node can change the pose of the bone. When set to [code]false[/code], the BoneAttachment3D will always be set to the bone's transform. + </member> </members> </class> diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml index 5171e0acbe..fbab1d76a0 100644 --- a/doc/classes/CanvasItem.xml +++ b/doc/classes/CanvasItem.xml @@ -97,6 +97,7 @@ <param index="2" name="color" type="Color" /> <param index="3" name="width" type="float" default="1.0" /> <param index="4" name="dash" type="float" default="2.0" /> + <param index="5" name="aligned" type="bool" default="true" /> <description> Draws a dashed line from a 2D point to another, with a given color and width. See also [method draw_multiline] and [method draw_polyline]. </description> diff --git a/doc/classes/EditorExportPlatform.xml b/doc/classes/EditorExportPlatform.xml index 1d63af9233..f2b39ab134 100644 --- a/doc/classes/EditorExportPlatform.xml +++ b/doc/classes/EditorExportPlatform.xml @@ -1,8 +1,11 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="EditorExportPlatform" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> + Identifies a supported export platform, and internally provides the functionality of exporting to that platform. </brief_description> <description> + Base resource that provides the functionality of exporting a release build of a project to a platform, from the editor. Stores platform-specific metadata such as the name and supported features of the platform, and performs the exporting of projects, PCK files, and ZIP files. Uses an export template for the platform provided at the time of project exporting. + Used in scripting by [EditorExportPlugin] to configure platform-specific customization of scenes and resources. See [method EditorExportPlugin._begin_customize_scenes] and [method EditorExportPlugin._begin_customize_resources] for more details. </description> <tutorials> </tutorials> diff --git a/doc/classes/EditorPlugin.xml b/doc/classes/EditorPlugin.xml index b44c1d7ffa..2124a97751 100644 --- a/doc/classes/EditorPlugin.xml +++ b/doc/classes/EditorPlugin.xml @@ -143,7 +143,7 @@ [gdscript] func _forward_canvas_draw_over_viewport(overlay): # Draw a circle at cursor position. - overlay.draw_circle(overlay.get_local_mouse_position(), 64, Color.white) + overlay.draw_circle(overlay.get_local_mouse_position(), 64, Color.WHITE) func _forward_canvas_gui_input(event): if event is InputEventMouseMotion: @@ -347,7 +347,7 @@ [codeblock] func _set_state(data): zoom = data.get("zoom", 1.0) - preferred_color = data.get("my_color", Color.white) + preferred_color = data.get("my_color", Color.WHITE) [/codeblock] </description> </method> @@ -359,7 +359,7 @@ [codeblock] func _set_window_layout(configuration): $Window.position = configuration.get_value("MyPlugin", "window_position", Vector2()) - $Icon.modulate = configuration.get_value("MyPlugin", "icon_color", Color.white) + $Icon.modulate = configuration.get_value("MyPlugin", "icon_color", Color.WHITE) [/codeblock] </description> </method> diff --git a/doc/classes/GeometryInstance3D.xml b/doc/classes/GeometryInstance3D.xml index 1ae4718536..127c5daf95 100644 --- a/doc/classes/GeometryInstance3D.xml +++ b/doc/classes/GeometryInstance3D.xml @@ -21,7 +21,10 @@ <param index="0" name="name" type="StringName" /> <param index="1" name="value" type="Variant" /> <description> - Set the value of a shader parameter for this instance only. + Set the value of a shader uniform for this instance only ([url=$DOCS_URL/tutorials/shaders/shader_reference/shading_language.html#per-instance-uniforms]per-instance uniform[/url]). See also [method ShaderMaterial.set_shader_parameter] to assign a uniform on all instances using the same [ShaderMaterial]. + [b]Note:[/b] For a shader uniform to be assignable on a per-instance basis, it [i]must[/i] be defined with [code]instance uniform ...[/code] rather than [code]uniform ...[/code] in the shader code. + [b]Note:[/b] [param name] is case-sensitive and must match the name of the uniform in the code exactly (not the capitalized name in the inspector). + [b]Note:[/b] Per-instance shader uniforms are currently only available in 3D, so there is no 2D equivalent of this method. </description> </method> </methods> diff --git a/doc/classes/Image.xml b/doc/classes/Image.xml index ed1b40488e..051e087611 100644 --- a/doc/classes/Image.xml +++ b/doc/classes/Image.xml @@ -489,7 +489,7 @@ var img = Image.new() img.create(img_width, img_height, false, Image.FORMAT_RGBA8) - img.set_pixel(1, 2, Color.red) # Sets the color at (1, 2) to red. + img.set_pixel(1, 2, Color.RED) # Sets the color at (1, 2) to red. [/gdscript] [csharp] int imgWidth = 10; @@ -517,7 +517,7 @@ var img = Image.new() img.create(img_width, img_height, false, Image.FORMAT_RGBA8) - img.set_pixelv(Vector2i(1, 2), Color.red) # Sets the color at (1, 2) to red. + img.set_pixelv(Vector2i(1, 2), Color.RED) # Sets the color at (1, 2) to red. [/gdscript] [csharp] int imgWidth = 10; diff --git a/doc/classes/MeshInstance2D.xml b/doc/classes/MeshInstance2D.xml index e9666337a1..7bb33fc46d 100644 --- a/doc/classes/MeshInstance2D.xml +++ b/doc/classes/MeshInstance2D.xml @@ -13,10 +13,6 @@ <member name="mesh" type="Mesh" setter="set_mesh" getter="get_mesh"> The [Mesh] that will be drawn by the [MeshInstance2D]. </member> - <member name="normal_map" type="Texture2D" setter="set_normal_map" getter="get_normal_map"> - The normal map that will be used if using the default [CanvasItemMaterial]. - [b]Note:[/b] Godot expects the normal map to use X+, Y+, and Z+ coordinates. See [url=http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates]this page[/url] for a comparison of normal map coordinates expected by popular engines. - </member> <member name="texture" type="Texture2D" setter="set_texture" getter="get_texture"> The [Texture2D] that will be used if using the default [CanvasItemMaterial]. Can be accessed as [code]TEXTURE[/code] in CanvasItem shader. </member> diff --git a/doc/classes/MultiMeshInstance2D.xml b/doc/classes/MultiMeshInstance2D.xml index daf5ef6287..16c0f6070e 100644 --- a/doc/classes/MultiMeshInstance2D.xml +++ b/doc/classes/MultiMeshInstance2D.xml @@ -13,10 +13,6 @@ <member name="multimesh" type="MultiMesh" setter="set_multimesh" getter="get_multimesh"> The [MultiMesh] that will be drawn by the [MultiMeshInstance2D]. </member> - <member name="normal_map" type="Texture2D" setter="set_normal_map" getter="get_normal_map"> - The normal map that will be used if using the default [CanvasItemMaterial]. - [b]Note:[/b] Godot expects the normal map to use X+, Y+, and Z+ coordinates. See [url=http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates]this page[/url] for a comparison of normal map coordinates expected by popular engines. - </member> <member name="texture" type="Texture2D" setter="set_texture" getter="get_texture"> The [Texture2D] that will be used if using the default [CanvasItemMaterial]. Can be accessed as [code]TEXTURE[/code] in CanvasItem shader. </member> diff --git a/doc/classes/NavigationAgent2D.xml b/doc/classes/NavigationAgent2D.xml index 1607060ac2..b561748b30 100644 --- a/doc/classes/NavigationAgent2D.xml +++ b/doc/classes/NavigationAgent2D.xml @@ -114,7 +114,7 @@ <member name="max_neighbors" type="int" setter="set_max_neighbors" getter="get_max_neighbors" default="10"> The maximum number of neighbors for the agent to consider. </member> - <member name="max_speed" type="float" setter="set_max_speed" getter="get_max_speed" default="200.0"> + <member name="max_speed" type="float" setter="set_max_speed" getter="get_max_speed" default="100.0"> The maximum speed that an agent can move. </member> <member name="navigation_layers" type="int" setter="set_navigation_layers" getter="get_navigation_layers" default="1"> @@ -123,10 +123,10 @@ <member name="neighbor_distance" type="float" setter="set_neighbor_distance" getter="get_neighbor_distance" default="500.0"> The distance to search for other agents. </member> - <member name="path_desired_distance" type="float" setter="set_path_desired_distance" getter="get_path_desired_distance" default="1.0"> + <member name="path_desired_distance" type="float" setter="set_path_desired_distance" getter="get_path_desired_distance" default="20.0"> The distance threshold before a path point is considered to be reached. This will allow an agent to not have to hit a path point on the path exactly, but in the area. If this value is set to high the NavigationAgent will skip points on the path which can lead to leaving the navigation mesh. If this value is set to low the NavigationAgent will be stuck in a repath loop cause it will constantly overshoot or undershoot the distance to the next point on each physics frame update. </member> - <member name="path_max_distance" type="float" setter="set_path_max_distance" getter="get_path_max_distance" default="3.0"> + <member name="path_max_distance" type="float" setter="set_path_max_distance" getter="get_path_max_distance" default="100.0"> The maximum distance the agent is allowed away from the ideal path to the final location. This can happen due to trying to avoid collisions. When the maximum distance is exceeded, it recalculates the ideal path. </member> <member name="path_metadata_flags" type="int" setter="set_path_metadata_flags" getter="get_path_metadata_flags" enum="NavigationPathQueryParameters2D.PathMetadataFlags" default="7"> @@ -136,13 +136,13 @@ The radius of the avoidance agent. This is the "body" of the avoidance agent and not the avoidance maneuver starting radius (which is controlled by [member neighbor_distance]). Does not affect normal pathfinding. To change an actor's pathfinding radius bake [NavigationMesh] resources with a different [member NavigationMesh.agent_radius] property and use different navigation maps for each actor size. </member> - <member name="target_desired_distance" type="float" setter="set_target_desired_distance" getter="get_target_desired_distance" default="1.0"> + <member name="target_desired_distance" type="float" setter="set_target_desired_distance" getter="get_target_desired_distance" default="10.0"> The distance threshold before the final target point is considered to be reached. This will allow an agent to not have to hit the point of the final target exactly, but only the area. If this value is set to low the NavigationAgent will be stuck in a repath loop cause it will constantly overshoot or undershoot the distance to the final target point on each physics frame update. </member> <member name="target_location" type="Vector2" setter="set_target_location" getter="get_target_location" default="Vector2(0, 0)"> The user-defined target location. Setting this property will clear the current navigation path. </member> - <member name="time_horizon" type="float" setter="set_time_horizon" getter="get_time_horizon" default="20.0"> + <member name="time_horizon" type="float" setter="set_time_horizon" getter="get_time_horizon" default="1.0"> The minimal amount of time for which this agent's velocities, that are computed with the collision avoidance algorithm, are safe with respect to other agents. The larger the number, the sooner the agent will respond to other agents, but less freedom in choosing its velocities. Must be positive. </member> </members> diff --git a/doc/classes/NavigationServer3D.xml b/doc/classes/NavigationServer3D.xml index 6fed3f40e5..e007c71342 100644 --- a/doc/classes/NavigationServer3D.xml +++ b/doc/classes/NavigationServer3D.xml @@ -134,6 +134,13 @@ Returns all created navigation map [RID]s on the NavigationServer. This returns both 2D and 3D created navigation maps as there is technically no distinction between them. </description> </method> + <method name="get_process_info" qualifiers="const"> + <return type="int" /> + <param index="0" name="process_info" type="int" enum="NavigationServer3D.ProcessInfo" /> + <description> + Returns information about the current state of the NavigationServer. See [enum ProcessInfo] for a list of available states. + </description> + </method> <method name="link_create"> <return type="RID" /> <description> @@ -593,4 +600,33 @@ </description> </signal> </signals> + <constants> + <constant name="INFO_ACTIVE_MAPS" value="0" enum="ProcessInfo"> + Constant to get the number of active navigation maps. + </constant> + <constant name="INFO_REGION_COUNT" value="1" enum="ProcessInfo"> + Constant to get the number of active navigation regions. + </constant> + <constant name="INFO_AGENT_COUNT" value="2" enum="ProcessInfo"> + Constant to get the number of active navigation agents processing avoidance. + </constant> + <constant name="INFO_LINK_COUNT" value="3" enum="ProcessInfo"> + Constant to get the number of active navigation links. + </constant> + <constant name="INFO_POLYGON_COUNT" value="4" enum="ProcessInfo"> + Constant to get the number of navigation mesh polygons. + </constant> + <constant name="INFO_EDGE_COUNT" value="5" enum="ProcessInfo"> + Constant to get the number of navigation mesh polygon edges. + </constant> + <constant name="INFO_EDGE_MERGE_COUNT" value="6" enum="ProcessInfo"> + Constant to get the number of navigation mesh polygon edges that were merged due to edge key overlap. + </constant> + <constant name="INFO_EDGE_CONNECTION_COUNT" value="7" enum="ProcessInfo"> + Constant to get the number of navigation mesh polygon edges that are considered connected by edge proximity. + </constant> + <constant name="INFO_EDGE_FREE_COUNT" value="8" enum="ProcessInfo"> + Constant to get the number of navigation mesh polygon edges that could not be merged but may be still connected by edge proximity or with links. + </constant> + </constants> </class> diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml index ff4982e2fb..6dab7b4ebe 100644 --- a/doc/classes/OS.xml +++ b/doc/classes/OS.xml @@ -572,10 +572,9 @@ </method> <method name="read_string_from_stdin"> <return type="String" /> - <param index="0" name="block" type="bool" default="true" /> <description> - Reads a user input string from the standard input (usually the terminal). - [b]Note:[/b] This method is implemented on Linux, macOS and Windows. Non-blocking reads are not currently supported on any platform. + Reads a user input string from the standard input (usually the terminal). This operation is [i]blocking[/i], which causes the window to freeze if [method read_string_from_stdin] is called on the main thread. The thread calling [method read_string_from_stdin] will block until the program receives a line break in standard input (usually by the user pressing [kbd]Enter[/kbd]). + [b]Note:[/b] This method is implemented on Linux, macOS and Windows. </description> </method> <method name="request_permission"> diff --git a/doc/classes/Performance.xml b/doc/classes/Performance.xml index 381fa3e9ef..6b7daa534e 100644 --- a/doc/classes/Performance.xml +++ b/doc/classes/Performance.xml @@ -131,67 +131,97 @@ <constant name="TIME_PHYSICS_PROCESS" value="2" enum="Monitor"> Time it took to complete one physics frame, in seconds. [i]Lower is better.[/i] </constant> - <constant name="MEMORY_STATIC" value="3" enum="Monitor"> + <constant name="TIME_NAVIGATION_PROCESS" value="3" enum="Monitor"> + Time it took to complete one navigation step, in seconds. This includes navigation map updates as well as agent avoidance calculations. [i]Lower is better.[/i] + </constant> + <constant name="MEMORY_STATIC" value="4" enum="Monitor"> Static memory currently used, in bytes. Not available in release builds. [i]Lower is better.[/i] </constant> - <constant name="MEMORY_STATIC_MAX" value="4" enum="Monitor"> + <constant name="MEMORY_STATIC_MAX" value="5" enum="Monitor"> Available static memory. Not available in release builds. [i]Lower is better.[/i] </constant> - <constant name="MEMORY_MESSAGE_BUFFER_MAX" value="5" enum="Monitor"> + <constant name="MEMORY_MESSAGE_BUFFER_MAX" value="6" enum="Monitor"> Largest amount of memory the message queue buffer has used, in bytes. The message queue is used for deferred functions calls and notifications. [i]Lower is better.[/i] </constant> - <constant name="OBJECT_COUNT" value="6" enum="Monitor"> + <constant name="OBJECT_COUNT" value="7" enum="Monitor"> Number of objects currently instantiated (including nodes). [i]Lower is better.[/i] </constant> - <constant name="OBJECT_RESOURCE_COUNT" value="7" enum="Monitor"> + <constant name="OBJECT_RESOURCE_COUNT" value="8" enum="Monitor"> Number of resources currently used. [i]Lower is better.[/i] </constant> - <constant name="OBJECT_NODE_COUNT" value="8" enum="Monitor"> + <constant name="OBJECT_NODE_COUNT" value="9" enum="Monitor"> Number of nodes currently instantiated in the scene tree. This also includes the root node. [i]Lower is better.[/i] </constant> - <constant name="OBJECT_ORPHAN_NODE_COUNT" value="9" enum="Monitor"> + <constant name="OBJECT_ORPHAN_NODE_COUNT" value="10" enum="Monitor"> Number of orphan nodes, i.e. nodes which are not parented to a node of the scene tree. [i]Lower is better.[/i] </constant> - <constant name="RENDER_TOTAL_OBJECTS_IN_FRAME" value="10" enum="Monitor"> + <constant name="RENDER_TOTAL_OBJECTS_IN_FRAME" value="11" enum="Monitor"> The total number of objects in the last rendered frame. This metric doesn't include culled objects (either via hiding nodes, frustum culling or occlusion culling). [i]Lower is better.[/i] </constant> - <constant name="RENDER_TOTAL_PRIMITIVES_IN_FRAME" value="11" enum="Monitor"> + <constant name="RENDER_TOTAL_PRIMITIVES_IN_FRAME" value="12" enum="Monitor"> The total number of vertices or indices rendered in the last rendered frame. This metric doesn't include primitives from culled objects (either via hiding nodes, frustum culling or occlusion culling). Due to the depth prepass and shadow passes, the number of primitives is always higher than the actual number of vertices in the scene (typically double or triple the original vertex count). [i]Lower is better.[/i] </constant> - <constant name="RENDER_TOTAL_DRAW_CALLS_IN_FRAME" value="12" enum="Monitor"> + <constant name="RENDER_TOTAL_DRAW_CALLS_IN_FRAME" value="13" enum="Monitor"> The total number of draw calls performed in the last rendered frame. This metric doesn't include culled objects (either via hiding nodes, frustum culling or occlusion culling), since they do not result in draw calls. [i]Lower is better.[/i] </constant> - <constant name="RENDER_VIDEO_MEM_USED" value="13" enum="Monitor"> + <constant name="RENDER_VIDEO_MEM_USED" value="14" enum="Monitor"> The amount of video memory used (texture and vertex memory combined, in bytes). Since this metric also includes miscellaneous allocations, this value is always greater than the sum of [constant RENDER_TEXTURE_MEM_USED] and [constant RENDER_BUFFER_MEM_USED]. [i]Lower is better.[/i] </constant> - <constant name="RENDER_TEXTURE_MEM_USED" value="14" enum="Monitor"> + <constant name="RENDER_TEXTURE_MEM_USED" value="15" enum="Monitor"> The amount of texture memory used (in bytes). [i]Lower is better.[/i] </constant> - <constant name="RENDER_BUFFER_MEM_USED" value="15" enum="Monitor"> + <constant name="RENDER_BUFFER_MEM_USED" value="16" enum="Monitor"> The amount of render buffer memory used (in bytes). [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_2D_ACTIVE_OBJECTS" value="16" enum="Monitor"> + <constant name="PHYSICS_2D_ACTIVE_OBJECTS" value="17" enum="Monitor"> Number of active [RigidBody2D] nodes in the game. [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_2D_COLLISION_PAIRS" value="17" enum="Monitor"> + <constant name="PHYSICS_2D_COLLISION_PAIRS" value="18" enum="Monitor"> Number of collision pairs in the 2D physics engine. [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_2D_ISLAND_COUNT" value="18" enum="Monitor"> + <constant name="PHYSICS_2D_ISLAND_COUNT" value="19" enum="Monitor"> Number of islands in the 2D physics engine. [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_3D_ACTIVE_OBJECTS" value="19" enum="Monitor"> + <constant name="PHYSICS_3D_ACTIVE_OBJECTS" value="20" enum="Monitor"> Number of active [RigidBody3D] and [VehicleBody3D] nodes in the game. [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_3D_COLLISION_PAIRS" value="20" enum="Monitor"> + <constant name="PHYSICS_3D_COLLISION_PAIRS" value="21" enum="Monitor"> Number of collision pairs in the 3D physics engine. [i]Lower is better.[/i] </constant> - <constant name="PHYSICS_3D_ISLAND_COUNT" value="21" enum="Monitor"> + <constant name="PHYSICS_3D_ISLAND_COUNT" value="22" enum="Monitor"> Number of islands in the 3D physics engine. [i]Lower is better.[/i] </constant> - <constant name="AUDIO_OUTPUT_LATENCY" value="22" enum="Monitor"> + <constant name="AUDIO_OUTPUT_LATENCY" value="23" enum="Monitor"> Output latency of the [AudioServer]. [i]Lower is better.[/i] </constant> - <constant name="MONITOR_MAX" value="23" enum="Monitor"> + <constant name="NAVIGATION_ACTIVE_MAPS" value="24" enum="Monitor"> + Number of active navigation maps in the [NavigationServer3D]. This also includes the two empty default navigation maps created by World2D and World3D. + </constant> + <constant name="NAVIGATION_REGION_COUNT" value="25" enum="Monitor"> + Number of active navigation regions in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_AGENT_COUNT" value="26" enum="Monitor"> + Number of active navigation agents processing avoidance in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_LINK_COUNT" value="27" enum="Monitor"> + Number of active navigation links in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_POLYGON_COUNT" value="28" enum="Monitor"> + Number of navigation mesh polygons in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_EDGE_COUNT" value="29" enum="Monitor"> + Number of navigation mesh polygon edges in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_EDGE_MERGE_COUNT" value="30" enum="Monitor"> + Number of navigation mesh polygon edges that were merged due to edge key overlap in the [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_EDGE_CONNECTION_COUNT" value="31" enum="Monitor"> + Number of polygon edges that are considered connected by edge proximity [NavigationServer3D]. + </constant> + <constant name="NAVIGATION_EDGE_FREE_COUNT" value="32" enum="Monitor"> + Number of navigation mesh polygon edges that could not be merged in the [NavigationServer3D]. The edges still may be connected by edge proximity or with links. + </constant> + <constant name="MONITOR_MAX" value="33" enum="Monitor"> Represents the size of the [enum Monitor] enum. </constant> </constants> diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml index cfcfca9880..9e1c751662 100644 --- a/doc/classes/ProjectSettings.xml +++ b/doc/classes/ProjectSettings.xml @@ -84,6 +84,25 @@ GD.Print(ProjectSettings.GetSetting("application/config/custom_description", "No description specified.")); [/csharp] [/codeblocks] + [b]Note:[/b] This method doesn't take potential feature overrides into account automatically. Use [method get_setting_with_override] to handle seamlessly. + </description> + </method> + <method name="get_setting_with_override" qualifiers="const"> + <return type="Variant" /> + <param index="0" name="name" type="StringName" /> + <description> + Similar to [method get_setting], but applies feature tag overrides if any exists and is valid. + [b]Example:[/b] + If the following setting override exists "application/config/name.windows", and the following code is executed: + [codeblocks] + [gdscript] + print(ProjectSettings.get_setting_with_override("application/config/name")) + [/gdscript] + [csharp] + GD.Print(ProjectSettings.GetSettingWithOverride("application/config/name")); + [/csharp] + [/codeblocks] + Then the overridden setting will be returned instead if the project is running on the [i]Windows[/i] operating system. </description> </method> <method name="globalize_path" qualifiers="const"> @@ -741,6 +760,9 @@ <member name="gui/theme/lcd_subpixel_layout" type="int" setter="" getter="" default="1"> LCD subpixel layout used for font anti-aliasing. See [enum TextServer.FontLCDSubpixelLayout]. </member> + <member name="gui/timers/button_shortcut_feedback_highlight_time" type="float" setter="" getter="" default="0.2"> + When [member BaseButton.shortcut_feedback] is enabled, this is the time the [BaseButton] will remain highlighted after a shortcut. + </member> <member name="gui/timers/incremental_search_max_interval_msec" type="int" setter="" getter="" default="2000"> Timer setting for incremental search in [Tree], [ItemList], etc. controls (in milliseconds). </member> diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml index 937d36d422..7675a37cbd 100644 --- a/doc/classes/RenderingServer.xml +++ b/doc/classes/RenderingServer.xml @@ -1262,6 +1262,12 @@ Tries to free an object in the RenderingServer. </description> </method> + <method name="get_default_clear_color"> + <return type="Color" /> + <description> + Returns the default clear color which is used when a specific clear color has not been selected. + </description> + </method> <method name="get_frame_setup_time_cpu" qualifiers="const"> <return type="float" /> <description> diff --git a/doc/classes/ShaderMaterial.xml b/doc/classes/ShaderMaterial.xml index 1af7ac4fc5..a2346822e5 100644 --- a/doc/classes/ShaderMaterial.xml +++ b/doc/classes/ShaderMaterial.xml @@ -23,7 +23,8 @@ <param index="1" name="value" type="Variant" /> <description> Changes the value set for this material of a uniform in the shader. - [b]Note:[/b] [param param] must match the name of the uniform in the code exactly. + [b]Note:[/b] [param param] is case-sensitive and must match the name of the uniform in the code exactly (not the capitalized name in the inspector). + [b]Note:[/b] Changes to the shader uniform will be effective on all instances using this [ShaderMaterial]. To prevent this, use per-instance uniforms with [method GeometryInstance3D.set_instance_shader_parameter] or duplicate the [ShaderMaterial] resource using [method Resource.duplicate]. Per-instance uniforms allow for better shader reuse and are therefore faster, so they should be preferred over duplicating the [ShaderMaterial] when possible. </description> </method> </methods> diff --git a/doc/classes/Skeleton3D.xml b/doc/classes/Skeleton3D.xml index 3bd0e04b92..70986ba06a 100644 --- a/doc/classes/Skeleton3D.xml +++ b/doc/classes/Skeleton3D.xml @@ -7,6 +7,7 @@ Skeleton3D provides a hierarchical interface for managing bones, including pose, rest and animation (see [Animation]). It can also use ragdoll physics. The overall transform of a bone with respect to the skeleton is determined by the following hierarchical order: rest pose, custom pose and pose. Note that "global pose" below refers to the overall transform of the bone with respect to skeleton, so it not the actual global/world transform of the bone. + To setup different types of inverse kinematics, consider using [SkeletonIK3D], or add a custom IK implementation in [method Node._process] as a child node. </description> <tutorials> <link title="3D Inverse Kinematics Demo">https://godotengine.org/asset-library/asset/523</link> @@ -32,26 +33,11 @@ Removes the global pose override on all bones in the skeleton. </description> </method> - <method name="clear_bones_local_pose_override" is_deprecated="true"> - <return type="void" /> - <description> - Deprecated. Local pose overrides will be removed. - Removes the local pose override on all bones in the skeleton. - </description> - </method> <method name="create_skin_from_rest_transforms"> <return type="Skin" /> <description> </description> </method> - <method name="execute_modifications" is_deprecated="true"> - <return type="void" /> - <param index="0" name="delta" type="float" /> - <param index="1" name="execution_mode" type="int" /> - <description> - Executes all the modifications on the [SkeletonModificationStack3D], if the Skeleton3D has one assigned. - </description> - </method> <method name="find_bone" qualifiers="const"> <return type="int" /> <param index="0" name="name" type="String" /> @@ -113,13 +99,6 @@ Returns the global rest transform for [param bone_idx]. </description> </method> - <method name="get_bone_local_pose_override" qualifiers="const"> - <return type="Transform3D" /> - <param index="0" name="bone_idx" type="int" /> - <description> - Returns the local pose override transform for [param bone_idx]. - </description> - </method> <method name="get_bone_name" qualifiers="const"> <return type="String" /> <param index="0" name="bone_idx" type="int" /> @@ -167,43 +146,18 @@ Returns the rest transform for a bone [param bone_idx]. </description> </method> - <method name="get_modification_stack" is_deprecated="true"> - <return type="SkeletonModificationStack3D" /> - <description> - Returns the modification stack attached to this skeleton, if one exists. - </description> - </method> <method name="get_parentless_bones" qualifiers="const"> <return type="PackedInt32Array" /> <description> Returns an array with all of the bones that are parentless. Another way to look at this is that it returns the indexes of all the bones that are not dependent or modified by other bones in the Skeleton. </description> </method> - <method name="global_pose_to_local_pose" is_deprecated="true"> - <return type="Transform3D" /> - <param index="0" name="bone_idx" type="int" /> - <param index="1" name="global_pose" type="Transform3D" /> - <description> - Takes the passed-in global pose and converts it to local pose transform. - This can be used to easily convert a global pose from [method get_bone_global_pose] to a global transform in [method set_bone_local_pose_override]. - </description> - </method> - <method name="global_pose_to_world_transform" is_deprecated="true"> - <return type="Transform3D" /> - <param index="0" name="global_pose" type="Transform3D" /> - <description> - Deprecated. Use [Node3D] apis instead. - Takes the passed-in global pose and converts it to a world transform. - This can be used to easily convert a global pose from [method get_bone_global_pose] to a global transform usable with a node's transform, like [member Node3D.global_transform] for example. - </description> - </method> - <method name="global_pose_z_forward_to_bone_forward" is_deprecated="true"> - <return type="Basis" /> - <param index="0" name="bone_idx" type="int" /> - <param index="1" name="basis" type="Basis" /> + <method name="get_version" qualifiers="const"> + <return type="int" /> <description> - Rotates the given [Basis] so that the forward axis of the Basis is facing in the forward direction of the bone at [param bone_idx]. - This is helper function to make using [method Transform3D.looking_at] easier with bone poses. + Returns the number of times the bone hierarchy has changed within this skeleton, including renames. + The Skeleton version is not serialized: only use within a single instance of Skeleton3D. + Use for invalidating caches in IK solvers and other nodes which process bones. </description> </method> <method name="is_bone_enabled" qualifiers="const"> @@ -213,15 +167,6 @@ Returns whether the bone pose for the bone at [param bone_idx] is enabled. </description> </method> - <method name="local_pose_to_global_pose" is_deprecated="true"> - <return type="Transform3D" /> - <param index="0" name="bone_idx" type="int" /> - <param index="1" name="local_pose" type="Transform3D" /> - <description> - Converts the passed-in local pose to a global pose relative to the inputted bone, [param bone_idx]. - This could be used to convert [method get_bone_pose] for use with the [method set_bone_global_pose_override] function. - </description> - </method> <method name="localize_rests"> <return type="void" /> <description> @@ -298,19 +243,6 @@ [b]Note:[/b] The pose transform needs to be a global pose! To convert a world transform from a [Node3D] to a global bone pose, multiply the [method Transform3D.affine_inverse] of the node's [member Node3D.global_transform] by the desired world transform </description> </method> - <method name="set_bone_local_pose_override" is_deprecated="true"> - <return type="void" /> - <param index="0" name="bone_idx" type="int" /> - <param index="1" name="pose" type="Transform3D" /> - <param index="2" name="amount" type="float" /> - <param index="3" name="persistent" type="bool" default="false" /> - <description> - Deprecated. Local pose overrides will be removed. - Sets the local pose transform, [param pose], for the bone at [param bone_idx]. - [param amount] is the interpolation strength that will be used when applying the pose, and [param persistent] determines if the applied pose will remain. - [b]Note:[/b] The pose transform needs to be a local pose! Use [method global_pose_to_local_pose] to convert a global pose to a local pose. - </description> - </method> <method name="set_bone_name"> <return type="void" /> <param index="0" name="bone_idx" type="int" /> @@ -356,13 +288,6 @@ Sets the rest transform for bone [param bone_idx]. </description> </method> - <method name="set_modification_stack" is_deprecated="true"> - <return type="void" /> - <param index="0" name="modification_stack" type="SkeletonModificationStack3D" /> - <description> - Sets the modification stack for this skeleton to the passed-in modification stack, [param modification_stack]. - </description> - </method> <method name="unparent_bone_and_rest"> <return type="void" /> <param index="0" name="bone_idx" type="int" /> @@ -370,15 +295,6 @@ Unparents the bone at [param bone_idx] and sets its rest position to that of its parent prior to being reset. </description> </method> - <method name="world_transform_to_global_pose" is_deprecated="true"> - <return type="Transform3D" /> - <param index="0" name="world_transform" type="Transform3D" /> - <description> - Deprecated. Use [Node3D] apis instead. - Takes the passed-in global transform and converts it to a global pose. - This can be used to easily convert a global transform from [member Node3D.global_transform] to a global pose usable with [method set_bone_global_pose_override], for example. - </description> - </method> </methods> <members> <member name="animate_physical_bones" type="bool" setter="set_animate_physical_bones" getter="get_animate_physical_bones" default="true"> diff --git a/doc/classes/SkeletonModification3D.xml b/doc/classes/SkeletonModification3D.xml deleted file mode 100644 index 25431ea96f..0000000000 --- a/doc/classes/SkeletonModification3D.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3D" inherits="Resource" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A resource that operates on bones in a [Skeleton3D]. - </brief_description> - <description> - This resource provides an interface that can be expanded so code that operates on bones in a [Skeleton3D] can be mixed and matched together to create complex interactions. - This is used to provide Godot with a flexible and powerful Inverse Kinematics solution that can be adapted for many different uses. - </description> - <tutorials> - </tutorials> - <methods> - <method name="_execute" qualifiers="virtual"> - <return type="void" /> - <param index="0" name="delta" type="float" /> - <description> - Executes the given modification. This is where the modification performs whatever function it is designed to do. - </description> - </method> - <method name="_setup_modification" qualifiers="virtual"> - <return type="void" /> - <param index="0" name="modification_stack" type="SkeletonModificationStack3D" /> - <description> - Sets up the modification so it can be executed. This function should be called automatically by the [SkeletonModificationStack3D] containing this modification. - If you need to initialize a modification before use, this is the place to do it! - </description> - </method> - <method name="clamp_angle"> - <return type="float" /> - <param index="0" name="angle" type="float" /> - <param index="1" name="min" type="float" /> - <param index="2" name="max" type="float" /> - <param index="3" name="invert" type="bool" /> - <description> - Takes a angle and clamps it so it is within the passed-in [param min] and [param max] range. [param invert] will inversely clamp the angle, clamping it to the range outside of the given bounds. - </description> - </method> - <method name="get_is_setup" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether this modification has been successfully setup or not. - </description> - </method> - <method name="get_modification_stack"> - <return type="SkeletonModificationStack3D" /> - <description> - Returns the [SkeletonModificationStack3D] that this modification is bound to. Through the modification stack, you can access the Skeleton3D the modification is operating on. - </description> - </method> - <method name="set_is_setup"> - <return type="void" /> - <param index="0" name="is_setup" type="bool" /> - <description> - Manually allows you to set the setup state of the modification. This function should only rarely be used, as the [SkeletonModificationStack3D] the modification is bound to should handle setting the modification up. - </description> - </method> - </methods> - <members> - <member name="enabled" type="bool" setter="set_enabled" getter="get_enabled" default="true"> - When true, the modification's [method _execute] function will be called by the [SkeletonModificationStack3D]. - </member> - <member name="execution_mode" type="int" setter="set_execution_mode" getter="get_execution_mode" default="0"> - The execution mode for the modification. This tells the modification stack when to execute the modification. Some modifications have settings that are only available in certain execution modes. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModification3DCCDIK.xml b/doc/classes/SkeletonModification3DCCDIK.xml deleted file mode 100644 index 90b2e78449..0000000000 --- a/doc/classes/SkeletonModification3DCCDIK.xml +++ /dev/null @@ -1,136 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DCCDIK" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that uses CCDIK to manipulate a series of bones to reach a target. - </brief_description> - <description> - This [SkeletonModification3D] uses an algorithm called Cyclic Coordinate Descent Inverse Kinematics, or CCDIK, to manipulate a chain of bones in a Skeleton so it reaches a defined target. - CCDIK works by rotating a set of bones, typically called a "bone chain", on a single axis. Each bone is rotated to face the target from the tip (by default), which over a chain of bones allow it to rotate properly to reach the target. Because the bones only rotate on a single axis, CCDIK [i]can[/i] look more robotic than other IK solvers. - [b]Note:[/b] The CCDIK modifier has [code]ccdik_joints[/code], which are the data objects that hold the data for each joint in the CCDIK chain. This is different from a bone! CCDIK joints hold the data needed for each bone in the bone chain used by CCDIK. - CCDIK also fully supports angle constraints, allowing for more control over how a solution is met. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_ccdik_joint_bone_index" qualifiers="const"> - <return type="int" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the bone index of the bone assigned to the CCDIK joint at [param joint_idx]. - </description> - </method> - <method name="get_ccdik_joint_bone_name" qualifiers="const"> - <return type="String" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the name of the bone that is assigned to the CCDIK joint at [param joint_idx]. - </description> - </method> - <method name="get_ccdik_joint_ccdik_axis" qualifiers="const"> - <return type="int" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the integer representing the joint axis of the CCDIK joint at [param joint_idx]. - </description> - </method> - <method name="get_ccdik_joint_constraint_angle_max" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the maximum angle constraint for the joint at [param joint_idx]. [b]Note:[/b] This angle is in degrees! - </description> - </method> - <method name="get_ccdik_joint_constraint_angle_min" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the minimum angle constraint for the joint at [param joint_idx]. [b]Note:[/b] This angle is in degrees! - </description> - </method> - <method name="get_ccdik_joint_constraint_invert" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns whether the CCDIK joint at [param joint_idx] uses an inverted joint constraint. See [method set_ccdik_joint_constraint_invert] for details. - </description> - </method> - <method name="get_ccdik_joint_enable_joint_constraint" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Enables angle constraints to the CCDIK joint at [param joint_idx]. - </description> - </method> - <method name="set_ccdik_joint_bone_index"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="bone_index" type="int" /> - <description> - Sets the bone index, [param bone_index], of the CCDIK joint at [param joint_idx]. When possible, this will also update the [code]bone_name[/code] of the CCDIK joint based on data provided by the linked skeleton. - </description> - </method> - <method name="set_ccdik_joint_bone_name"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="bone_name" type="String" /> - <description> - Sets the bone name, [param bone_name], of the CCDIK joint at [param joint_idx]. When possible, this will also update the [code]bone_index[/code] of the CCDIK joint based on data provided by the linked skeleton. - </description> - </method> - <method name="set_ccdik_joint_ccdik_axis"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="axis" type="int" /> - <description> - Sets the joint axis of the CCDIK joint at [param joint_idx] to the passed-in joint axis, [param axis]. - </description> - </method> - <method name="set_ccdik_joint_constraint_angle_max"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="max_angle" type="float" /> - <description> - Sets the maximum angle constraint for the joint at [param joint_idx]. [b]Note:[/b] This angle must be in radians! - </description> - </method> - <method name="set_ccdik_joint_constraint_angle_min"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="min_angle" type="float" /> - <description> - Sets the minimum angle constraint for the joint at [param joint_idx]. [b]Note:[/b] This angle must be in radians! - </description> - </method> - <method name="set_ccdik_joint_constraint_invert"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="invert" type="bool" /> - <description> - Sets whether the CCDIK joint at [param joint_idx] uses an inverted joint constraint. - An inverted joint constraint only constraints the CCDIK joint to the angles [i]outside of[/i] the inputted minimum and maximum angles. For this reason, it is referred to as an inverted joint constraint, as it constraints the joint to the outside of the inputted values. - </description> - </method> - <method name="set_ccdik_joint_enable_joint_constraint"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="enable" type="bool" /> - <description> - Sets whether joint constraints are enabled for the CCDIK joint at [param joint_idx]. - </description> - </method> - </methods> - <members> - <member name="ccdik_data_chain_length" type="int" setter="set_ccdik_data_chain_length" getter="get_ccdik_data_chain_length" default="0"> - The number of CCDIK joints in the CCDIK modification. - </member> - <member name="high_quality_solve" type="bool" setter="set_use_high_quality_solve" getter="get_use_high_quality_solve" default="true"> - When true, the CCDIK algorithm will perform a higher quality solve that returns more natural results. A high quality solve requires more computation power to solve though, and therefore can be disabled to save performance. - </member> - <member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath("")"> - The NodePath to the node that is the target for the CCDIK modification. This node is what the CCDIK chain will attempt to rotate the bone chain to. - </member> - <member name="tip_nodepath" type="NodePath" setter="set_tip_node" getter="get_tip_node" default="NodePath("")"> - The end position of the CCDIK chain. Typically, this should be a child of a [BoneAttachment3D] node attached to the final bone in the CCDIK chain, where the child node is offset so it is at the end of the final bone. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModification3DFABRIK.xml b/doc/classes/SkeletonModification3DFABRIK.xml deleted file mode 100644 index a2bec2b559..0000000000 --- a/doc/classes/SkeletonModification3DFABRIK.xml +++ /dev/null @@ -1,161 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DFABRIK" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that uses FABRIK to manipulate a series of bones to reach a target. - </brief_description> - <description> - This [SkeletonModification3D] uses an algorithm called Forward And Backward Reaching Inverse Kinematics, or FABRIK, to rotate a bone chain so that it reaches a target. - FABRIK works by knowing the positions and lengths of a series of bones, typically called a "bone chain". It first starts by running a forward pass, which places the final bone at the target's position. Then all other bones are moved towards the tip bone, so they stay at the defined bone length away. Then a backwards pass is performed, where the root/first bone in the FABRIK chain is placed back at the origin. then all other bones are moved so they stay at the defined bone length away. This positions the bone chain so that it reaches the target when possible, but all of the bones stay the correct length away from each other. - Because of how FABRIK works, it often gives more natural results than those seen in [SkeletonModification3DCCDIK], though FABRIK currently does not support joint constraints. - [b]Note:[/b] The FABRIK modifier has [code]fabrik_joints[/code], which are the data objects that hold the data for each joint in the FABRIK chain. This is different from a bone! FABRIK joints hold the data needed for each bone in the bone chain used by FABRIK. - To help control how the FABRIK joints move, a magnet vector can be passed, which can nudge the bones in a certain direction prior to solving, giving a level of control over the final result. - </description> - <tutorials> - </tutorials> - <methods> - <method name="fabrik_joint_auto_calculate_length"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Will attempt to automatically calculate the length of the bone assigned to the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_auto_calculate_length" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns a boolean that indicates whether this modification will attempt to autocalculate the length of the bone assigned to the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_bone_index" qualifiers="const"> - <return type="int" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the bone index of the bone assigned to the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_bone_name" qualifiers="const"> - <return type="String" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the name of the bone that is assigned to the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_length" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the length of the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_magnet" qualifiers="const"> - <return type="Vector3" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the magnet vector of the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="get_fabrik_joint_tip_node" qualifiers="const"> - <return type="NodePath" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the [Node3D]-based node placed at the tip of the FABRIK joint at [param joint_idx], if one has been set. - </description> - </method> - <method name="get_fabrik_joint_use_target_basis" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns a boolean indicating whether the FABRIK joint uses the target's [Basis] for its rotation. - [b]Note:[/b] This option is only available for the final bone in the FABRIK chain, with this setting being ignored for all other bones. - </description> - </method> - <method name="get_fabrik_joint_use_tip_node" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Sets the [Node3D]-based node that will be used as the tip of the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="set_fabrik_joint_auto_calculate_length"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="auto_calculate_length" type="bool" /> - <description> - When [code]true[/code], this modification will attempt to automatically calculate the length of the bone for the FABRIK joint at [param joint_idx]. It does this by either using the tip node assigned, if there is one assigned, or the distance the of the bone's children, if the bone has any. If the bone has no children and no tip node is assigned, then the modification [b]cannot[/b] autocalculate the joint's length. In this case, the joint length should be entered manually or a tip node assigned. - </description> - </method> - <method name="set_fabrik_joint_bone_index"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="bone_index" type="int" /> - <description> - Sets the bone index, [param bone_index], of the FABRIK joint at [param joint_idx]. When possible, this will also update the [code]bone_name[/code] of the FABRIK joint based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_fabrik_joint_bone_name"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="bone_name" type="String" /> - <description> - Sets the bone name, [param bone_name], of the FABRIK joint at [param joint_idx]. When possible, this will also update the [code]bone_index[/code] of the FABRIK joint based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_fabrik_joint_length"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="length" type="float" /> - <description> - Sets the joint length, [param length], of the FABRIK joint at [param joint_idx]. - </description> - </method> - <method name="set_fabrik_joint_magnet"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="magnet_position" type="Vector3" /> - <description> - Sets the magenet position to [param magnet_position] for the joint at [param joint_idx]. The magnet position is used to nudge the joint in that direction when solving, which gives some control over how that joint will bend when being solved. - </description> - </method> - <method name="set_fabrik_joint_tip_node"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="tip_node" type="NodePath" /> - <description> - Sets the nodepath of the FARIK joint at [param joint_idx] to [param tip_node]. The tip node is used to calculate the length of the FABRIK joint when set to automatically calculate joint length. - [b]Note:[/b] The tip node should generally be a child node of a [BoneAttachment3D] node attached to the bone that this FABRIK joint operates on, with the child node being offset so it is at the end of the bone. - </description> - </method> - <method name="set_fabrik_joint_use_target_basis"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="use_target_basis" type="bool" /> - <description> - Sets whether the FABRIK joint at [param joint_idx] uses the target's [Basis] for its rotation. - [b]Note:[/b] This option is only available for the final bone in the FABRIK chain, with this setting being ignored for all other bones. - </description> - </method> - <method name="set_fabrik_joint_use_tip_node"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="use_tip_node" type="bool" /> - <description> - Sets whether the tip node should be used when autocalculating the joint length for the FABRIK joint at [param joint_idx]. This will only work if there is a node assigned to the tip nodepath for this joint. - </description> - </method> - </methods> - <members> - <member name="chain_max_iterations" type="int" setter="set_chain_max_iterations" getter="get_chain_max_iterations" default="10"> - The number of times FABRIK will try to solve each time the [code]execute[/code] function is called. Setting this value to a lower number will be result in better performance, but this can also result in harsher movements and slower solves. - </member> - <member name="chain_tolerance" type="float" setter="set_chain_tolerance" getter="get_chain_tolerance" default="0.01"> - The minimum distance the target has to be from the tip of the final bone in the bone chain. Setting this value to a higher number allows for greater performance, but less accurate solves. - </member> - <member name="fabrik_data_chain_length" type="int" setter="set_fabrik_data_chain_length" getter="get_fabrik_data_chain_length" default="0"> - The amount of FABRIK joints in the FABRIK modification. - </member> - <member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath("")"> - The NodePath to the node that is the target for the FABRIK modification. This node is what the FABRIK chain will attempt to rotate the bone chain to. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModification3DJiggle.xml b/doc/classes/SkeletonModification3DJiggle.xml deleted file mode 100644 index 304f08bb20..0000000000 --- a/doc/classes/SkeletonModification3DJiggle.xml +++ /dev/null @@ -1,199 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DJiggle" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that jiggles bones as they move towards a target. - </brief_description> - <description> - This modification moves a series of bones, typically called a bone chain, towards a target. What makes this modification special is that it calculates the velocity and acceleration for each bone in the bone chain, and runs a very light physics-like calculation using the inputted values. This allows the bones to overshoot the target and "jiggle" around. It can be configured to act more like a spring, or sway around like cloth might. - This modification is useful for adding additional motion to things like hair, the edges of clothing, and more. It has several settings to that allow control over how the joint moves when the target moves. - [b]Note:[/b] The Jiggle modifier has [code]jiggle_joints[/code], which are the data objects that hold the data for each joint in the Jiggle chain. This is different from a bone! Jiggle joints hold the data needed for each bone in the bone chain used by the Jiggle modification. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_collision_mask" qualifiers="const"> - <return type="int" /> - <description> - Returns the collision mask that the Jiggle modifier will take into account when performing physics calculations. - </description> - </method> - <method name="get_jiggle_joint_bone_index" qualifiers="const"> - <return type="int" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the bone index of the bone assigned to the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="get_jiggle_joint_bone_name" qualifiers="const"> - <return type="String" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the name of the bone that is assigned to the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="get_jiggle_joint_damping" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the amount of dampening of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="get_jiggle_joint_gravity" qualifiers="const"> - <return type="Vector3" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns a [Vector3] representign the amount of gravity the Jiggle joint at [param joint_idx] is influenced by. - </description> - </method> - <method name="get_jiggle_joint_mass" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the amount of mass of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="get_jiggle_joint_override" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns a boolean that indicates whether the joint at [param joint_idx] is overriding the default jiggle joint data defined in the modification. - </description> - </method> - <method name="get_jiggle_joint_roll" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the amount of roll/twist applied to the bone that the Jiggle joint is applied to. - </description> - </method> - <method name="get_jiggle_joint_stiffness" qualifiers="const"> - <return type="float" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns the stiffness of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="get_jiggle_joint_use_gravity" qualifiers="const"> - <return type="bool" /> - <param index="0" name="joint_idx" type="int" /> - <description> - Returns a boolean that indicates whether the joint at [param joint_idx] is using gravity or not. - </description> - </method> - <method name="get_use_colliders" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the Jiggle modifier is taking physics colliders into account when solving. - </description> - </method> - <method name="set_collision_mask"> - <return type="void" /> - <param index="0" name="mask" type="int" /> - <description> - Sets the collision mask that the Jiggle modifier takes into account when performing physics calculations. - </description> - </method> - <method name="set_jiggle_joint_bone_index"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="bone_idx" type="int" /> - <description> - Sets the bone index, [param bone_idx], of the Jiggle joint at [param joint_idx]. When possible, this will also update the [code]bone_name[/code] of the Jiggle joint based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_jiggle_joint_bone_name"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="name" type="String" /> - <description> - Sets the bone name, [param name], of the Jiggle joint at [param joint_idx]. When possible, this will also update the [code]bone_index[/code] of the Jiggle joint based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_jiggle_joint_damping"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="damping" type="float" /> - <description> - Sets the amount of dampening of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="set_jiggle_joint_gravity"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="gravity" type="Vector3" /> - <description> - Sets the gravity vector of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="set_jiggle_joint_mass"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="mass" type="float" /> - <description> - Sets the of mass of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="set_jiggle_joint_override"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="override" type="bool" /> - <description> - Sets whether the Jiggle joint at [param joint_idx] should override the default Jiggle joint settings. Setting this to true will make the joint use its own settings rather than the default ones attached to the modification. - </description> - </method> - <method name="set_jiggle_joint_roll"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="roll" type="float" /> - <description> - Sets the amount of roll/twist on the bone the Jiggle joint is attached to. - </description> - </method> - <method name="set_jiggle_joint_stiffness"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="stiffness" type="float" /> - <description> - Sets the of stiffness of the Jiggle joint at [param joint_idx]. - </description> - </method> - <method name="set_jiggle_joint_use_gravity"> - <return type="void" /> - <param index="0" name="joint_idx" type="int" /> - <param index="1" name="use_gravity" type="bool" /> - <description> - Sets whether the Jiggle joint at [param joint_idx] should use gravity. - </description> - </method> - <method name="set_use_colliders"> - <return type="void" /> - <param index="0" name="use_colliders" type="bool" /> - <description> - When [code]true[/code], the Jiggle modifier will use raycasting to prevent the Jiggle joints from rotating themselves into collision objects when solving. - </description> - </method> - </methods> - <members> - <member name="damping" type="float" setter="set_damping" getter="get_damping" default="0.75"> - The default amount of dampening applied to the Jiggle joints, if they are not overridden. Higher values lead to more of the calculated velocity being applied. - </member> - <member name="gravity" type="Vector3" setter="set_gravity" getter="get_gravity" default="Vector3(0, -6, 0)"> - The default amount of gravity applied to the Jiggle joints, if they are not overridden. - </member> - <member name="jiggle_data_chain_length" type="int" setter="set_jiggle_data_chain_length" getter="get_jiggle_data_chain_length" default="0"> - The amount of Jiggle joints in the Jiggle modification. - </member> - <member name="mass" type="float" setter="set_mass" getter="get_mass" default="0.75"> - The default amount of mass assigned to the Jiggle joints, if they are not overridden. Higher values lead to faster movements and more overshooting. - </member> - <member name="stiffness" type="float" setter="set_stiffness" getter="get_stiffness" default="3.0"> - The default amount of stiffness assigned to the Jiggle joints, if they are not overridden. Higher values act more like springs, quickly moving into the correct position. - </member> - <member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath("")"> - The NodePath to the node that is the target for the Jiggle modification. This node is what the Jiggle chain will attempt to rotate the bone chain to. - </member> - <member name="use_gravity" type="bool" setter="set_use_gravity" getter="get_use_gravity" default="false"> - Whether the gravity vector, [member gravity], should be applied to the Jiggle joints, assuming they are not overriding the default settings. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModification3DLookAt.xml b/doc/classes/SkeletonModification3DLookAt.xml deleted file mode 100644 index aeed953ca9..0000000000 --- a/doc/classes/SkeletonModification3DLookAt.xml +++ /dev/null @@ -1,64 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DLookAt" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that rotates a bone to look at a target. - </brief_description> - <description> - This [SkeletonModification3D] rotates a bone to look a target. This is extremely helpful for moving character's heads to look at the player, rotating a turret to look at a target, or any other case where you want to make a bone rotate towards something quickly and easily. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_additional_rotation" qualifiers="const"> - <return type="Vector3" /> - <description> - Returns the amount of extra rotation that is applied to the bone after the LookAt modification executes. - </description> - </method> - <method name="get_lock_rotation_plane" qualifiers="const"> - <return type="int" /> - <description> - Returns the plane that the LookAt modification is limiting rotation to. - </description> - </method> - <method name="get_lock_rotation_to_plane" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the LookAt modification is limiting rotation to a single plane in 3D space. - </description> - </method> - <method name="set_additional_rotation"> - <return type="void" /> - <param index="0" name="additional_rotation" type="Vector3" /> - <description> - Sets the amount of extra rotation to be applied after the LookAt modification executes. This allows you to adjust the finished result. - </description> - </method> - <method name="set_lock_rotation_plane"> - <return type="void" /> - <param index="0" name="plane" type="int" /> - <description> - </description> - </method> - <method name="set_lock_rotation_to_plane"> - <return type="void" /> - <param index="0" name="lock_to_plane" type="bool" /> - <description> - When [code]true[/code], the LookAt modification will limit its rotation to a single plane in 3D space. The plane used can be configured using the [code]set_lock_rotation_plane[/code] function. - </description> - </method> - </methods> - <members> - <member name="bone_index" type="int" setter="set_bone_index" getter="get_bone_index" default="-2"> - The bone index of the bone that should be operated on by this modification. - When possible, this will also update the [member bone_name] based on data provided by the [Skeleton3D]. - </member> - <member name="bone_name" type="String" setter="set_bone_name" getter="get_bone_name" default=""""> - The name of the bone that should be operated on by this modification. - When possible, this will also update the [member bone_index] based on data provided by the [Skeleton3D]. - </member> - <member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath("")"> - The NodePath to the node that is the target for the modification. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModification3DStackHolder.xml b/doc/classes/SkeletonModification3DStackHolder.xml deleted file mode 100644 index 9448e2c783..0000000000 --- a/doc/classes/SkeletonModification3DStackHolder.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DStackHolder" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that holds and executes a [SkeletonModificationStack3D]. - </brief_description> - <description> - This [SkeletonModification3D] holds a reference to a [SkeletonModificationStack3D], allowing you to use multiple modification stacks on a single [Skeleton3D]. - [b]Note:[/b] The modifications in the held [SkeletonModificationStack3D] will only be executed if their execution mode matches the execution mode of the SkeletonModification3DStackHolder. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_held_modification_stack" qualifiers="const"> - <return type="SkeletonModificationStack3D" /> - <description> - Returns the [SkeletonModificationStack3D] that this modification is holding. - </description> - </method> - <method name="set_held_modification_stack"> - <return type="void" /> - <param index="0" name="held_modification_stack" type="SkeletonModificationStack3D" /> - <description> - Sets the [SkeletonModificationStack3D] that this modification is holding. This modification stack will then be executed when this modification is executed. - </description> - </method> - </methods> -</class> diff --git a/doc/classes/SkeletonModification3DTwoBoneIK.xml b/doc/classes/SkeletonModification3DTwoBoneIK.xml deleted file mode 100644 index 0e7ffd5c80..0000000000 --- a/doc/classes/SkeletonModification3DTwoBoneIK.xml +++ /dev/null @@ -1,191 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModification3DTwoBoneIK" inherits="SkeletonModification3D" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A modification that moves two bones to reach the target. - </brief_description> - <description> - This [SkeletonModification3D] uses an algorithm typically called TwoBoneIK. This algorithm works by leveraging the law of cosigns and the lengths of the bones to figure out what rotation the bones currently have, and what rotation they need to make a complete triangle, where the first bone, the second bone, and the target form the three vertices of the triangle. Because the algorithm works by making a triangle, it can only operate on two bones. - TwoBoneIK is great for arms, legs, and really any joints that can be represented by just two bones that bend to reach a target. This solver is more lightweight than [SkeletonModification3DFABRIK], but gives similar, natural looking results. - A [Node3D]-based node can be used to define the pole, or bend direction, allowing control over which direction the joint takes when bending to reach the target when the target is within reach. - </description> - <tutorials> - </tutorials> - <methods> - <method name="get_auto_calculate_joint_length" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the TwoBoneIK modification will attempt to autocalculate the lengths of the two bones. - </description> - </method> - <method name="get_joint_one_bone_idx" qualifiers="const"> - <return type="int" /> - <description> - Returns the bone index of the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_one_bone_name" qualifiers="const"> - <return type="String" /> - <description> - Returns the name of the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_one_length" qualifiers="const"> - <return type="float" /> - <description> - Returns the length of the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_one_roll" qualifiers="const"> - <return type="float" /> - <description> - Returns the amount of roll/twist applied to the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_two_bone_idx" qualifiers="const"> - <return type="int" /> - <description> - Returns the bone index of the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_two_bone_name" qualifiers="const"> - <return type="String" /> - <description> - Returns the name of the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_two_length" qualifiers="const"> - <return type="float" /> - <description> - Returns the length of the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_joint_two_roll" qualifiers="const"> - <return type="float" /> - <description> - Returns the amount of roll/twist applied to the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="get_pole_node" qualifiers="const"> - <return type="NodePath" /> - <description> - Returns the node that is being used as the pole node for the TwoBoneIK modification, if a pole node has been set. - </description> - </method> - <method name="get_tip_node" qualifiers="const"> - <return type="NodePath" /> - <description> - Returns the node that is being used to calculate the tip position of the second bone in the TwoBoneIK modification, if a tip node has been set. - </description> - </method> - <method name="get_use_pole_node" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the TwoBoneIK modification will attempt to use the pole node to figure out which direction to bend, if a pole node has been set. - </description> - </method> - <method name="get_use_tip_node" qualifiers="const"> - <return type="bool" /> - <description> - Returns whether the TwoBoneIK modification will attempt to use the tip node to figure out the length and position of the tip of the second bone. - </description> - </method> - <method name="set_auto_calculate_joint_length"> - <return type="void" /> - <param index="0" name="auto_calculate_joint_length" type="bool" /> - <description> - If true, the TwoBoneIK modification will attempt to autocalculate the lengths of the bones being used. The first bone will be calculated by using the distance from the origin of the first bone to the origin of the second bone. - The second bone will be calculated either using the tip node if that setting is enabled, or by using the distances of the second bone's children. If the tip node is not enabled and the bone has no children, then the length cannot be autocalculated. In this case, the length will either have to be manually inputted or a tip node used to calculate the length. - </description> - </method> - <method name="set_joint_one_bone_idx"> - <return type="void" /> - <param index="0" name="bone_idx" type="int" /> - <description> - Sets the bone index, [param bone_idx], of the first bone. When possible, this will also update the [code]bone_name[/code] of the first bone based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_joint_one_bone_name"> - <return type="void" /> - <param index="0" name="bone_name" type="String" /> - <description> - Sets the bone name, [param bone_name], of the first bone. When possible, this will also update the [code]bone_index[/code] of the first bone based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_joint_one_length"> - <return type="void" /> - <param index="0" name="bone_length" type="float" /> - <description> - Sets the length of the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="set_joint_one_roll"> - <return type="void" /> - <param index="0" name="roll" type="float" /> - <description> - Sets the amount of roll/twist applied to the first bone in the TwoBoneIK modification. - </description> - </method> - <method name="set_joint_two_bone_idx"> - <return type="void" /> - <param index="0" name="bone_idx" type="int" /> - <description> - Sets the bone index, [param bone_idx], of the second bone. When possible, this will also update the [code]bone_name[/code] of the second bone based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_joint_two_bone_name"> - <return type="void" /> - <param index="0" name="bone_name" type="String" /> - <description> - Sets the bone name, [param bone_name], of the second bone. When possible, this will also update the [code]bone_index[/code] of the second bone based on data provided by the [Skeleton3D]. - </description> - </method> - <method name="set_joint_two_length"> - <return type="void" /> - <param index="0" name="bone_length" type="float" /> - <description> - Sets the length of the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="set_joint_two_roll"> - <return type="void" /> - <param index="0" name="roll" type="float" /> - <description> - Sets the amount of roll/twist applied to the second bone in the TwoBoneIK modification. - </description> - </method> - <method name="set_pole_node"> - <return type="void" /> - <param index="0" name="pole_nodepath" type="NodePath" /> - <description> - Sets the node to be used as the for the pole of the TwoBoneIK. When a node is set and the modification is set to use the pole node, the TwoBoneIK modification will bend the nodes in the direction towards this node when the bones need to bend. - </description> - </method> - <method name="set_tip_node"> - <return type="void" /> - <param index="0" name="tip_nodepath" type="NodePath" /> - <description> - Sets the node to be used as the tip for the second bone. This is used to calculate the length and position of the end of the second bone in the TwoBoneIK modification. - [b]Note:[/b] The tip node should generally be a child node of a [BoneAttachment3D] node attached to the second bone, with the child node being offset so it is at the end of the bone. - </description> - </method> - <method name="set_use_pole_node"> - <return type="void" /> - <param index="0" name="use_pole_node" type="bool" /> - <description> - When [code]true[/code], the TwoBoneIK modification will bend the bones towards the pole node, if one has been set. This gives control over the direction the TwoBoneIK solver will bend, which is helpful for joints like elbows that only bend in certain directions. - </description> - </method> - <method name="set_use_tip_node"> - <return type="void" /> - <param index="0" name="use_tip_node" type="bool" /> - <description> - When [code]true[/code], the TwoBoneIK modification will use the tip node to calculate the distance and position of the end/tip of the second bone. This is the most stable solution for knowing the tip position and length of the second bone. - </description> - </method> - </methods> - <members> - <member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath("")"> - The NodePath to the node that is the target for the TwoBoneIK modification. This node is what the modification will attempt to rotate the bones to reach. - </member> - </members> -</class> diff --git a/doc/classes/SkeletonModificationStack3D.xml b/doc/classes/SkeletonModificationStack3D.xml deleted file mode 100644 index 9eaeeefd8e..0000000000 --- a/doc/classes/SkeletonModificationStack3D.xml +++ /dev/null @@ -1,88 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="SkeletonModificationStack3D" inherits="Resource" is_deprecated="true" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> - <brief_description> - A resource that holds a stack of [SkeletonModification3D]s. - </brief_description> - <description> - This resource is used by the Skeleton and holds a stack of [SkeletonModification3D]s. The SkeletonModificationStack3D controls the order of the modifications, which controls how they are applied. Modification order is especially important for full-body IK setups, as you need to execute the modifications in the correct order to get the desired results. For example, you want to execute a modification on the spine [i]before[/i] the arms on a humanoid skeleton. - Additionally, the SkeletonModificationStack3D also controls how strongly the modifications are applied to the [Skeleton3D] node. - </description> - <tutorials> - </tutorials> - <methods> - <method name="add_modification"> - <return type="void" /> - <param index="0" name="modification" type="SkeletonModification3D" /> - <description> - Adds the passed-in [SkeletonModification3D] to the stack. - </description> - </method> - <method name="delete_modification"> - <return type="void" /> - <param index="0" name="mod_idx" type="int" /> - <description> - Deletes the [SkeletonModification3D] at the index position [param mod_idx], if it exists. - </description> - </method> - <method name="enable_all_modifications"> - <return type="void" /> - <param index="0" name="enabled" type="bool" /> - <description> - Enables all [SkeletonModification3D]s in the stack. - </description> - </method> - <method name="execute"> - <return type="void" /> - <param index="0" name="delta" type="float" /> - <param index="1" name="execution_mode" type="int" /> - <description> - Executes all of the [SkeletonModification3D]s in the stack that use the same execution mode as the passed-in [param execution_mode], starting from index [code]0[/code] to [member modification_count]. - [b]Note:[/b] The order of the modifications can matter depending on the modifications. For example, modifications on a spine should operate before modifications on the arms in order to get proper results. - </description> - </method> - <method name="get_is_setup" qualifiers="const"> - <return type="bool" /> - <description> - Returns a boolean that indicates whether the modification stack is setup and can execute. - </description> - </method> - <method name="get_modification" qualifiers="const"> - <return type="SkeletonModification3D" /> - <param index="0" name="mod_idx" type="int" /> - <description> - Returns the [SkeletonModification3D] at the passed-in index, [param mod_idx]. - </description> - </method> - <method name="get_skeleton" qualifiers="const"> - <return type="Skeleton3D" /> - <description> - Returns the [Skeleton3D] node that the SkeletonModificationStack3D is bound to. - </description> - </method> - <method name="set_modification"> - <return type="void" /> - <param index="0" name="mod_idx" type="int" /> - <param index="1" name="modification" type="SkeletonModification3D" /> - <description> - Sets the modification at [param mod_idx] to the passed-in modification, [param modification]. - </description> - </method> - <method name="setup"> - <return type="void" /> - <description> - Sets up the modification stack so it can execute. This function should be called by [Skeleton3D] and shouldn't be called unless you know what you are doing. - </description> - </method> - </methods> - <members> - <member name="enabled" type="bool" setter="set_enabled" getter="get_enabled" default="false"> - When true, the modification's in the stack will be called. This is handled automatically through the [Skeleton3D] node. - </member> - <member name="modification_count" type="int" setter="set_modification_count" getter="get_modification_count" default="0"> - The number of modifications in the stack. - </member> - <member name="strength" type="float" setter="set_strength" getter="get_strength" default="1.0"> - The interpolation strength of the modifications in stack. A value of [code]0[/code] will make it where the modifications are not applied, a strength of [code]0.5[/code] will be half applied, and a strength of [code]1[/code] will allow the modifications to be fully applied and override the skeleton bone poses. - </member> - </members> -</class> diff --git a/doc/classes/TextureRect.xml b/doc/classes/TextureRect.xml index 348b4a5837..460ffbbb80 100644 --- a/doc/classes/TextureRect.xml +++ b/doc/classes/TextureRect.xml @@ -10,15 +10,15 @@ <link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link> </tutorials> <members> + <member name="expand_mode" type="int" setter="set_expand_mode" getter="get_expand_mode" enum="TextureRect.ExpandMode" default="0"> + Defines how minimum size is determined based on the texture's size. See [enum ExpandMode] for options. + </member> <member name="flip_h" type="bool" setter="set_flip_h" getter="is_flipped_h" default="false"> If [code]true[/code], texture is flipped horizontally. </member> <member name="flip_v" type="bool" setter="set_flip_v" getter="is_flipped_v" default="false"> If [code]true[/code], texture is flipped vertically. </member> - <member name="ignore_texture_size" type="bool" setter="set_ignore_texture_size" getter="get_ignore_texture_size" default="false"> - If [code]true[/code], the size of the texture won't be considered for minimum size calculation, so the [TextureRect] can be shrunk down past the texture size. Useful for preventing [TextureRect]s from breaking GUI layout regardless of their texture size. - </member> <member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" overrides="Control" enum="Control.MouseFilter" default="1" /> <member name="stretch_mode" type="int" setter="set_stretch_mode" getter="get_stretch_mode" enum="TextureRect.StretchMode" default="0"> Controls the texture's behavior when resizing the node's bounding rectangle. See [enum StretchMode]. @@ -28,6 +28,24 @@ </member> </members> <constants> + <constant name="EXPAND_KEEP_SIZE" value="0" enum="ExpandMode"> + The minimum size will be equal to texture size, i.e. [TextureRect] can't be smaller than the texture. + </constant> + <constant name="EXPAND_IGNORE_SIZE" value="1" enum="ExpandMode"> + The size of the texture won't be considered for minimum size calculation, so the [TextureRect] can be shrunk down past the texture size. + </constant> + <constant name="EXPAND_FIT_WIDTH" value="2" enum="ExpandMode"> + The height of the texture will be ignored. Minimum width will be equal to the current height. Useful for horizontal layouts, e.g. inside [HBoxContainer]. + </constant> + <constant name="EXPAND_FIT_WIDTH_PROPORTIONAL" value="3" enum="ExpandMode"> + Same as [constant EXPAND_FIT_WIDTH], but keeps texture's aspect ratio. + </constant> + <constant name="EXPAND_FIT_HEIGHT" value="4" enum="ExpandMode"> + The width of the texture will be ignored. Minimum height will be equal to the current width. Useful for vertical layouts, e.g. inside [VBoxContainer]. + </constant> + <constant name="EXPAND_FIT_HEIGHT_PROPORTIONAL" value="5" enum="ExpandMode"> + Same as [constant EXPAND_FIT_HEIGHT], but keeps texture's aspect ratio. + </constant> <constant name="STRETCH_SCALE" value="0" enum="StretchMode"> Scale to fit the node's bounding rectangle. </constant> diff --git a/doc/classes/Timer.xml b/doc/classes/Timer.xml index d171797e80..1b6c05284e 100644 --- a/doc/classes/Timer.xml +++ b/doc/classes/Timer.xml @@ -48,7 +48,7 @@ </member> <member name="time_left" type="float" setter="" getter="get_time_left"> The timer's remaining time in seconds. Returns 0 if the timer is inactive. - [b]Note:[/b] You cannot set this value. To change the timer's remaining time, use [method start]. + [b]Note:[/b] This value is read-only and cannot be set. It is based on [member wait_time], which can be set using [method start]. </member> <member name="wait_time" type="float" setter="set_wait_time" getter="get_wait_time" default="1.0"> The wait time in seconds. diff --git a/doc/classes/Tween.xml b/doc/classes/Tween.xml index eef35049e5..fc0dd9f05d 100644 --- a/doc/classes/Tween.xml +++ b/doc/classes/Tween.xml @@ -11,7 +11,7 @@ [codeblocks] [gdscript] var tween = get_tree().create_tween() - tween.tween_property($Sprite, "modulate", Color.red, 1) + tween.tween_property($Sprite, "modulate", Color.RED, 1) tween.tween_property($Sprite, "scale", Vector2(), 1) tween.tween_callback($Sprite.queue_free) [/gdscript] @@ -27,7 +27,7 @@ [codeblocks] [gdscript] var tween = get_tree().create_tween() - tween.tween_property($Sprite, "modulate", Color.red, 1).set_trans(Tween.TRANS_SINE) + tween.tween_property($Sprite, "modulate", Color.RED, 1).set_trans(Tween.TRANS_SINE) tween.tween_property($Sprite, "scale", Vector2(), 1).set_trans(Tween.TRANS_BOUNCE) tween.tween_callback($Sprite.queue_free) [/gdscript] @@ -42,7 +42,7 @@ [codeblocks] [gdscript] var tween = get_tree().create_tween().bind_node(self).set_trans(Tween.TRANS_ELASTIC) - tween.tween_property($Sprite, "modulate", Color.red, 1) + tween.tween_property($Sprite, "modulate", Color.RED, 1) tween.tween_property($Sprite, "scale", Vector2(), 1) tween.tween_callback($Sprite.queue_free) [/gdscript] @@ -288,8 +288,8 @@ [codeblocks] [gdscript] var tween = get_tree().create_tween() - tween.tween_callback($Sprite.set_modulate.bind(Color.red)).set_delay(2) - tween.tween_callback($Sprite.set_modulate.bind(Color.blue)).set_delay(2) + tween.tween_callback($Sprite.set_modulate.bind(Color.RED)).set_delay(2) + tween.tween_callback($Sprite.set_modulate.bind(Color.BLUE)).set_delay(2) [/gdscript] [csharp] Tween tween = GetTree().CreateTween(); diff --git a/doc/classes/VisualShaderNodeParticleRandomness.xml b/doc/classes/VisualShaderNodeParticleRandomness.xml index 574ba63ba9..233e072246 100644 --- a/doc/classes/VisualShaderNodeParticleRandomness.xml +++ b/doc/classes/VisualShaderNodeParticleRandomness.xml @@ -23,7 +23,10 @@ <constant name="OP_TYPE_VECTOR_3D" value="2" enum="OpType"> A 3D vector type. </constant> - <constant name="OP_TYPE_MAX" value="3" enum="OpType"> + <constant name="OP_TYPE_VECTOR_4D" value="3" enum="OpType"> + A 4D vector type. + </constant> + <constant name="OP_TYPE_MAX" value="4" enum="OpType"> Represents the size of the [enum OpType] enum. </constant> </constants> diff --git a/drivers/gles3/storage/material_storage.cpp b/drivers/gles3/storage/material_storage.cpp index e54fad1551..2d81771898 100644 --- a/drivers/gles3/storage/material_storage.cpp +++ b/drivers/gles3/storage/material_storage.cpp @@ -2765,6 +2765,14 @@ void MaterialStorage::material_free(RID p_rid) { Material *material = material_owner.get_or_null(p_rid); ERR_FAIL_COND(!material); + // Need to clear texture arrays to prevent spin locking of their RID's. + // This happens when the app is being closed. + for (KeyValue<StringName, Variant> &E : material->params) { + if (E.value.get_type() == Variant::ARRAY) { + Array(E.value).clear(); + } + } + material_set_shader(p_rid, RID()); //clean up shader material->dependency.deleted_notify(p_rid); diff --git a/drivers/gles3/storage/texture_storage.cpp b/drivers/gles3/storage/texture_storage.cpp index 2f0a253e46..489c328f64 100644 --- a/drivers/gles3/storage/texture_storage.cpp +++ b/drivers/gles3/storage/texture_storage.cpp @@ -300,6 +300,7 @@ Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, I r_real_format = p_format; bool need_decompress = false; + bool decompress_ra_to_rg = false; switch (p_format) { case Image::FORMAT_L8: { @@ -565,6 +566,28 @@ Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, I need_decompress = true; } } break; + case Image::FORMAT_ETC2_RA_AS_RG: { + if (config->etc2_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA8_ETC2_EAC; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + decompress_ra_to_rg = true; + } break; + case Image::FORMAT_DXT5_RA_AS_RG: { + if (config->s3tc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + decompress_ra_to_rg = true; + } break; default: { ERR_FAIL_V_MSG(Ref<Image>(), "Image Format: " + itos(p_format) + " is not supported by the OpenGL3 Renderer"); } @@ -575,7 +598,18 @@ Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, I image = image->duplicate(); image->decompress(); ERR_FAIL_COND_V(image->is_compressed(), image); + if (decompress_ra_to_rg) { + image->convert_ra_rgba8_to_rg(); + image->convert(Image::FORMAT_RG8); + } switch (image->get_format()) { + case Image::FORMAT_RG8: { + r_gl_format = GL_RG; + r_gl_internal_format = GL_RG8; + r_gl_type = GL_UNSIGNED_BYTE; + r_real_format = Image::FORMAT_RG8; + r_compressed = false; + } break; case Image::FORMAT_RGB8: { r_gl_format = GL_RGB; r_gl_internal_format = GL_RGB; @@ -597,7 +631,6 @@ Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, I r_gl_type = GL_UNSIGNED_BYTE; r_real_format = Image::FORMAT_RGBA8; r_compressed = false; - } break; } } @@ -1104,15 +1137,13 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image, texture->gl_set_filter(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST); texture->gl_set_repeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED); - //set swizle for older format compatibility -#ifdef GLES_OVER_GL switch (texture->format) { +#ifdef GLES_OVER_GL case Image::FORMAT_L8: { glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_RED); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ONE); - } break; case Image::FORMAT_LA8: { glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED); @@ -1120,15 +1151,27 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image, glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_GREEN); } break; +#endif + case Image::FORMAT_ETC2_RA_AS_RG: + case Image::FORMAT_DXT5_RA_AS_RG: { + glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED); + if (texture->format == real_format) { + // Swizzle RA from compressed texture into RG + glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_ALPHA); + } else { + // Converted textures are already in RG, leave as-is + glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_GREEN); + } + glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_ZERO); + glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ONE); + } break; default: { glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); - } break; } -#endif int mipmaps = img->has_mipmaps() ? img->get_mipmap_count() + 1 : 1; diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp index 2f3a78a689..c37b3d9c87 100644 --- a/drivers/unix/os_unix.cpp +++ b/drivers/unix/os_unix.cpp @@ -149,13 +149,9 @@ Vector<String> OS_Unix::get_video_adapter_driver_info() const { return Vector<String>(); } -String OS_Unix::get_stdin_string(bool p_block) { - if (p_block) { - char buff[1024]; - return String::utf8(fgets(buff, 1024, stdin)); - } - - return String(); +String OS_Unix::get_stdin_string() { + char buff[1024]; + return String::utf8(fgets(buff, 1024, stdin)); } Error OS_Unix::get_entropy(uint8_t *r_buffer, int p_bytes) { diff --git a/drivers/unix/os_unix.h b/drivers/unix/os_unix.h index 56c4d1747f..416311307c 100644 --- a/drivers/unix/os_unix.h +++ b/drivers/unix/os_unix.h @@ -51,7 +51,7 @@ public: virtual Vector<String> get_video_adapter_driver_info() const override; - virtual String get_stdin_string(bool p_block) override; + virtual String get_stdin_string() override; virtual Error get_entropy(uint8_t *r_buffer, int p_bytes) override; diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp index 6e701cb6bd..98fcde17c4 100644 --- a/editor/create_dialog.cpp +++ b/editor/create_dialog.cpp @@ -148,6 +148,11 @@ bool CreateDialog::_should_hide_type(const String &p_type) const { return true; } + StringName native_type = ScriptServer::get_global_class_native_base(p_type); + if (ClassDB::class_exists(native_type) && !ClassDB::can_instantiate(native_type)) { + return true; + } + String script_path = ScriptServer::get_global_class_path(p_type); if (script_path.begins_with("res://addons/")) { if (!EditorNode::get_singleton()->is_addon_plugin_enabled(script_path.get_slicec('/', 3))) { diff --git a/editor/debugger/editor_profiler.cpp b/editor/debugger/editor_profiler.cpp index 38934ae8a5..e4730faf38 100644 --- a/editor/debugger/editor_profiler.cpp +++ b/editor/debugger/editor_profiler.cpp @@ -670,7 +670,7 @@ EditorProfiler::EditorProfiler() { variables->connect("item_edited", callable_mp(this, &EditorProfiler::_item_edited)); graph = memnew(TextureRect); - graph->set_ignore_texture_size(true); + graph->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); graph->set_mouse_filter(MOUSE_FILTER_STOP); graph->connect("draw", callable_mp(this, &EditorProfiler::_graph_tex_draw)); graph->connect("gui_input", callable_mp(this, &EditorProfiler::_graph_tex_input)); diff --git a/editor/debugger/editor_visual_profiler.cpp b/editor/debugger/editor_visual_profiler.cpp index 91d9204863..1a06e85f90 100644 --- a/editor/debugger/editor_visual_profiler.cpp +++ b/editor/debugger/editor_visual_profiler.cpp @@ -798,7 +798,7 @@ EditorVisualProfiler::EditorVisualProfiler() { variables->connect("cell_selected", callable_mp(this, &EditorVisualProfiler::_item_selected)); graph = memnew(TextureRect); - graph->set_ignore_texture_size(true); + graph->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); graph->set_mouse_filter(MOUSE_FILTER_STOP); graph->connect("draw", callable_mp(this, &EditorVisualProfiler::_graph_tex_draw)); graph->connect("gui_input", callable_mp(this, &EditorVisualProfiler::_graph_tex_input)); diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index 12aa44891d..8723354e84 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -1361,38 +1361,22 @@ void EditorInspectorSection::_notification(int p_what) { } break; case NOTIFICATION_DRAG_BEGIN: { - Dictionary dd = get_viewport()->gui_get_drag_data(); - - // Only allow dropping if the section contains properties which can take the dragged data. - bool children_can_drop = false; - for (int child_idx = 0; child_idx < vbox->get_child_count(); child_idx++) { - Control *editor_property = Object::cast_to<Control>(vbox->get_child(child_idx)); - - // Test can_drop_data and can_drop_data_fw, since can_drop_data only works if set up with forwarding or if script attached. - if (editor_property && (editor_property->can_drop_data(Point2(), dd) || editor_property->call("_can_drop_data_fw", Point2(), dd, this))) { - children_can_drop = true; - break; - } - } - - dropping = children_can_drop; - queue_redraw(); + dropping_for_unfold = true; } break; case NOTIFICATION_DRAG_END: { - dropping = false; - queue_redraw(); + dropping_for_unfold = false; } break; case NOTIFICATION_MOUSE_ENTER: { - if (dropping) { + if (dropping || dropping_for_unfold) { dropping_unfold_timer->start(); } queue_redraw(); } break; case NOTIFICATION_MOUSE_EXIT: { - if (dropping) { + if (dropping || dropping_for_unfold) { dropping_unfold_timer->stop(); } queue_redraw(); diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index af8d1e6806..699a88e657 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -276,6 +276,7 @@ class EditorInspectorSection : public Container { Timer *dropping_unfold_timer = nullptr; bool dropping = false; + bool dropping_for_unfold = false; HashSet<StringName> revertable_properties; diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index ab79031ad2..b1b40eb52a 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -584,10 +584,11 @@ void EditorNode::_notification(int p_what) { case NOTIFICATION_ENTER_TREE: { Engine::get_singleton()->set_editor_hint(true); - Window *window = static_cast<Window *>(get_tree()->get_root()); + Window *window = get_window(); if (window) { // Handle macOS fullscreen and extend-to-title changes. window->connect("titlebar_changed", callable_mp(this, &EditorNode::_titlebar_resized)); + window->set_theme(theme); } OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/low_processor_mode_sleep_usec"))); @@ -608,6 +609,9 @@ void EditorNode::_notification(int p_what) { } break; case NOTIFICATION_EXIT_TREE: { + if (progress_dialog) { + progress_dialog->queue_free(); + } editor_data.save_editor_external_data(); FileAccess::set_file_close_fail_notify_callback(nullptr); log->deinit(); // Do not get messages anymore. @@ -688,9 +692,11 @@ void EditorNode::_notification(int p_what) { if (theme_changed) { theme = create_custom_theme(theme_base->get_theme()); + DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), SNAME("Editor"))); theme_base->set_theme(theme); gui_base->set_theme(theme); + get_window()->set_theme(theme); gui_base->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("Background"), SNAME("EditorStyles"))); scene_root_parent->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("Content"), SNAME("EditorStyles"))); @@ -4307,7 +4313,7 @@ bool EditorNode::is_object_of_custom_type(const Object *p_object, const StringNa void EditorNode::progress_add_task(const String &p_task, const String &p_label, int p_steps, bool p_can_cancel) { if (singleton->cmdline_export_mode) { print_line(p_task + ": begin: " + p_label + " steps: " + itos(p_steps)); - } else { + } else if (singleton->progress_dialog) { singleton->progress_dialog->add_task(p_task, p_label, p_steps, p_can_cancel); } } @@ -4316,15 +4322,17 @@ bool EditorNode::progress_task_step(const String &p_task, const String &p_state, if (singleton->cmdline_export_mode) { print_line("\t" + p_task + ": step " + itos(p_step) + ": " + p_state); return false; - } else { + } else if (singleton->progress_dialog) { return singleton->progress_dialog->task_step(p_task, p_state, p_step, p_force_refresh); + } else { + return false; } } void EditorNode::progress_end_task(const String &p_task) { if (singleton->cmdline_export_mode) { print_line(p_task + ": end"); - } else { + } else if (singleton->progress_dialog) { singleton->progress_dialog->end_task(p_task); } } @@ -6235,6 +6243,7 @@ EditorNode::EditorNode() { // Exporters might need the theme. EditorColorMap::create(); theme = create_custom_theme(); + DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), SNAME("Editor"))); register_exporters(); @@ -6289,7 +6298,6 @@ EditorNode::EditorNode() { resource_preview = memnew(EditorResourcePreview); add_child(resource_preview); progress_dialog = memnew(ProgressDialog); - gui_base->add_child(progress_dialog); // Take up all screen. gui_base->set_anchor(SIDE_RIGHT, Control::ANCHOR_END); diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp index 8ef394a59f..6c917a0c4f 100644 --- a/editor/editor_properties.cpp +++ b/editor/editor_properties.cpp @@ -4584,6 +4584,7 @@ EditorProperty *EditorInspectorDefaultPlugin::get_editor_for_property(Object *p_ return editor; } else { EditorPropertyDictionary *editor = memnew(EditorPropertyDictionary); + editor->setup(p_hint); return editor; } } break; diff --git a/editor/editor_properties_array_dict.cpp b/editor/editor_properties_array_dict.cpp index ed667aa7c8..069e80fc05 100644 --- a/editor/editor_properties_array_dict.cpp +++ b/editor/editor_properties_array_dict.cpp @@ -818,6 +818,10 @@ void EditorPropertyDictionary::_change_type_menu(int p_index) { update_property(); } +void EditorPropertyDictionary::setup(PropertyHint p_hint) { + property_hint = p_hint; +} + void EditorPropertyDictionary::update_property() { Variant updated_val = get_edited_object()->get(get_edited_property()); @@ -929,7 +933,13 @@ void EditorPropertyDictionary::update_property() { prop = editor; } break; case Variant::STRING: { - prop = memnew(EditorPropertyText); + if (i != amount && property_hint == PROPERTY_HINT_MULTILINE_TEXT) { + // If this is NOT the new key field and there's a multiline hint, + // show the field as multiline + prop = memnew(EditorPropertyMultilineText); + } else { + prop = memnew(EditorPropertyText); + } } break; diff --git a/editor/editor_properties_array_dict.h b/editor/editor_properties_array_dict.h index 96fc2dce24..73a16e3687 100644 --- a/editor/editor_properties_array_dict.h +++ b/editor/editor_properties_array_dict.h @@ -154,6 +154,7 @@ class EditorPropertyDictionary : public EditorProperty { EditorSpinSlider *size_sliderv = nullptr; Button *button_add_item = nullptr; EditorPaginator *paginator = nullptr; + PropertyHint property_hint; void _page_changed(int p_page); void _edit_pressed(); @@ -169,6 +170,7 @@ protected: void _notification(int p_what); public: + void setup(PropertyHint p_hint); virtual void update_property() override; EditorPropertyDictionary(); }; diff --git a/editor/editor_property_name_processor.cpp b/editor/editor_property_name_processor.cpp index 195457c239..18ba19f5f6 100644 --- a/editor/editor_property_name_processor.cpp +++ b/editor/editor_property_name_processor.cpp @@ -211,6 +211,7 @@ EditorPropertyNameProcessor::EditorPropertyNameProcessor() { capitalize_string_remaps["rmb"] = "RMB"; capitalize_string_remaps["rpc"] = "RPC"; capitalize_string_remaps["s3tc"] = "S3TC"; + capitalize_string_remaps["scp"] = "SCP"; capitalize_string_remaps["sdf"] = "SDF"; capitalize_string_remaps["sdfgi"] = "SDFGI"; capitalize_string_remaps["sdk"] = "SDK"; diff --git a/editor/editor_resource_picker.cpp b/editor/editor_resource_picker.cpp index 6b733e11f7..81b2fff97a 100644 --- a/editor/editor_resource_picker.cpp +++ b/editor/editor_resource_picker.cpp @@ -958,7 +958,7 @@ EditorResourcePicker::EditorResourcePicker(bool p_hide_assign_button_controls) { if (!p_hide_assign_button_controls) { preview_rect = memnew(TextureRect); - preview_rect->set_ignore_texture_size(true); + preview_rect->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); preview_rect->set_anchors_and_offsets_preset(PRESET_FULL_RECT); preview_rect->set_offset(SIDE_TOP, 1); preview_rect->set_offset(SIDE_BOTTOM, -1); diff --git a/editor/editor_run_native.cpp b/editor/editor_run_native.cpp index b0eb4c3d55..eab4e08cec 100644 --- a/editor/editor_run_native.cpp +++ b/editor/editor_run_native.cpp @@ -154,7 +154,9 @@ Error EditorRunNative::run_native(int p_idx, int p_platform) { Error err = eep->run(preset, p_idx, flags); result_dialog_log->clear(); if (eep->fill_log_messages(result_dialog_log, err)) { - result_dialog->popup_centered_ratio(0.5); + if (eep->get_worst_message_type() >= EditorExportPlatform::EXPORT_MESSAGE_ERROR) { + result_dialog->popup_centered_ratio(0.5); + } } return err; } diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp index ea03b1c744..177266e366 100644 --- a/editor/editor_spin_slider.cpp +++ b/editor/editor_spin_slider.cpp @@ -253,6 +253,12 @@ void EditorSpinSlider::_value_input_gui_input(const Ref<InputEvent> &p_event) { value_input_dirty = true; set_process_internal(true); } break; + case Key::ESCAPE: { + value_input_closed_frame = Engine::get_singleton()->get_frames_drawn(); + if (value_input_popup) { + value_input_popup->hide(); + } + } break; default: break; } @@ -479,10 +485,10 @@ void EditorSpinSlider::_notification(int p_what) { } break; case NOTIFICATION_FOCUS_ENTER: { - if ((Input::get_singleton()->is_action_pressed("ui_focus_next") || Input::get_singleton()->is_action_pressed("ui_focus_prev")) && !value_input_just_closed) { + if ((Input::get_singleton()->is_action_pressed("ui_focus_next") || Input::get_singleton()->is_action_pressed("ui_focus_prev")) && value_input_closed_frame != Engine::get_singleton()->get_frames_drawn()) { _focus_entered(); } - value_input_just_closed = false; + value_input_closed_frame = 0; } break; } } @@ -553,7 +559,7 @@ void EditorSpinSlider::_evaluate_input_text() { //text_submitted signal void EditorSpinSlider::_value_input_submitted(const String &p_text) { - value_input_just_closed = true; + value_input_closed_frame = Engine::get_singleton()->get_frames_drawn(); if (value_input_popup) { value_input_popup->hide(); } @@ -562,7 +568,7 @@ void EditorSpinSlider::_value_input_submitted(const String &p_text) { //modal_closed signal void EditorSpinSlider::_value_input_closed() { _evaluate_input_text(); - value_input_just_closed = true; + value_input_closed_frame = Engine::get_singleton()->get_frames_drawn(); } //focus_exited signal @@ -578,7 +584,7 @@ void EditorSpinSlider::_value_focus_exited() { // -> TAB was pressed // -> modal_close was not called // -> need to close/hide manually - if (!value_input_just_closed) { //value_input_just_closed should do the same + if (value_input_closed_frame != Engine::get_singleton()->get_frames_drawn()) { if (value_input_popup) { value_input_popup->hide(); } @@ -672,6 +678,7 @@ void EditorSpinSlider::_ensure_input_popup() { add_child(value_input_popup); value_input = memnew(LineEdit); + value_input->set_focus_mode(FOCUS_CLICK); value_input_popup->add_child(value_input); value_input->set_anchors_and_offsets_preset(PRESET_FULL_RECT); value_input_popup->connect("hidden", callable_mp(this, &EditorSpinSlider::_value_input_closed)); diff --git a/editor/editor_spin_slider.h b/editor/editor_spin_slider.h index 99eb953166..a4d810b18b 100644 --- a/editor/editor_spin_slider.h +++ b/editor/editor_spin_slider.h @@ -65,7 +65,7 @@ class EditorSpinSlider : public Range { Control *value_input_popup = nullptr; LineEdit *value_input = nullptr; - bool value_input_just_closed = false; + uint64_t value_input_closed_frame = 0; bool value_input_dirty = false; bool hide_slider = false; diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index d8252bed9c..7a880d2ab3 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -753,6 +753,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { // Editor background Color background_color_opaque = background_color; background_color_opaque.a = 1.0; + theme->set_color("background", "Editor", background_color_opaque); theme->set_stylebox("Background", "EditorStyles", make_flat_stylebox(background_color_opaque, default_margin_size, default_margin_size, default_margin_size, default_margin_size)); // Focus diff --git a/editor/export/editor_export.cpp b/editor/export/editor_export.cpp index f48cabf207..cc96107f97 100644 --- a/editor/export/editor_export.cpp +++ b/editor/export/editor_export.cpp @@ -170,6 +170,12 @@ void EditorExport::_notification(int p_what) { case NOTIFICATION_PROCESS: { update_export_presets(); } break; + + case NOTIFICATION_EXIT_TREE: { + for (int i = 0; i < export_platforms.size(); i++) { + export_platforms.write[i]->cleanup(); + } + } break; } } diff --git a/editor/export/editor_export_platform.cpp b/editor/export/editor_export_platform.cpp index 028071ff62..6478f99fb1 100644 --- a/editor/export/editor_export_platform.cpp +++ b/editor/export/editor_export_platform.cpp @@ -444,8 +444,10 @@ HashSet<String> EditorExportPlatform::get_features(const Ref<EditorExportPreset> result.insert("template"); if (p_debug) { + result.insert("debug"); result.insert("template_debug"); } else { + result.insert("release"); result.insert("template_release"); } @@ -1320,6 +1322,121 @@ Error EditorExportPlatform::_add_shared_object(void *p_userdata, const SharedObj return OK; } +void EditorExportPlatform::zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name) { + String dir = p_folder.is_empty() ? p_root_path : p_root_path.path_join(p_folder); + + Ref<DirAccess> da = DirAccess::open(dir); + da->list_dir_begin(); + String f = da->get_next(); + while (!f.is_empty()) { + if (f == "." || f == "..") { + f = da->get_next(); + continue; + } + if (da->is_link(f)) { + OS::DateTime dt = OS::get_singleton()->get_datetime(); + + zip_fileinfo zipfi; + zipfi.tmz_date.tm_year = dt.year; + zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ + zipfi.tmz_date.tm_mday = dt.day; + zipfi.tmz_date.tm_hour = dt.hour; + zipfi.tmz_date.tm_min = dt.minute; + zipfi.tmz_date.tm_sec = dt.second; + zipfi.dosDate = 0; + // 0120000: symbolic link type + // 0000755: permissions rwxr-xr-x + // 0000644: permissions rw-r--r-- + uint32_t _mode = 0120644; + zipfi.external_fa = (_mode << 16L) | !(_mode & 0200); + zipfi.internal_fa = 0; + + zipOpenNewFileInZip4(p_zip, + p_folder.path_join(f).utf8().get_data(), + &zipfi, + nullptr, + 0, + nullptr, + 0, + nullptr, + Z_DEFLATED, + Z_DEFAULT_COMPRESSION, + 0, + -MAX_WBITS, + DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, + nullptr, + 0, + 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions + 0); + + String target = da->read_link(f); + zipWriteInFileInZip(p_zip, target.utf8().get_data(), target.utf8().size()); + zipCloseFileInZip(p_zip); + } else if (da->current_is_dir()) { + zip_folder_recursive(p_zip, p_root_path, p_folder.path_join(f), p_pkg_name); + } else { + bool _is_executable = is_executable(dir.path_join(f)); + + OS::DateTime dt = OS::get_singleton()->get_datetime(); + + zip_fileinfo zipfi; + zipfi.tmz_date.tm_year = dt.year; + zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ + zipfi.tmz_date.tm_mday = dt.day; + zipfi.tmz_date.tm_hour = dt.hour; + zipfi.tmz_date.tm_min = dt.minute; + zipfi.tmz_date.tm_sec = dt.second; + zipfi.dosDate = 0; + // 0100000: regular file type + // 0000755: permissions rwxr-xr-x + // 0000644: permissions rw-r--r-- + uint32_t _mode = (_is_executable ? 0100755 : 0100644); + zipfi.external_fa = (_mode << 16L) | !(_mode & 0200); + zipfi.internal_fa = 0; + + zipOpenNewFileInZip4(p_zip, + p_folder.path_join(f).utf8().get_data(), + &zipfi, + nullptr, + 0, + nullptr, + 0, + nullptr, + Z_DEFLATED, + Z_DEFAULT_COMPRESSION, + 0, + -MAX_WBITS, + DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, + nullptr, + 0, + 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions + 0); + + Ref<FileAccess> fa = FileAccess::open(dir.path_join(f), FileAccess::READ); + if (fa.is_null()) { + add_message(EXPORT_MESSAGE_ERROR, TTR("ZIP Creation"), vformat(TTR("Could not open file to read from path \"%s\"."), dir.path_join(f))); + return; + } + const int bufsize = 16384; + uint8_t buf[bufsize]; + + while (true) { + uint64_t got = fa->get_buffer(buf, bufsize); + if (got == 0) { + break; + } + zipWriteInFileInZip(p_zip, buf, got); + } + + zipCloseFileInZip(p_zip); + } + f = da->get_next(); + } + da->list_dir_end(); +} + Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, bool p_embed, int64_t *r_embedded_start, int64_t *r_embedded_size) { EditorProgress ep("savepack", TTR("Packing"), 102, true); @@ -1640,5 +1757,123 @@ bool EditorExportPlatform::can_export(const Ref<EditorExportPreset> &p_preset, S return valid; } +Error EditorExportPlatform::ssh_run_on_remote(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, String *r_out, int p_port_fwd) const { + String ssh_path = EditorSettings::get_singleton()->get("export/ssh/ssh"); + if (ssh_path.is_empty()) { + ssh_path = "ssh"; + } + + List<String> args; + args.push_back("-p"); + args.push_back(p_port); + for (const String &E : p_ssh_args) { + args.push_back(E); + } + if (p_port_fwd > 0) { + args.push_back("-R"); + args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd)); + } + args.push_back(p_host); + args.push_back(p_cmd_args); + + String out; + int exit_code = -1; + + if (OS::get_singleton()->is_stdout_verbose()) { + OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data()); + for (const String &arg : args) { + OS::get_singleton()->print(" %s", arg.utf8().get_data()); + } + OS::get_singleton()->print("\n"); + } + + Error err = OS::get_singleton()->execute(ssh_path, args, &out, &exit_code, true); + if (out.is_empty()) { + print_verbose(vformat("Exit code: %d", exit_code)); + } else { + print_verbose(vformat("Exit code: %d, Output: %s", exit_code, out.replace("\r\n", "\n"))); + } + if (r_out) { + *r_out = out.replace("\r\n", "\n").get_slice("\n", 0); + } + if (err != OK) { + return err; + } else if (exit_code != 0) { + if (!out.is_empty()) { + print_line(out); + } + return FAILED; + } + return OK; +} + +Error EditorExportPlatform::ssh_run_on_remote_no_wait(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, OS::ProcessID *r_pid, int p_port_fwd) const { + String ssh_path = EditorSettings::get_singleton()->get("export/ssh/ssh"); + if (ssh_path.is_empty()) { + ssh_path = "ssh"; + } + + List<String> args; + args.push_back("-p"); + args.push_back(p_port); + for (const String &E : p_ssh_args) { + args.push_back(E); + } + if (p_port_fwd > 0) { + args.push_back("-R"); + args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd)); + } + args.push_back(p_host); + args.push_back(p_cmd_args); + + if (OS::get_singleton()->is_stdout_verbose()) { + OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data()); + for (const String &arg : args) { + OS::get_singleton()->print(" %s", arg.utf8().get_data()); + } + OS::get_singleton()->print("\n"); + } + + return OS::get_singleton()->create_process(ssh_path, args, r_pid); +} + +Error EditorExportPlatform::ssh_push_to_remote(const String &p_host, const String &p_port, const Vector<String> &p_scp_args, const String &p_src_file, const String &p_dst_file) const { + String scp_path = EditorSettings::get_singleton()->get("export/ssh/scp"); + if (scp_path.is_empty()) { + scp_path = "scp"; + } + + List<String> args; + args.push_back("-P"); + args.push_back(p_port); + for (const String &E : p_scp_args) { + args.push_back(E); + } + args.push_back(p_src_file); + args.push_back(vformat("%s:%s", p_host, p_dst_file)); + + String out; + int exit_code = -1; + + if (OS::get_singleton()->is_stdout_verbose()) { + OS::get_singleton()->print("Executing: %s", scp_path.utf8().get_data()); + for (const String &arg : args) { + OS::get_singleton()->print(" %s", arg.utf8().get_data()); + } + OS::get_singleton()->print("\n"); + } + + Error err = OS::get_singleton()->execute(scp_path, args, &out, &exit_code, true); + if (err != OK) { + return err; + } else if (exit_code != 0) { + if (!out.is_empty()) { + print_line(out); + } + return FAILED; + } + return OK; +} + EditorExportPlatform::EditorExportPlatform() { } diff --git a/editor/export/editor_export_platform.h b/editor/export/editor_export_platform.h index d3d8a8f186..1fb35759ac 100644 --- a/editor/export/editor_export_platform.h +++ b/editor/export/editor_export_platform.h @@ -35,6 +35,7 @@ class EditorFileSystemDirectory; struct EditorProgress; #include "core/io/dir_access.h" +#include "core/io/zip_io.h" #include "editor_export_preset.h" #include "editor_export_shared_object.h" #include "scene/gui/rich_text_label.h" @@ -92,7 +93,6 @@ private: void _export_find_resources(EditorFileSystemDirectory *p_dir, HashSet<String> &p_paths); void _export_find_dependencies(const String &p_path, HashSet<String> &p_paths); - void gen_debug_flags(Vector<String> &r_flags, int p_flags); static Error _save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); static Error _save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); @@ -126,6 +126,13 @@ protected: bool exists_export_template(String template_file_name, String *err) const; String find_export_template(String template_file_name, String *err = nullptr) const; void gen_export_flags(Vector<String> &r_flags, int p_flags); + void gen_debug_flags(Vector<String> &r_flags, int p_flags); + + virtual void zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name); + + Error ssh_run_on_remote(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, String *r_out = nullptr, int p_port_fwd = -1) const; + Error ssh_run_on_remote_no_wait(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, OS::ProcessID *r_pid = nullptr, int p_port_fwd = -1) const; + Error ssh_push_to_remote(const String &p_host, const String &p_port, const Vector<String> &p_scp_args, const String &p_src_file, const String &p_dst_file) const; public: virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const = 0; @@ -215,6 +222,7 @@ public: DEBUG_FLAG_VIEW_NAVIGATION = 16, }; + virtual void cleanup() {} virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) { return OK; } virtual Ref<Texture2D> get_run_icon() const { return get_logo(); } diff --git a/editor/export/editor_export_platform_pc.h b/editor/export/editor_export_platform_pc.h index c71a62ee5c..8c24f2fc68 100644 --- a/editor/export/editor_export_platform_pc.h +++ b/editor/export/editor_export_platform_pc.h @@ -62,7 +62,6 @@ public: virtual Error modify_template(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) { return OK; }; virtual Error export_project_data(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags); - void set_extension(const String &p_extension, const String &p_feature_key = "default"); void set_name(const String &p_name); void set_os_name(const String &p_name); diff --git a/editor/export/editor_export_plugin.cpp b/editor/export/editor_export_plugin.cpp index f34ebfa541..784dbc116a 100644 --- a/editor/export/editor_export_plugin.cpp +++ b/editor/export/editor_export_plugin.cpp @@ -34,6 +34,7 @@ #include "core/io/dir_access.h" #include "core/io/file_access.h" #include "editor/editor_paths.h" +#include "editor/editor_settings.h" #include "editor/export/editor_export_platform.h" #include "scene/resources/resource_format_text.h" @@ -226,4 +227,8 @@ void EditorExportPlugin::_bind_methods() { } EditorExportPlugin::EditorExportPlugin() { + GLOBAL_DEF("editor/export/convert_text_resources_to_binary", false); + + EDITOR_DEF("export/ssh/ssh", ""); + EDITOR_DEF("export/ssh/scp", ""); } diff --git a/editor/import/resource_importer_obj.cpp b/editor/import/resource_importer_obj.cpp index a67da0c2b1..f1fd1d5a03 100644 --- a/editor/import/resource_importer_obj.cpp +++ b/editor/import/resource_importer_obj.cpp @@ -217,6 +217,7 @@ static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_ Vector<Vector3> vertices; Vector<Vector3> normals; Vector<Vector2> uvs; + Vector<Color> colors; String name; HashMap<String, HashMap<String, Ref<StandardMaterial3D>>> material_map; @@ -249,6 +250,19 @@ static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_ vtx.y = v[2].to_float() * scale_mesh.y + offset_mesh.y; vtx.z = v[3].to_float() * scale_mesh.z + offset_mesh.z; vertices.push_back(vtx); + //vertex color + if (v.size() == 7) { + while (colors.size() < vertices.size() - 1) { + colors.push_back(Color(1.0, 1.0, 1.0)); + } + Color c; + c.r = v[4].to_float(); + c.g = v[5].to_float(); + c.b = v[6].to_float(); + colors.push_back(c); + } else if (!colors.is_empty()) { + colors.push_back(Color(1.0, 1.0, 1.0)); + } } else if (l.begins_with("vt ")) { //uv Vector<String> v = l.split(" ", false); @@ -317,6 +331,9 @@ static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_ ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT); Vector3 vertex = vertices[vtx]; + if (!colors.is_empty()) { + surf_tool->set_color(colors[vtx]); + } if (!smoothing) { smooth_group++; } @@ -356,7 +373,11 @@ static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_ print_verbose("OBJ: Current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material))); if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) { - surf_tool->set_material(material_map[current_material_library][current_material]); + Ref<StandardMaterial3D> &material = material_map[current_material_library][current_material]; + if (!colors.is_empty()) { + material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); + } + surf_tool->set_material(material); } mesh = surf_tool->commit(mesh, mesh_flags); diff --git a/editor/import/resource_importer_shader_file.cpp b/editor/import/resource_importer_shader_file.cpp index 7187e85df0..ba48fc9029 100644 --- a/editor/import/resource_importer_shader_file.cpp +++ b/editor/import/resource_importer_shader_file.cpp @@ -91,6 +91,7 @@ static String _include_function(const String &p_path, void *userpointer) { Error ResourceImporterShaderFile::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) { /* STEP 1, Read shader code */ + ERR_FAIL_COND_V_EDMSG((OS::get_singleton()->get_current_rendering_method() == "gl_compatibility"), ERR_UNAVAILABLE, "Cannot import custom .glsl shaders when using the gl_compatibility rendering_method. Please switch to the forward_plus or mobile rendering methods to use custom shaders."); Error err; Ref<FileAccess> file = FileAccess::open(p_source_file, FileAccess::READ, &err); diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp index ec3eb1a494..ddd6ac728f 100644 --- a/editor/plugins/animation_player_editor_plugin.cpp +++ b/editor/plugins/animation_player_editor_plugin.cpp @@ -94,6 +94,7 @@ void AnimationPlayerEditor::_notification(int p_what) { // Need the last frame after it stopped. frame->set_value(player->get_current_animation_position()); track_editor->set_anim_pos(player->get_current_animation_position()); + stop->set_icon(stop_icon); } last_active = player->is_playing(); @@ -119,8 +120,15 @@ void AnimationPlayerEditor::_notification(int p_what) { case NOTIFICATION_TRANSLATION_CHANGED: case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: case NOTIFICATION_THEME_CHANGED: { - autoplay->set_icon(get_theme_icon(SNAME("AutoPlay"), SNAME("EditorIcons"))); + stop_icon = get_theme_icon(SNAME("Stop"), SNAME("EditorIcons")); + pause_icon = get_theme_icon(SNAME("Pause"), SNAME("EditorIcons")); + if (player && player->is_playing()) { + stop->set_icon(pause_icon); + } else { + stop->set_icon(stop_icon); + } + autoplay->set_icon(get_theme_icon(SNAME("AutoPlay"), SNAME("EditorIcons"))); play->set_icon(get_theme_icon(SNAME("PlayStart"), SNAME("EditorIcons"))); play_from->set_icon(get_theme_icon(SNAME("Play"), SNAME("EditorIcons"))); play_bw->set_icon(get_theme_icon(SNAME("PlayStartBackwards"), SNAME("EditorIcons"))); @@ -137,7 +145,6 @@ void AnimationPlayerEditor::_notification(int p_what) { autoplay_reset_img->blit_rect(reset_img, Rect2i(Point2i(), icon_size), Point2i(icon_size.x, 0)); autoplay_reset_icon = ImageTexture::create_from_image(autoplay_reset_img); } - stop->set_icon(get_theme_icon(SNAME("Stop"), SNAME("EditorIcons"))); onion_toggle->set_icon(get_theme_icon(SNAME("Onion"), SNAME("EditorIcons"))); onion_skinning->set_icon(get_theme_icon(SNAME("GuiTabMenuHl"), SNAME("EditorIcons"))); @@ -204,7 +211,7 @@ void AnimationPlayerEditor::_play_pressed() { } //unstop - stop->set_pressed(false); + stop->set_icon(pause_icon); } void AnimationPlayerEditor::_play_from_pressed() { @@ -221,7 +228,7 @@ void AnimationPlayerEditor::_play_from_pressed() { } //unstop - stop->set_pressed(false); + stop->set_icon(pause_icon); } String AnimationPlayerEditor::_get_current() const { @@ -242,7 +249,7 @@ void AnimationPlayerEditor::_play_bw_pressed() { } //unstop - stop->set_pressed(false); + stop->set_icon(pause_icon); } void AnimationPlayerEditor::_play_bw_from_pressed() { @@ -259,7 +266,7 @@ void AnimationPlayerEditor::_play_bw_from_pressed() { } //unstop - stop->set_pressed(false); + stop->set_icon(pause_icon); } void AnimationPlayerEditor::_stop_pressed() { @@ -267,9 +274,16 @@ void AnimationPlayerEditor::_stop_pressed() { return; } - player->stop(false); - play->set_pressed(false); - stop->set_pressed(true); + if (player->is_playing()) { + player->pause(); + } else { + String current = _get_current(); + player->stop(); + player->set_assigned_animation(current); + frame->set_value(0); + track_editor->set_anim_pos(0); + } + stop->set_icon(stop_icon); } void AnimationPlayerEditor::_animation_selected(int p_which) { @@ -798,12 +812,9 @@ void AnimationPlayerEditor::_update_animation() { updating = true; if (player->is_playing()) { - play->set_pressed(true); - stop->set_pressed(false); - + stop->set_icon(pause_icon); } else { - play->set_pressed(false); - stop->set_pressed(true); + stop->set_icon(stop_icon); } scale->set_text(String::num(player->get_speed_scale(), 2)); @@ -1155,7 +1166,7 @@ void AnimationPlayerEditor::_seek_value_changed(float p_value, bool p_set, bool player->seek_delta(pos, pos - cpos); } else { - player->stop(true); + player->stop(); player->seek(pos, true); } } @@ -1663,7 +1674,6 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug stop = memnew(Button); stop->set_flat(true); - stop->set_toggle_mode(true); hb->add_child(stop); stop->set_tooltip_text(TTR("Stop animation playback. (S)")); diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h index 6c690c812c..327200506f 100644 --- a/editor/plugins/animation_player_editor_plugin.h +++ b/editor/plugins/animation_player_editor_plugin.h @@ -101,6 +101,8 @@ class AnimationPlayerEditor : public VBoxContainer { OptionButton *library = nullptr; Label *name_title = nullptr; + Ref<Texture2D> stop_icon; + Ref<Texture2D> pause_icon; Ref<Texture2D> autoplay_icon; Ref<Texture2D> reset_icon; Ref<ImageTexture> autoplay_reset_icon; diff --git a/editor/plugins/asset_library_editor_plugin.cpp b/editor/plugins/asset_library_editor_plugin.cpp index c2dac83416..9f2cfc8d9c 100644 --- a/editor/plugins/asset_library_editor_plugin.cpp +++ b/editor/plugins/asset_library_editor_plugin.cpp @@ -293,7 +293,7 @@ EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() { preview = memnew(TextureRect); previews_vbox->add_child(preview); - preview->set_ignore_texture_size(true); + preview->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); preview->set_custom_minimum_size(Size2(640 * EDSCALE, 345 * EDSCALE)); preview->set_v_size_flags(Control::SIZE_EXPAND_FILL); diff --git a/editor/plugins/bone_map_editor_plugin.cpp b/editor/plugins/bone_map_editor_plugin.cpp index dfcf9256c4..c913a9b0ab 100644 --- a/editor/plugins/bone_map_editor_plugin.cpp +++ b/editor/plugins/bone_map_editor_plugin.cpp @@ -316,7 +316,7 @@ void BoneMapper::create_editor() { profile_texture = memnew(TextureRect); profile_texture->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); - profile_texture->set_ignore_texture_size(true); + profile_texture->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); profile_texture->set_h_size_flags(Control::SIZE_FILL); profile_texture->set_v_size_flags(Control::SIZE_FILL); bone_mapper_field->add_child(profile_texture); diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp index 7f9a23463c..bd7b7ff1cb 100644 --- a/editor/plugins/canvas_item_editor_plugin.cpp +++ b/editor/plugins/canvas_item_editor_plugin.cpp @@ -4370,8 +4370,7 @@ void CanvasItemEditor::_popup_callback(int p_op) { show_rulers = !show_rulers; int idx = view_menu->get_popup()->get_item_index(SHOW_RULERS); view_menu->get_popup()->set_item_checked(idx, show_rulers); - _update_scrollbars(); - viewport->queue_redraw(); + update_viewport(); } break; case SHOW_GUIDES: { show_guides = !show_guides; @@ -4683,25 +4682,18 @@ void CanvasItemEditor::_focus_selection(int p_op) { } else { rect = rect.merge(canvas_item_rect); } - }; - - if (p_op == VIEW_CENTER_TO_SELECTION) { - center = rect.get_center(); - Vector2 offset = viewport->get_size() / 2 - EditorNode::get_singleton()->get_scene_root()->get_global_canvas_transform().xform(center); - view_offset -= (offset / zoom).round(); - update_viewport(); - - } else { // VIEW_FRAME_TO_SELECTION + } - if (rect.size.x > CMP_EPSILON && rect.size.y > CMP_EPSILON) { - real_t scale_x = viewport->get_size().x / rect.size.x; - real_t scale_y = viewport->get_size().y / rect.size.y; - zoom = scale_x < scale_y ? scale_x : scale_y; - zoom *= 0.90; - viewport->queue_redraw(); - zoom_widget->set_zoom(zoom); - call_deferred(SNAME("_popup_callback"), VIEW_CENTER_TO_SELECTION); - } + if (p_op == VIEW_FRAME_TO_SELECTION && rect.size.x > CMP_EPSILON && rect.size.y > CMP_EPSILON) { + real_t scale_x = viewport->get_size().x / rect.size.x; + real_t scale_y = viewport->get_size().y / rect.size.y; + zoom = scale_x < scale_y ? scale_x : scale_y; + zoom *= 0.90; + zoom_widget->set_zoom(zoom); + viewport->queue_redraw(); // Redraw to update the global canvas transform after zoom changes. + call_deferred(SNAME("center_at"), rect.get_center()); // Defer because the updated transform is needed. + } else { + center_at(rect.get_center()); } } @@ -4715,6 +4707,7 @@ void CanvasItemEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("set_state"), &CanvasItemEditor::set_state); ClassDB::bind_method(D_METHOD("update_viewport"), &CanvasItemEditor::update_viewport); + ClassDB::bind_method(D_METHOD("center_at", "position"), &CanvasItemEditor::center_at); ClassDB::bind_method("_set_owner_for_node_and_children", &CanvasItemEditor::_set_owner_for_node_and_children); @@ -4961,6 +4954,12 @@ void CanvasItemEditor::focus_selection() { _focus_selection(VIEW_CENTER_TO_SELECTION); } +void CanvasItemEditor::center_at(const Point2 &p_pos) { + Vector2 offset = viewport->get_size() / 2 - EditorNode::get_singleton()->get_scene_root()->get_global_canvas_transform().xform(p_pos); + view_offset -= (offset / zoom).round(); + update_viewport(); +} + CanvasItemEditor::CanvasItemEditor() { zoom = 1.0 / MAX(1, EDSCALE); view_offset = Point2(-150 - RULER_WIDTH, -95 - RULER_WIDTH); diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h index 8f02f02c32..f4fcc8a3d2 100644 --- a/editor/plugins/canvas_item_editor_plugin.h +++ b/editor/plugins/canvas_item_editor_plugin.h @@ -550,6 +550,7 @@ public: void edit(CanvasItem *p_canvas_item); void focus_selection(); + void center_at(const Point2 &p_pos); EditorSelection *editor_selection = nullptr; diff --git a/editor/plugins/gradient_texture_2d_editor_plugin.cpp b/editor/plugins/gradient_texture_2d_editor_plugin.cpp index 703a44403d..e03353a67b 100644 --- a/editor/plugins/gradient_texture_2d_editor_plugin.cpp +++ b/editor/plugins/gradient_texture_2d_editor_plugin.cpp @@ -178,7 +178,7 @@ void GradientTexture2DEditorRect::_notification(int p_what) { GradientTexture2DEditorRect::GradientTexture2DEditorRect() { checkerboard = memnew(TextureRect); checkerboard->set_stretch_mode(TextureRect::STRETCH_TILE); - checkerboard->set_ignore_texture_size(true); + checkerboard->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); checkerboard->set_draw_behind_parent(true); add_child(checkerboard, false, INTERNAL_MODE_FRONT); diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp index 7603a5e55d..f4ec026504 100644 --- a/editor/plugins/sprite_frames_editor_plugin.cpp +++ b/editor/plugins/sprite_frames_editor_plugin.cpp @@ -1551,7 +1551,7 @@ SpriteFramesEditor::SpriteFramesEditor() { split_sheet_vb->add_child(split_sheet_panel); split_sheet_preview = memnew(TextureRect); - split_sheet_preview->set_ignore_texture_size(true); + split_sheet_preview->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); split_sheet_preview->set_mouse_filter(MOUSE_FILTER_PASS); split_sheet_preview->connect("draw", callable_mp(this, &SpriteFramesEditor::_sheet_preview_draw)); split_sheet_preview->connect("gui_input", callable_mp(this, &SpriteFramesEditor::_sheet_preview_input)); diff --git a/editor/plugins/texture_editor_plugin.cpp b/editor/plugins/texture_editor_plugin.cpp index 2dab3fa278..2fb624b713 100644 --- a/editor/plugins/texture_editor_plugin.cpp +++ b/editor/plugins/texture_editor_plugin.cpp @@ -128,7 +128,7 @@ TexturePreview::TexturePreview(Ref<Texture2D> p_texture, bool p_show_metadata) { texture_display->set_texture(p_texture); texture_display->set_anchors_preset(TextureRect::PRESET_FULL_RECT); texture_display->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); - texture_display->set_ignore_texture_size(true); + texture_display->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); add_child(texture_display); if (p_show_metadata) { diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp index 59f2159167..05d32e1d08 100644 --- a/editor/plugins/texture_region_editor_plugin.cpp +++ b/editor/plugins/texture_region_editor_plugin.cpp @@ -824,10 +824,18 @@ void TextureRegionEditor::_update_autoslice() { void TextureRegionEditor::_notification(int p_what) { switch (p_what) { - case NOTIFICATION_ENTER_TREE: + case NOTIFICATION_EXIT_TREE: { + get_tree()->disconnect("node_removed", callable_mp(this, &TextureRegionEditor::_node_removed)); + } break; + + case NOTIFICATION_ENTER_TREE: { + get_tree()->connect("node_removed", callable_mp(this, &TextureRegionEditor::_node_removed)); + [[fallthrough]]; + } case NOTIFICATION_THEME_CHANGED: { edit_draw->add_theme_style_override("panel", get_theme_stylebox(SNAME("panel"), SNAME("Tree"))); } break; + case NOTIFICATION_READY: { zoom_out->set_icon(get_theme_icon(SNAME("ZoomLess"), SNAME("EditorIcons"))); zoom_reset->set_icon(get_theme_icon(SNAME("ZoomReset"), SNAME("EditorIcons"))); @@ -840,11 +848,13 @@ void TextureRegionEditor::_notification(int p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/sub_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning"))); } break; + case NOTIFICATION_VISIBILITY_CHANGED: { if (snap_mode == SNAP_AUTOSLICE && is_visible() && autoslice_is_dirty) { _update_autoslice(); } } break; + case NOTIFICATION_WM_WINDOW_FOCUS_IN: { // This happens when the user leaves the Editor and returns, // they could have changed the textures, so the cache is cleared. @@ -867,7 +877,6 @@ void TextureRegionEditor::_node_removed(Object *p_obj) { void TextureRegionEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_edit_region"), &TextureRegionEditor::_edit_region); - ClassDB::bind_method(D_METHOD("_node_removed"), &TextureRegionEditor::_node_removed); ClassDB::bind_method(D_METHOD("_zoom_on_position"), &TextureRegionEditor::_zoom_on_position); ClassDB::bind_method(D_METHOD("_update_rect"), &TextureRegionEditor::_update_rect); } diff --git a/editor/plugins/tiles/atlas_merging_dialog.cpp b/editor/plugins/tiles/atlas_merging_dialog.cpp index 7edf6e3a30..4128029fc6 100644 --- a/editor/plugins/tiles/atlas_merging_dialog.cpp +++ b/editor/plugins/tiles/atlas_merging_dialog.cpp @@ -56,7 +56,7 @@ void AtlasMergingDialog::_generate_merged(Vector<Ref<TileSetAtlasSource>> p_atla new_texture_region_size = new_texture_region_size.max(atlas_source->get_texture_region_size()); } - // Generate the merged TileSetAtlasSource. + // Generate the new texture. Vector2i atlas_offset; int line_height = 0; for (int source_index = 0; source_index < p_atlas_sources.size(); source_index++) { @@ -72,28 +72,6 @@ void AtlasMergingDialog::_generate_merged(Vector<Ref<TileSetAtlasSource>> p_atla Rect2i new_tile_rect_in_altas = Rect2i(atlas_offset + tile_id, atlas_source->get_tile_size_in_atlas(tile_id)); - // Create tiles and alternatives, then copy their properties. - for (int alternative_index = 0; alternative_index < atlas_source->get_alternative_tiles_count(tile_id); alternative_index++) { - int alternative_id = atlas_source->get_alternative_tile_id(tile_id, alternative_index); - if (alternative_id == 0) { - merged->create_tile(new_tile_rect_in_altas.position, new_tile_rect_in_altas.size); - } else { - merged->create_alternative_tile(new_tile_rect_in_altas.position, alternative_index); - } - - // Copy the properties. - TileData *original_tile_data = atlas_source->get_tile_data(tile_id, alternative_id); - List<PropertyInfo> properties; - original_tile_data->get_property_list(&properties); - for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { - const StringName &property_name = E->get().name; - merged->set(property_name, original_tile_data->get(property_name)); - } - - // Add to the mapping. - merged_mapping[source_index][tile_id] = new_tile_rect_in_altas.position; - } - // Copy the texture. for (int frame = 0; frame < atlas_source->get_tile_animation_frames_count(tile_id); frame++) { Rect2i src_rect = atlas_source->get_tile_texture_region(tile_id, frame); @@ -103,6 +81,9 @@ void AtlasMergingDialog::_generate_merged(Vector<Ref<TileSetAtlasSource>> p_atla } output_image->blit_rect(atlas_source->get_texture()->get_image(), src_rect, dst_rect_wide.get_center() - src_rect.size / 2); } + + // Add to the mapping. + merged_mapping[source_index][tile_id] = new_tile_rect_in_altas.position; } // Compute the atlas offset. @@ -115,8 +96,43 @@ void AtlasMergingDialog::_generate_merged(Vector<Ref<TileSetAtlasSource>> p_atla } } - merged->set_name(p_atlas_sources[0]->get_name()); merged->set_texture(ImageTexture::create_from_image(output_image)); + + // Copy the tiles to the merged TileSetAtlasSource. + for (int source_index = 0; source_index < p_atlas_sources.size(); source_index++) { + Ref<TileSetAtlasSource> atlas_source = p_atlas_sources[source_index]; + for (KeyValue<Vector2i, Vector2i> tile_mapping : merged_mapping[source_index]) { + // Create tiles and alternatives, then copy their properties. + for (int alternative_index = 0; alternative_index < atlas_source->get_alternative_tiles_count(tile_mapping.key); alternative_index++) { + int alternative_id = atlas_source->get_alternative_tile_id(tile_mapping.key, alternative_index); + if (alternative_id == 0) { + merged->create_tile(tile_mapping.value, atlas_source->get_tile_size_in_atlas(tile_mapping.key)); + } else { + merged->create_alternative_tile(tile_mapping.value, alternative_index); + } + + // Copy the properties. + TileData *src_tile_data = atlas_source->get_tile_data(tile_mapping.key, alternative_id); + List<PropertyInfo> properties; + src_tile_data->get_property_list(&properties); + + TileData *dst_tile_data = merged->get_tile_data(tile_mapping.value, alternative_id); + for (PropertyInfo property : properties) { + if (!(property.usage & PROPERTY_USAGE_STORAGE)) { + continue; + } + Variant value = src_tile_data->get(property.name); + Variant default_value = ClassDB::class_get_default_property_value("TileData", property.name); + if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) { + continue; + } + dst_tile_data->set(property.name, value); + } + } + } + } + + merged->set_name(p_atlas_sources[0]->get_name()); merged->set_texture_region_size(new_texture_region_size); } } @@ -151,6 +167,8 @@ void AtlasMergingDialog::_merge_confirmed(String p_path) { Ref<ImageTexture> output_image_texture = merged->get_texture(); output_image_texture->get_image()->save_png(p_path); + ResourceLoader::import(p_path); + Ref<Texture2D> new_texture_resource = ResourceLoader::load(p_path, "Texture2D"); merged->set_texture(new_texture_resource); @@ -225,6 +243,14 @@ bool AtlasMergingDialog::_get(const StringName &p_name, Variant &r_ret) const { return false; } +void AtlasMergingDialog::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_VISIBILITY_CHANGED: { + _update_texture(); + } break; + } +} + void AtlasMergingDialog::update_tile_set(Ref<TileSet> p_tile_set) { ERR_FAIL_COND(!p_tile_set.is_valid()); tile_set = p_tile_set; @@ -300,7 +326,7 @@ AtlasMergingDialog::AtlasMergingDialog() { preview = memnew(TextureRect); preview->set_h_size_flags(Control::SIZE_EXPAND_FILL); preview->set_v_size_flags(Control::SIZE_EXPAND_FILL); - preview->set_ignore_texture_size(true); + preview->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); preview->hide(); preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); atlas_merging_right_panel->add_child(preview); diff --git a/editor/plugins/tiles/atlas_merging_dialog.h b/editor/plugins/tiles/atlas_merging_dialog.h index 032541c90e..bf1b56894f 100644 --- a/editor/plugins/tiles/atlas_merging_dialog.h +++ b/editor/plugins/tiles/atlas_merging_dialog.h @@ -75,6 +75,8 @@ protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; + void _notification(int p_what); + public: void update_tile_set(Ref<TileSet> p_tile_set); diff --git a/editor/plugins/tiles/tile_map_editor.cpp b/editor/plugins/tiles/tile_map_editor.cpp index dd4daa45b7..e9c313a372 100644 --- a/editor/plugins/tiles/tile_map_editor.cpp +++ b/editor/plugins/tiles/tile_map_editor.cpp @@ -3303,12 +3303,16 @@ void TileMapEditorTerrainsPlugin::_update_theme() { void TileMapEditorTerrainsPlugin::edit(ObjectID p_tile_map_id, int p_tile_map_layer) { _stop_dragging(); // Avoids staying in a wrong drag state. - tile_map_id = p_tile_map_id; - tile_map_layer = p_tile_map_layer; + if (tile_map_id != p_tile_map_id) { + tile_map_id = p_tile_map_id; - _update_terrains_cache(); - _update_terrains_tree(); - _update_tiles_list(); + // Clear the selection. + _update_terrains_cache(); + _update_terrains_tree(); + _update_tiles_list(); + } + + tile_map_layer = p_tile_map_layer; } TileMapEditorTerrainsPlugin::TileMapEditorTerrainsPlugin() { diff --git a/editor/plugins/tiles/tiles_editor_plugin.cpp b/editor/plugins/tiles/tiles_editor_plugin.cpp index b40e588e07..19ee0ae98d 100644 --- a/editor/plugins/tiles/tiles_editor_plugin.cpp +++ b/editor/plugins/tiles/tiles_editor_plugin.cpp @@ -185,26 +185,34 @@ void TilesEditorPlugin::_notification(int p_what) { } void TilesEditorPlugin::make_visible(bool p_visible) { - is_visible = p_visible; - - if (is_visible) { + if (p_visible || is_tile_map_selected()) { // Disable and hide invalid editors. TileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id)); tileset_editor_button->set_visible(tile_set.is_valid()); tilemap_editor_button->set_visible(tile_map); - if (tile_map && !is_editing_tile_set) { + if (tile_map && (!is_editing_tile_set || !p_visible)) { EditorNode::get_singleton()->make_bottom_panel_item_visible(tilemap_editor); } else { EditorNode::get_singleton()->make_bottom_panel_item_visible(tileset_editor); } - + is_visible = true; } else { tileset_editor_button->hide(); tilemap_editor_button->hide(); EditorNode::get_singleton()->hide_bottom_panel(); + is_visible = false; } } +bool TilesEditorPlugin::is_tile_map_selected() { + TypedArray<Node> selection = get_editor_interface()->get_selection()->get_selected_nodes(); + if (selection.size() == 1 && Object::cast_to<TileMap>(selection[0])) { + return true; + } + + return false; +} + void TilesEditorPlugin::queue_pattern_preview(Ref<TileSet> p_tile_set, Ref<TileMapPattern> p_pattern, Callable p_callback) { ERR_FAIL_COND(!p_tile_set.is_valid()); ERR_FAIL_COND(!p_pattern.is_valid()); @@ -362,19 +370,24 @@ void TilesEditorPlugin::edit(Object *p_object) { } else if (p_object->is_class("TileSet")) { tile_set = Ref<TileSet>(p_object); if (tile_map) { - if (tile_map->get_tileset() != tile_set || !tile_map->is_inside_tree()) { + if (tile_map->get_tileset() != tile_set || !tile_map->is_inside_tree() || !is_tile_map_selected()) { tile_map = nullptr; tile_map_id = ObjectID(); } } is_editing_tile_set = true; - EditorNode::get_singleton()->make_bottom_panel_item_visible(tileset_editor); } } // Update the editors. _update_editors(); + // If the tileset is being edited, the visibility function must be called + // here after _update_editors has been called. + if (is_editing_tile_set) { + EditorNode::get_singleton()->make_bottom_panel_item_visible(tileset_editor); + } + // Add change listener. if (tile_map) { tile_map->connect("changed", callable_mp(this, &TilesEditorPlugin::_tile_map_changed)); diff --git a/editor/plugins/tiles/tiles_editor_plugin.h b/editor/plugins/tiles/tiles_editor_plugin.h index 5b91584aa3..50073e59c6 100644 --- a/editor/plugins/tiles/tiles_editor_plugin.h +++ b/editor/plugins/tiles/tiles_editor_plugin.h @@ -110,6 +110,8 @@ public: virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return tilemap_editor->forward_canvas_gui_input(p_event); } virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { tilemap_editor->forward_canvas_draw_over_viewport(p_overlay); } + bool is_tile_map_selected(); + // Pattern preview API. void queue_pattern_preview(Ref<TileSet> p_tile_set, Ref<TileMapPattern> p_pattern, Callable p_callback); diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 46ec3bcdd1..d550c1e5d4 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -129,30 +129,32 @@ void VisualShaderGraphPlugin::set_connections(const List<VisualShader::Connectio void VisualShaderGraphPlugin::show_port_preview(VisualShader::Type p_type, int p_node_id, int p_port_id) { if (visual_shader->get_shader_type() == p_type && links.has(p_node_id) && links[p_node_id].output_ports.has(p_port_id)) { - for (const KeyValue<int, Port> &E : links[p_node_id].output_ports) { + Link &link = links[p_node_id]; + + for (const KeyValue<int, Port> &E : link.output_ports) { if (E.value.preview_button != nullptr) { E.value.preview_button->set_pressed(false); } } + bool is_dirty = link.preview_pos < 0; - if (links[p_node_id].preview_visible && !is_dirty() && links[p_node_id].preview_box != nullptr) { - links[p_node_id].graph_node->remove_child(links[p_node_id].preview_box); - memdelete(links[p_node_id].preview_box); - links[p_node_id].graph_node->reset_size(); - links[p_node_id].preview_visible = false; + if (!is_dirty && link.preview_visible && link.preview_box != nullptr) { + link.graph_node->remove_child(link.preview_box); + memdelete(link.preview_box); + link.preview_box = nullptr; + link.graph_node->reset_size(); + link.preview_visible = false; } - if (p_port_id != -1 && links[p_node_id].output_ports[p_port_id].preview_button != nullptr) { - if (is_dirty()) { - links[p_node_id].preview_pos = links[p_node_id].graph_node->get_child_count(); + if (p_port_id != -1 && link.output_ports[p_port_id].preview_button != nullptr) { + if (is_dirty) { + link.preview_pos = link.graph_node->get_child_count(); } VBoxContainer *vbox = memnew(VBoxContainer); - links[p_node_id].graph_node->add_child(vbox); - if (links[p_node_id].preview_pos != -1) { - links[p_node_id].graph_node->move_child(vbox, links[p_node_id].preview_pos); - } - links[p_node_id].graph_node->set_slot_draw_stylebox(vbox->get_index(), false); + link.graph_node->add_child(vbox); + link.graph_node->move_child(vbox, link.preview_pos); + link.graph_node->set_slot_draw_stylebox(vbox->get_index(), false); Control *offset = memnew(Control); offset->set_custom_minimum_size(Size2(0, 5 * EDSCALE)); @@ -162,9 +164,9 @@ void VisualShaderGraphPlugin::show_port_preview(VisualShader::Type p_type, int p port_preview->setup(visual_shader, visual_shader->get_shader_type(), p_node_id, p_port_id); port_preview->set_h_size_flags(Control::SIZE_SHRINK_CENTER); vbox->add_child(port_preview); - links[p_node_id].preview_visible = true; - links[p_node_id].preview_box = vbox; - links[p_node_id].output_ports[p_port_id].preview_button->set_pressed(true); + link.preview_visible = true; + link.preview_box = vbox; + link.output_ports[p_port_id].preview_button->set_pressed(true); } } } @@ -177,8 +179,8 @@ void VisualShaderGraphPlugin::update_node(VisualShader::Type p_type, int p_node_ if (p_type != visual_shader->get_shader_type() || !links.has(p_node_id)) { return; } - remove_node(p_type, p_node_id); - add_node(p_type, p_node_id); + remove_node(p_type, p_node_id, true); + add_node(p_type, p_node_id, true); } void VisualShaderGraphPlugin::set_input_port_default_value(VisualShader::Type p_type, int p_node_id, int p_port_id, Variant p_value) { @@ -305,8 +307,8 @@ void VisualShaderGraphPlugin::update_parameter_refs() { for (KeyValue<int, Link> &E : links) { VisualShaderNodeParameterRef *ref = Object::cast_to<VisualShaderNodeParameterRef>(E.value.visual_node); if (ref) { - remove_node(E.value.type, E.key); - add_node(E.value.type, E.key); + remove_node(E.value.type, E.key, true); + add_node(E.value.type, E.key, true); } } } @@ -329,14 +331,6 @@ void VisualShaderGraphPlugin::clear_links() { links.clear(); } -bool VisualShaderGraphPlugin::is_dirty() const { - return dirty; -} - -void VisualShaderGraphPlugin::make_dirty(bool p_enabled) { - dirty = p_enabled; -} - void VisualShaderGraphPlugin::register_link(VisualShader::Type p_type, int p_id, VisualShaderNode *p_visual_node, GraphNode *p_graph_node) { links.insert(p_id, { p_type, p_visual_node, p_graph_node, p_visual_node->get_output_port_for_preview() != -1, -1, HashMap<int, InputPort>(), HashMap<int, Port>(), nullptr, nullptr, nullptr, { nullptr, nullptr, nullptr } }); } @@ -356,7 +350,7 @@ void VisualShaderGraphPlugin::update_theme() { vector_expanded_color[3] = editor->get_theme_color(SNAME("axis_w_color"), SNAME("Editor")); // alpha } -void VisualShaderGraphPlugin::add_node(VisualShader::Type p_type, int p_id) { +void VisualShaderGraphPlugin::add_node(VisualShader::Type p_type, int p_id, bool p_just_update) { if (!visual_shader.is_valid() || p_type != visual_shader->get_shader_type()) { return; } @@ -424,7 +418,18 @@ void VisualShaderGraphPlugin::add_node(VisualShader::Type p_type, int p_id) { graph->add_child(node); node->set_theme(vstheme); editor->_update_created_node(node); - register_link(p_type, p_id, vsnode.ptr(), node); + + if (p_just_update) { + Link &link = links[p_id]; + + link.graph_node = node; + link.preview_box = nullptr; + link.preview_pos = -1; + link.output_ports.clear(); + link.input_ports.clear(); + } else { + register_link(p_type, p_id, vsnode.ptr(), node); + } if (is_resizable) { size = resizable_node->get_size(); @@ -1038,11 +1043,13 @@ void VisualShaderGraphPlugin::add_node(VisualShader::Type p_type, int p_id) { } } -void VisualShaderGraphPlugin::remove_node(VisualShader::Type p_type, int p_id) { +void VisualShaderGraphPlugin::remove_node(VisualShader::Type p_type, int p_id, bool p_just_update) { if (visual_shader->get_shader_type() == p_type && links.has(p_id)) { links[p_id].graph_node->get_parent()->remove_child(links[p_id].graph_node); memdelete(links[p_id].graph_node); - links.erase(p_id); + if (!p_just_update) { + links.erase(p_id); + } } } @@ -1909,15 +1916,12 @@ void VisualShaderEditor::_update_graph() { _update_varyings(); graph_plugin->clear_links(); - graph_plugin->make_dirty(true); graph_plugin->update_theme(); for (int n_i = 0; n_i < nodes.size(); n_i++) { - graph_plugin->add_node(type, nodes[n_i]); + graph_plugin->add_node(type, nodes[n_i], false); } - graph_plugin->make_dirty(false); - for (const VisualShader::Connection &E : node_connections) { int from = E.from_node; int from_idx = E.from_port; @@ -2967,8 +2971,8 @@ void VisualShaderEditor::_add_node(int p_idx, const Vector<Variant> &p_ops, Stri } undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, vsnode, position, id_to_use); undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_to_use); - undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_to_use); - undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_to_use); + undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_to_use, false); + undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_to_use, false); VisualShaderNodeExpression *expr = Object::cast_to<VisualShaderNodeExpression>(vsnode.ptr()); if (expr) { @@ -3361,7 +3365,7 @@ void VisualShaderEditor::_delete_nodes(int p_type, const List<int> &p_nodes) { undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, F); undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, node, visual_shader->get_node_position(type, F), F); - undo_redo->add_undo_method(graph_plugin.ptr(), "add_node", type, F); + undo_redo->add_undo_method(graph_plugin.ptr(), "add_node", type, F, false); VisualShaderNodeParameter *parameter = Object::cast_to<VisualShaderNodeParameter>(node.ptr()); if (parameter) { @@ -3391,7 +3395,7 @@ void VisualShaderEditor::_delete_nodes(int p_type, const List<int> &p_nodes) { // delete nodes from the graph for (const int &F : p_nodes) { - undo_redo->add_do_method(graph_plugin.ptr(), "remove_node", type, F); + undo_redo->add_do_method(graph_plugin.ptr(), "remove_node", type, F, false); } // update parameter refs if any parameter has been deleted @@ -4131,7 +4135,7 @@ void VisualShaderEditor::_dup_paste_nodes(int p_type, List<CopyItem> &r_items, c } undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, node, item.position + p_offset, id_from); - undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_from); + undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_from, false); added_set.insert(id_from); id_from++; @@ -4153,7 +4157,7 @@ void VisualShaderEditor::_dup_paste_nodes(int p_type, List<CopyItem> &r_items, c continue; } undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_from); - undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_from); + undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_from, false); id_from++; } diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h index a43d44473f..c4f6b4952c 100644 --- a/editor/plugins/visual_shader_editor_plugin.h +++ b/editor/plugins/visual_shader_editor_plugin.h @@ -95,7 +95,6 @@ private: Ref<VisualShader> visual_shader; HashMap<int, Link> links; List<VisualShader::Connection> connections; - bool dirty = false; Color vector_expanded_color[4]; @@ -115,12 +114,10 @@ public: void clear_links(); void set_shader_type(VisualShader::Type p_type); bool is_preview_visible(int p_id) const; - bool is_dirty() const; - void make_dirty(bool p_enabled); void update_node(VisualShader::Type p_type, int p_id); void update_node_deferred(VisualShader::Type p_type, int p_node_id); - void add_node(VisualShader::Type p_type, int p_id); - void remove_node(VisualShader::Type p_type, int p_id); + void add_node(VisualShader::Type p_type, int p_id, bool p_just_update); + void remove_node(VisualShader::Type p_type, int p_id, bool p_just_update); void connect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); void disconnect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); void show_port_preview(VisualShader::Type p_type, int p_node_id, int p_port_id); diff --git a/editor/progress_dialog.cpp b/editor/progress_dialog.cpp index 4ecf3338bc..db11f80826 100644 --- a/editor/progress_dialog.cpp +++ b/editor/progress_dialog.cpp @@ -32,6 +32,7 @@ #include "core/object/message_queue.h" #include "core/os/os.h" +#include "editor/editor_node.h" #include "editor/editor_scale.h" #include "main/main.h" #include "servers/display_server.h" @@ -133,6 +134,14 @@ void BackgroundProgress::end_task(const String &p_task) { ProgressDialog *ProgressDialog::singleton = nullptr; void ProgressDialog::_notification(int p_what) { + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { + if (!is_visible()) { + Node *p = get_parent(); + if (p) { + p->remove_child(this); + } + } + } } void ProgressDialog::_popup() { @@ -146,8 +155,17 @@ void ProgressDialog::_popup() { main->set_offset(SIDE_TOP, style->get_margin(SIDE_TOP)); main->set_offset(SIDE_BOTTOM, -style->get_margin(SIDE_BOTTOM)); - //raise(); - popup_centered(ms); + EditorNode *ed = EditorNode::get_singleton(); + if (ed && !is_inside_tree()) { + Window *w = ed->get_window(); + while (w && w->get_exclusive_child()) { + w = w->get_exclusive_child(); + } + if (w && w != this) { + w->add_child(this); + popup_centered(ms); + } + } } void ProgressDialog::add_task(const String &p_task, const String &p_label, int p_steps, bool p_can_cancel) { diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index b4ffc7d78d..c4f5eb777e 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -1233,7 +1233,7 @@ void ProjectList::load_project_icon(int p_index) { // The default project icon is 128×128 to look crisp on hiDPI displays, // but we want the actual displayed size to be 64×64 on loDPI displays. - item.control->icon->set_ignore_texture_size(true); + item.control->icon->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE); item.control->icon->set_custom_minimum_size(Size2(64, 64) * EDSCALE); item.control->icon->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); @@ -1273,7 +1273,7 @@ ProjectList::Item ProjectList::load_project_data(const String &p_path, bool p_fa PackedStringArray unsupported_features = ProjectSettings::get_unsupported_features(project_features); uint64_t last_edited = 0; - if (FileAccess::exists(conf)) { + if (cf_err == OK) { // The modification date marks the date the project was last edited. // This is because the `project.godot` file will always be modified // when editing a project (but not when running it). @@ -2653,8 +2653,9 @@ ProjectManager::ProjectManager() { AcceptDialog::set_swap_cancel_ok(swap_cancel_ok == 2); } - set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT); - set_theme(create_custom_theme()); + Ref<Theme> theme = create_custom_theme(); + set_theme(theme); + DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), SNAME("Editor"))); set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT); diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp index 2f50172f54..b4f1ca5d0b 100644 --- a/editor/scene_tree_editor.cpp +++ b/editor/scene_tree_editor.cpp @@ -993,6 +993,10 @@ void SceneTreeEditor::_renamed() { } if (new_name == n->get_name()) { + if (which->get_text(0).is_empty()) { + which->set_text(0, new_name); + } + return; } diff --git a/main/main.cpp b/main/main.cpp index 190cdf3151..7ba5ffab2a 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -1385,7 +1385,6 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph #ifdef TOOLS_ENABLED if (editor) { packed_data->set_disabled(true); - globals->set_disable_feature_overrides(true); Engine::get_singleton()->set_editor_hint(true); main_args.push_back("--editor"); if (!init_windowed) { @@ -1920,6 +1919,9 @@ Error Main::setup2(Thread::ID p_main_tid_override) { window_position = &position; } + Color boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", boot_splash_bg_color); + DisplayServer::set_early_window_clear_color_override(true, boot_bg_color); + // rendering_driver now held in static global String in main and initialized in setup() Error err; display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, err); @@ -2085,7 +2087,7 @@ Error Main::setup2(Thread::ID p_main_tid_override) { boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0)); } - Color boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", boot_splash_bg_color); + Color boot_bg_color = GLOBAL_GET("application/boot_splash/bg_color"); #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH) boot_bg_color = @@ -2120,6 +2122,8 @@ Error Main::setup2(Thread::ID p_main_tid_override) { #endif } + DisplayServer::set_early_window_clear_color_override(false); + MAIN_PRINT("Main: DCC"); RenderingServer::get_singleton()->set_default_clear_color( GLOBAL_GET("rendering/environment/defaults/default_clear_color")); @@ -2964,6 +2968,7 @@ bool Main::is_iterating() { // For performance metrics. static uint64_t physics_process_max = 0; static uint64_t process_max = 0; +static uint64_t navigation_process_max = 0; bool Main::iteration() { //for now do not error on this @@ -2992,6 +2997,7 @@ bool Main::iteration() { uint64_t physics_process_ticks = 0; uint64_t process_ticks = 0; + uint64_t navigation_process_ticks = 0; frame += ticks_elapsed; @@ -3028,8 +3034,13 @@ bool Main::iteration() { break; } + uint64_t navigation_begin = OS::get_singleton()->get_ticks_usec(); + NavigationServer3D::get_singleton()->process(physics_step * time_scale); + navigation_process_ticks = MAX(navigation_process_ticks, OS::get_singleton()->get_ticks_usec() - navigation_begin); // keep the largest one for reference + navigation_process_max = MAX(OS::get_singleton()->get_ticks_usec() - navigation_begin, navigation_process_max); + message_queue->flush(); PhysicsServer3D::get_singleton()->end_sync(); @@ -3108,8 +3119,10 @@ bool Main::iteration() { Engine::get_singleton()->_fps = frames; performance->set_process_time(USEC_TO_SEC(process_max)); performance->set_physics_process_time(USEC_TO_SEC(physics_process_max)); + performance->set_navigation_process_time(USEC_TO_SEC(navigation_process_max)); process_max = 0; physics_process_max = 0; + navigation_process_max = 0; frame %= 1000000; frames = 0; diff --git a/main/performance.cpp b/main/performance.cpp index c2624c708f..e24a3673b9 100644 --- a/main/performance.cpp +++ b/main/performance.cpp @@ -36,6 +36,7 @@ #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "servers/audio_server.h" +#include "servers/navigation_server_3d.h" #include "servers/physics_server_2d.h" #include "servers/physics_server_3d.h" #include "servers/rendering_server.h" @@ -54,6 +55,7 @@ void Performance::_bind_methods() { BIND_ENUM_CONSTANT(TIME_FPS); BIND_ENUM_CONSTANT(TIME_PROCESS); BIND_ENUM_CONSTANT(TIME_PHYSICS_PROCESS); + BIND_ENUM_CONSTANT(TIME_NAVIGATION_PROCESS); BIND_ENUM_CONSTANT(MEMORY_STATIC); BIND_ENUM_CONSTANT(MEMORY_STATIC_MAX); BIND_ENUM_CONSTANT(MEMORY_MESSAGE_BUFFER_MAX); @@ -74,7 +76,15 @@ void Performance::_bind_methods() { BIND_ENUM_CONSTANT(PHYSICS_3D_COLLISION_PAIRS); BIND_ENUM_CONSTANT(PHYSICS_3D_ISLAND_COUNT); BIND_ENUM_CONSTANT(AUDIO_OUTPUT_LATENCY); - + BIND_ENUM_CONSTANT(NAVIGATION_ACTIVE_MAPS); + BIND_ENUM_CONSTANT(NAVIGATION_REGION_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_AGENT_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_LINK_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_POLYGON_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_EDGE_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_EDGE_MERGE_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_EDGE_CONNECTION_COUNT); + BIND_ENUM_CONSTANT(NAVIGATION_EDGE_FREE_COUNT); BIND_ENUM_CONSTANT(MONITOR_MAX); } @@ -93,6 +103,7 @@ String Performance::get_monitor_name(Monitor p_monitor) const { "time/fps", "time/process", "time/physics_process", + "time/navigation_process", "memory/static", "memory/static_max", "memory/msg_buf_max", @@ -113,6 +124,15 @@ String Performance::get_monitor_name(Monitor p_monitor) const { "physics_3d/collision_pairs", "physics_3d/islands", "audio/driver/output_latency", + "navigation/active_maps", + "navigation/regions", + "navigation/agents", + "navigation/links", + "navigation/polygons", + "navigation/edges", + "navigation/edges_merged", + "navigation/edges_connected", + "navigation/edges_free", }; @@ -127,6 +147,8 @@ double Performance::get_monitor(Monitor p_monitor) const { return _process_time; case TIME_PHYSICS_PROCESS: return _physics_process_time; + case TIME_NAVIGATION_PROCESS: + return _navigation_process_time; case MEMORY_STATIC: return Memory::get_mem_usage(); case MEMORY_STATIC_MAX: @@ -167,6 +189,24 @@ double Performance::get_monitor(Monitor p_monitor) const { return PhysicsServer3D::get_singleton()->get_process_info(PhysicsServer3D::INFO_ISLAND_COUNT); case AUDIO_OUTPUT_LATENCY: return AudioServer::get_singleton()->get_output_latency(); + case NAVIGATION_ACTIVE_MAPS: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_ACTIVE_MAPS); + case NAVIGATION_REGION_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_REGION_COUNT); + case NAVIGATION_AGENT_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_AGENT_COUNT); + case NAVIGATION_LINK_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_LINK_COUNT); + case NAVIGATION_POLYGON_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_POLYGON_COUNT); + case NAVIGATION_EDGE_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_EDGE_COUNT); + case NAVIGATION_EDGE_MERGE_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_EDGE_MERGE_COUNT); + case NAVIGATION_EDGE_CONNECTION_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_EDGE_CONNECTION_COUNT); + case NAVIGATION_EDGE_FREE_COUNT: + return NavigationServer3D::get_singleton()->get_process_info(NavigationServer3D::INFO_EDGE_FREE_COUNT); default: { } @@ -182,6 +222,7 @@ Performance::MonitorType Performance::get_monitor_type(Monitor p_monitor) const MONITOR_TYPE_QUANTITY, MONITOR_TYPE_TIME, MONITOR_TYPE_TIME, + MONITOR_TYPE_TIME, MONITOR_TYPE_MEMORY, MONITOR_TYPE_MEMORY, MONITOR_TYPE_MEMORY, @@ -202,6 +243,15 @@ Performance::MonitorType Performance::get_monitor_type(Monitor p_monitor) const MONITOR_TYPE_QUANTITY, MONITOR_TYPE_QUANTITY, MONITOR_TYPE_TIME, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, + MONITOR_TYPE_QUANTITY, }; @@ -216,6 +266,10 @@ void Performance::set_physics_process_time(double p_pt) { _physics_process_time = p_pt; } +void Performance::set_navigation_process_time(double p_pt) { + _navigation_process_time = p_pt; +} + void Performance::add_custom_monitor(const StringName &p_id, const Callable &p_callable, const Vector<Variant> &p_args) { ERR_FAIL_COND_MSG(has_custom_monitor(p_id), "Custom monitor with id '" + String(p_id) + "' already exists."); _monitor_map.insert(p_id, MonitorCall(p_callable, p_args)); @@ -262,6 +316,7 @@ uint64_t Performance::get_monitor_modification_time() { Performance::Performance() { _process_time = 0; _physics_process_time = 0; + _navigation_process_time = 0; _monitor_modification_time = 0; singleton = this; } diff --git a/main/performance.h b/main/performance.h index 14695ab5a3..34162b2da9 100644 --- a/main/performance.h +++ b/main/performance.h @@ -50,6 +50,7 @@ class Performance : public Object { double _process_time; double _physics_process_time; + double _navigation_process_time; class MonitorCall { Callable _callable; @@ -69,6 +70,7 @@ public: TIME_FPS, TIME_PROCESS, TIME_PHYSICS_PROCESS, + TIME_NAVIGATION_PROCESS, MEMORY_STATIC, MEMORY_STATIC_MAX, MEMORY_MESSAGE_BUFFER_MAX, @@ -89,6 +91,15 @@ public: PHYSICS_3D_COLLISION_PAIRS, PHYSICS_3D_ISLAND_COUNT, AUDIO_OUTPUT_LATENCY, + NAVIGATION_ACTIVE_MAPS, + NAVIGATION_REGION_COUNT, + NAVIGATION_AGENT_COUNT, + NAVIGATION_LINK_COUNT, + NAVIGATION_POLYGON_COUNT, + NAVIGATION_EDGE_COUNT, + NAVIGATION_EDGE_MERGE_COUNT, + NAVIGATION_EDGE_CONNECTION_COUNT, + NAVIGATION_EDGE_FREE_COUNT, MONITOR_MAX }; @@ -105,6 +116,7 @@ public: void set_process_time(double p_pt); void set_physics_process_time(double p_pt); + void set_navigation_process_time(double p_pt); void add_custom_monitor(const StringName &p_id, const Callable &p_callable, const Vector<Variant> &p_args); void remove_custom_monitor(const StringName &p_id); diff --git a/methods.py b/methods.py index ee88401671..7ede2592ff 100644 --- a/methods.py +++ b/methods.py @@ -488,29 +488,29 @@ def use_windows_spawn_fix(self, platform=None): def save_active_platforms(apnames, ap): for x in ap: - names = ["logo"] - if os.path.isfile(x + "/run_icon.png"): - names.append("run_icon") - - for name in names: - pngf = open(x + "/" + name + ".png", "rb") - b = pngf.read(1) - str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n" - str += " static const unsigned char _" + x[9:] + "_" + name + "[]={" + svg_names = [] + if os.path.isfile(x + "/logo.svg"): + svg_names.append("logo") + if os.path.isfile(x + "/run_icon.svg"): + svg_names.append("run_icon") + + for name in svg_names: + svgf = open(x + "/" + name + ".svg", "rb") + b = svgf.read(1) + svg_str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n" + svg_str += " static const char *_" + x[9:] + "_" + name + '_svg = "' while len(b) == 1: - str += hex(ord(b)) - b = pngf.read(1) - if len(b) == 1: - str += "," + svg_str += "\\" + hex(ord(b))[1:] + b = svgf.read(1) - str += "};\n" + svg_str += '";\n' - pngf.close() + svgf.close() # NOTE: It is safe to generate this file here, since this is still executed serially - wf = x + "/" + name + ".gen.h" - with open(wf, "w") as pngw: - pngw.write(str) + wf = x + "/" + name + "_svg.gen.h" + with open(wf, "w") as svgw: + svgw.write(svg_str) def no_verbose(sys, env): diff --git a/misc/scripts/file_format.sh b/misc/scripts/file_format.sh index a2f33692f9..3ff5798e22 100755 --- a/misc/scripts/file_format.sh +++ b/misc/scripts/file_format.sh @@ -4,9 +4,9 @@ # This is supplementary to clang_format.sh and black_format.sh, but should be # run before them. -# We need dos2unix and recode. -if [ ! -x "$(command -v dos2unix)" -o ! -x "$(command -v recode)" ]; then - printf "Install 'dos2unix' and 'recode' to use this script.\n" +# We need dos2unix and isutf8. +if [ ! -x "$(command -v dos2unix)" -o ! -x "$(command -v isutf8)" ]; then + printf "Install 'dos2unix' and 'isutf8' (moreutils package) to use this script.\n" fi set -uo pipefail @@ -53,22 +53,24 @@ done diff=$(git diff --color) -# If no UTF-8 violations were collected and no diff has been -# generated all is OK, clean up, and exit. if [ ! -s utf8-validation.txt ] && [ -z "$diff" ] ; then + # If no UTF-8 violations were collected (the file is empty) and + # no diff has been generated all is OK, clean up, and exit. printf "Files in this commit comply with the formatting rules.\n" - rm -f utf8-violations.txt + rm -f utf8-validation.txt exit 0 fi -# Violations detected, notify the user, clean up, and exit. if [ -s utf8-validation.txt ] then + # If the file has content and is not empty, violations + # detected, notify the user, clean up, and exit. printf "\n*** The following files contain invalid UTF-8 character sequences:\n\n" cat utf8-validation.txt - rm -f utf8-validation.txt fi +rm -f utf8-validation.txt + if [ ! -z "$diff" ] then printf "\n*** The following differences were found between the code " diff --git a/modules/etcpak/image_compress_etcpak.cpp b/modules/etcpak/image_compress_etcpak.cpp index 1fd98a43d4..b5192bd664 100644 --- a/modules/etcpak/image_compress_etcpak.cpp +++ b/modules/etcpak/image_compress_etcpak.cpp @@ -118,6 +118,7 @@ void _compress_etcpak(EtcpakType p_compresstype, Image *r_img, float p_lossy_qua } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_RA_AS_RG) { target_format = Image::FORMAT_ETC2_RA_AS_RG; r_img->convert_rg_to_ra_rgba8(); + r_img->convert_rgba8_to_bgra8(); // It's badly documented but ETCPAK seems to be expected BGRA8 for ETC. } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_ALPHA) { target_format = Image::FORMAT_ETC2_RGBA8; r_img->convert_rgba8_to_bgra8(); // It's badly documented but ETCPAK seems to be expected BGRA8 for ETC. @@ -222,9 +223,9 @@ void _compress_etcpak(EtcpakType p_compresstype, Image *r_img, float p_lossy_qua } if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC1) { CompressEtc1RgbDither(src_mip_read, dest_mip_write, blocks, mip_w); - } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2 || p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_RA_AS_RG) { + } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2) { CompressEtc2Rgb(src_mip_read, dest_mip_write, blocks, mip_w, true); - } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_ALPHA) { + } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_ALPHA || p_compresstype == EtcpakType::ETCPAK_TYPE_ETC2_RA_AS_RG) { CompressEtc2Rgba(src_mip_read, dest_mip_write, blocks, mip_w, true); } else if (p_compresstype == EtcpakType::ETCPAK_TYPE_DXT1) { CompressDxt1Dither(src_mip_read, dest_mip_write, blocks, mip_w); diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 7b79c9cf7e..28f478e9cd 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -1037,7 +1037,7 @@ String GDScript::get_script_path() const { } Error GDScript::load_source_code(const String &p_path) { - if (p_path.is_empty() || ResourceLoader::get_resource_type(p_path.get_slice("::", 0)) == "PackedScene") { + if (p_path.is_empty() || p_path.begins_with("gdscript://") || ResourceLoader::get_resource_type(p_path.get_slice("::", 0)) == "PackedScene") { return OK; } @@ -1363,6 +1363,8 @@ GDScript::GDScript() : GDScriptLanguage::get_singleton()->script_list.add(&script_list); } + + path = vformat("gdscript://%d.gd", get_instance_id()); } void GDScript::_save_orphaned_subclasses(GDScript::ClearData *p_clear_data) { diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 7bde4e7c4b..1b488d560c 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -68,9 +68,6 @@ static MethodInfo info_from_utility_func(const StringName &p_function) { pi.name = "arg" + itos(i + 1); #endif pi.type = Variant::get_utility_function_argument_type(p_function, i); - if (pi.type == Variant::NIL) { - pi.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; - } info.arguments.push_back(pi); } } @@ -103,8 +100,21 @@ static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; type.kind = GDScriptParser::DataType::NATIVE; type.builtin_type = Variant::OBJECT; - type.is_constant = true; type.native_type = p_class_name; + type.is_constant = true; + type.is_meta_type = true; + return type; +} + +static GDScriptParser::DataType make_script_meta_type(const Ref<Script> &p_script) { + GDScriptParser::DataType type; + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::SCRIPT; + type.builtin_type = Variant::OBJECT; + type.native_type = p_script->get_instance_base_type(); + type.script_type = p_script; + type.script_path = p_script->get_path(); + type.is_constant = true; type.is_meta_type = true; return type; } @@ -421,7 +431,7 @@ Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_c return err; } base = info_parser->get_parser()->head->get_datatype(); - } else if (class_exists(name) && ClassDB::can_instantiate(name)) { + } else if (class_exists(name)) { base.kind = GDScriptParser::DataType::NATIVE; base.native_type = name; } else { @@ -581,11 +591,8 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type result.builtin_type = GDScriptParser::get_builtin_type(first); if (result.builtin_type == Variant::ARRAY) { - GDScriptParser::DataType container_type = resolve_datatype(p_type->container_type); - + GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->container_type)); if (container_type.kind != GDScriptParser::DataType::VARIANT) { - container_type.is_meta_type = false; - container_type.is_constant = false; result.set_container_element_type(container_type); } } @@ -607,12 +614,7 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type } result = ref->get_parser()->head->get_datatype(); } else { - result.kind = GDScriptParser::DataType::SCRIPT; - result.script_type = ResourceLoader::load(path, "Script"); - result.native_type = result.script_type->get_instance_base_type(); - result.script_path = path; - result.is_constant = true; - result.is_meta_type = false; + result = make_script_meta_type(ResourceLoader::load(path, "Script")); } } } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { @@ -656,7 +658,6 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type case GDScriptParser::ClassNode::Member::CONSTANT: if (member.get_datatype().is_meta_type) { result = member.get_datatype(); - result.is_meta_type = false; found = true; break; } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) { @@ -668,15 +669,8 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type return bad_type; } result = ref->get_parser()->head->get_datatype(); - result.is_meta_type = false; } else { - Ref<Script> script = member.constant->initializer->reduced_value; - result.kind = GDScriptParser::DataType::SCRIPT; - result.builtin_type = Variant::OBJECT; - result.script_type = script; - result.script_path = script->get_path(); - result.native_type = script->get_instance_base_type(); - result.is_meta_type = false; + result = make_script_meta_type(member.constant->initializer->reduced_value); } found = true; break; @@ -832,8 +826,7 @@ void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, for (int j = 0; j < member.signal->parameters.size(); j++) { GDScriptParser::ParameterNode *param = member.signal->parameters[j]; - GDScriptParser::DataType param_type = resolve_datatype(param->datatype_specifier); - param_type.is_meta_type = false; + GDScriptParser::DataType param_type = type_from_metatype(resolve_datatype(param->datatype_specifier)); param->set_datatype(param_type); mi.arguments.push_back(PropertyInfo(param_type.builtin_type, param->identifier->name)); // TODO: add signal parameter default values @@ -896,11 +889,11 @@ void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, resolve_function_signature(member.function, p_source); break; case GDScriptParser::ClassNode::Member::ENUM_VALUE: { + member.enum_value.identifier->set_datatype(resolving_datatype); + if (member.enum_value.custom_value) { check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value); - member.enum_value.identifier->set_datatype(resolving_datatype); - const GDScriptParser::EnumNode *prev_enum = current_enum; current_enum = member.enum_value.parent_enum; reduce_expression(member.enum_value.custom_value); @@ -1518,14 +1511,12 @@ void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assi GDScriptParser::DataType type; type.kind = GDScriptParser::DataType::VARIANT; - bool is_variable = p_assignable->type == GDScriptParser::Node::VARIABLE; bool is_constant = p_assignable->type == GDScriptParser::Node::CONSTANT; GDScriptParser::DataType specified_type; bool has_specified_type = p_assignable->datatype_specifier != nullptr; if (has_specified_type) { - specified_type = resolve_datatype(p_assignable->datatype_specifier); - specified_type.is_meta_type = false; + specified_type = type_from_metatype(resolve_datatype(p_assignable->datatype_specifier)); type = specified_type; } @@ -1581,13 +1572,14 @@ void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assi } else if (!specified_type.is_variant()) { if (initializer_type.is_variant() || !initializer_type.is_hard_type()) { mark_node_unsafe(p_assignable->initializer); - if (is_variable) { - static_cast<GDScriptParser::VariableNode *>(p_assignable)->use_conversion_assign = true; + p_assignable->use_conversion_assign = true; + if (!initializer_type.is_variant() && !is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) { + downgrade_node_type_source(p_assignable->initializer); } } else if (!is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) { - if (is_variable && is_type_compatible(initializer_type, specified_type, true, p_assignable->initializer)) { + if (!is_constant && is_type_compatible(initializer_type, specified_type, true, p_assignable->initializer)) { mark_node_unsafe(p_assignable->initializer); - static_cast<GDScriptParser::VariableNode *>(p_assignable)->use_conversion_assign = true; + p_assignable->use_conversion_assign = true; } else { push_error(vformat(R"(Cannot assign a value of type %s to %s "%s" with specified type %s.)", initializer_type.to_string(), p_kind, p_assignable->identifier->name, specified_type.to_string()), p_assignable->initializer); } @@ -2108,84 +2100,86 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype(); + bool assignee_is_variant = assignee_type.is_variant(); + bool assignee_is_hard = assignee_type.is_hard_type(); + bool assigned_is_variant = assigned_value_type.is_variant(); + bool assigned_is_hard = assigned_value_type.is_hard_type(); bool compatible = true; + bool downgrades_assignee = false; + bool downgrades_assigned = false; GDScriptParser::DataType op_type = assigned_value_type; if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && !op_type.is_variant()) { op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value); + + if (assignee_is_variant) { + // variant assignee + mark_node_unsafe(p_assignment); + } else if (!compatible) { + // incompatible hard types and non-variant assignee + mark_node_unsafe(p_assignment); + if (assigned_is_variant) { + // incompatible hard non-variant assignee and hard variant assigned + p_assignment->use_conversion_assign = true; + } else { + // incompatible hard non-variant types + push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment); + } + } else if (op_type.type_source == GDScriptParser::DataType::UNDETECTED && !assigned_is_variant) { + // incompatible non-variant types (at least one weak) + downgrades_assignee = !assignee_is_hard; + downgrades_assigned = !assigned_is_hard; + } } p_assignment->set_datatype(op_type); - // If Assignee is a variant, then you can assign anything - // When the assigned value has a known type, further checks are possible. - if (assignee_type.is_hard_type() && !assignee_type.is_variant() && op_type.is_hard_type() && !op_type.is_variant()) { - if (compatible) { - compatible = is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value); - if (!compatible) { - // Try reverse test since it can be a masked subtype. - if (!is_type_compatible(op_type, assignee_type, true)) { - push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value); - } else { - // TODO: Add warning. - mark_node_unsafe(p_assignment); - p_assignment->use_conversion_assign = true; - } - } - } else { - push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment); + if (assignee_is_variant) { + if (!assignee_is_hard) { + // weak variant assignee + mark_node_unsafe(p_assignment); } - } else if (assignee_type.is_hard_type() && !assignee_type.is_variant()) { - mark_node_unsafe(p_assignment); - p_assignment->use_conversion_assign = true; } else { - mark_node_unsafe(p_assignment); - if (assignee_type.is_hard_type() && !assignee_type.is_variant()) { + if (assignee_is_hard && !assigned_is_hard) { + // hard non-variant assignee and weak assigned + mark_node_unsafe(p_assignment); p_assignment->use_conversion_assign = true; - } - } - - if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) { - // Change source type so it's not wrongly detected later. - GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee); - - switch (identifier->source) { - case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: { - GDScriptParser::DataType id_type = identifier->variable_source->get_datatype(); - if (!id_type.is_hard_type()) { - id_type.kind = GDScriptParser::DataType::VARIANT; - id_type.type_source = GDScriptParser::DataType::UNDETECTED; - identifier->variable_source->set_datatype(id_type); - } - } break; - case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: { - GDScriptParser::DataType id_type = identifier->parameter_source->get_datatype(); - if (!id_type.is_hard_type()) { - id_type.kind = GDScriptParser::DataType::VARIANT; - id_type.type_source = GDScriptParser::DataType::UNDETECTED; - identifier->parameter_source->set_datatype(id_type); - } - } break; - case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: { - GDScriptParser::DataType id_type = identifier->variable_source->get_datatype(); - if (!id_type.is_hard_type()) { - id_type.kind = GDScriptParser::DataType::VARIANT; - id_type.type_source = GDScriptParser::DataType::UNDETECTED; - identifier->variable_source->set_datatype(id_type); + downgrades_assigned = downgrades_assigned || (!assigned_is_variant && !is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value)); + } else if (compatible) { + if (op_type.is_variant()) { + // non-variant assignee and variant result + mark_node_unsafe(p_assignment); + if (assignee_is_hard) { + // hard non-variant assignee and variant result + p_assignment->use_conversion_assign = true; + } else { + // weak non-variant assignee and variant result + downgrades_assignee = true; } - } break; - case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: { - GDScriptParser::DataType id_type = identifier->bind_source->get_datatype(); - if (!id_type.is_hard_type()) { - id_type.kind = GDScriptParser::DataType::VARIANT; - id_type.type_source = GDScriptParser::DataType::UNDETECTED; - identifier->bind_source->set_datatype(id_type); + } else if (!is_type_compatible(assignee_type, op_type, assignee_is_hard, p_assignment->assigned_value)) { + // non-variant assignee and incompatible result + mark_node_unsafe(p_assignment); + if (assignee_is_hard) { + if (is_type_compatible(op_type, assignee_type, true, p_assignment->assigned_value)) { + // hard non-variant assignee and maybe compatible result + p_assignment->use_conversion_assign = true; + } else { + // hard non-variant assignee and incompatible result + push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value); + } + } else { + // weak non-variant assignee and incompatible result + downgrades_assignee = true; } - } break; - default: - // Nothing to do. - break; + } } } + if (downgrades_assignee) { + downgrade_node_type_source(p_assignment->assignee); + } + if (downgrades_assigned) { + downgrade_node_type_source(p_assignment->assigned_value); + } + #ifdef DEBUG_ENABLED if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) { parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION); @@ -2464,7 +2458,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a bool types_match = true; for (int i = 0; i < p_call->arguments.size(); i++) { - GDScriptParser::DataType par_type = type_from_property(info.arguments[i]); + GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true); if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) { types_match = false; @@ -2521,7 +2515,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: { PropertyInfo wrong_arg = function_info.arguments[err.argument]; push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1, - type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()), + type_from_property(wrong_arg, true).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()), p_call->arguments[err.argument]); } break; case Callable::CallError::CALL_ERROR_INVALID_METHOD: @@ -2568,7 +2562,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: { String expected_type_name; if (err.argument < function_info.arguments.size()) { - expected_type_name = type_from_property(function_info.arguments[err.argument]).to_string(); + expected_type_name = type_from_property(function_info.arguments[err.argument], true).to_string(); } else { expected_type_name = Variant::get_type_name((Variant::Type)err.expected); } @@ -2649,6 +2643,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a } else { reduce_expression(subscript->base); base_type = subscript->base->get_datatype(); + is_self = subscript->base->type == GDScriptParser::Node::SELF; } } else { // Invalid call. Error already sent in parser. @@ -2766,14 +2761,13 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) { reduce_expression(p_cast->operand); - GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type); + GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type)); if (!cast_type.is_set()) { mark_node_unsafe(p_cast); return; } - cast_type = type_from_metatype(cast_type); // The casted value won't be a type name. p_cast->set_datatype(cast_type); if (!cast_type.is_variant()) { @@ -2907,15 +2901,7 @@ GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const Str return ref->get_parser()->head->get_datatype(); } else { - type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - type.kind = GDScriptParser::DataType::SCRIPT; - type.builtin_type = Variant::OBJECT; - type.script_type = ResourceLoader::load(path, "Script"); - type.native_type = type.script_type->get_instance_base_type(); - type.script_path = path; - type.is_constant = true; - type.is_meta_type = true; - return type; + return make_script_meta_type(ResourceLoader::load(path, "Script")); } } @@ -3938,10 +3924,10 @@ GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptPars return result; } -GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const { +GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg) const { GDScriptParser::DataType result; result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) { + if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) { // Variant result.kind = GDScriptParser::DataType::VARIANT; return result; @@ -4030,6 +4016,25 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bo return false; } + StringName base_native = p_base_type.native_type; + if (base_native != StringName()) { + // Empty native class might happen in some Script implementations. + // Just ignore it. + if (!class_exists(base_native)) { + push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source); + return false; + } else if (p_is_constructor && !ClassDB::can_instantiate(base_native)) { + if (p_base_type.kind == GDScriptParser::DataType::CLASS) { + push_error(vformat(R"(Class "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.class_type->fqcn.get_file(), base_native), p_source); + } else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) { + push_error(vformat(R"(Script "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.script_path.get_file(), base_native), p_source); + } else { + push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source); + } + return false; + } + } + if (p_is_constructor) { function_name = "_init"; r_static = true; @@ -4090,17 +4095,6 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bo } } - StringName base_native = p_base_type.native_type; -#ifdef DEBUG_ENABLED - if (base_native != StringName()) { - // Empty native class might happen in some Script implementations. - // Just ignore it. - if (!class_exists(base_native)) { - ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native)); - } - } -#endif - if (p_is_constructor) { // Native types always have a default constructor. r_return_type = p_base_type; @@ -4128,7 +4122,7 @@ bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GD r_static = (p_info.flags & METHOD_FLAG_STATIC) != 0; for (const PropertyInfo &E : p_info.arguments) { - r_par_types.push_back(type_from_property(E)); + r_par_types.push_back(type_from_property(E, true)); } return true; } @@ -4137,7 +4131,7 @@ bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScr List<GDScriptParser::DataType> arg_types; for (const PropertyInfo &E : p_method.arguments) { - arg_types.push_back(type_from_property(E)); + arg_types.push_back(type_from_property(E, true)); } return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call); @@ -4255,9 +4249,6 @@ GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator } GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) { - GDScriptParser::DataType result; - result.kind = GDScriptParser::DataType::VARIANT; - Variant::Type a_type = p_a.builtin_type; Variant::Type b_type = p_b.builtin_type; @@ -4277,28 +4268,18 @@ GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator } Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type); - bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type(); bool validated = op_eval != nullptr; - if (hard_operation && !validated) { - r_valid = false; - return result; - } else if (hard_operation && validated) { + GDScriptParser::DataType result; + if (validated) { r_valid = true; - result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; + result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED; result.kind = GDScriptParser::DataType::BUILTIN; result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type); - } else if (!hard_operation && !validated) { - r_valid = true; - result.type_source = GDScriptParser::DataType::UNDETECTED; + } else { + r_valid = !hard_operation; result.kind = GDScriptParser::DataType::VARIANT; - result.builtin_type = Variant::NIL; - } else if (!hard_operation && validated) { - r_valid = true; - result.type_source = GDScriptParser::DataType::INFERRED; - result.kind = GDScriptParser::DataType::BUILTIN; - result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type); } return result; @@ -4474,6 +4455,46 @@ void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) { #endif } +void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) { + GDScriptParser::IdentifierNode *identifier = nullptr; + if (p_node->type == GDScriptParser::Node::IDENTIFIER) { + identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node); + } else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) { + GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node); + if (subscript->is_attribute) { + identifier = subscript->attribute; + } + } + if (identifier == nullptr) { + return; + } + + GDScriptParser::Node *source = nullptr; + switch (identifier->source) { + case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: { + source = identifier->variable_source; + } break; + case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: { + source = identifier->parameter_source; + } break; + case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: { + source = identifier->variable_source; + } break; + case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: { + source = identifier->bind_source; + } break; + default: + break; + } + if (source == nullptr) { + return; + } + + GDScriptParser::DataType datatype; + datatype.kind = GDScriptParser::DataType::VARIANT; + source->set_datatype(datatype); +} + void GDScriptAnalyzer::mark_lambda_use_self() { for (GDScriptParser::LambdaNode *lambda : lambda_stack) { lambda->use_self = true; diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index ecae0b4629..b22d47982f 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -108,7 +108,7 @@ class GDScriptAnalyzer { // Helpers. GDScriptParser::DataType type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source); static GDScriptParser::DataType type_from_metatype(const GDScriptParser::DataType &p_meta_type); - GDScriptParser::DataType type_from_property(const PropertyInfo &p_property) const; + GDScriptParser::DataType type_from_property(const PropertyInfo &p_property, bool p_is_arg = false) const; GDScriptParser::DataType make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source); bool get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); bool function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg); @@ -120,6 +120,7 @@ class GDScriptAnalyzer { bool is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion = false, const GDScriptParser::Node *p_source_node = nullptr); void push_error(const String &p_message, const GDScriptParser::Node *p_origin = nullptr); void mark_node_unsafe(const GDScriptParser::Node *p_node); + void downgrade_node_type_source(GDScriptParser::Node *p_node); void mark_lambda_use_self(); bool class_exists(const StringName &p_class) const; Ref<GDScriptParserRef> get_parser_for(const String &p_path); diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp index 57ee41e34e..6c80fb7665 100644 --- a/modules/gdscript/gdscript_byte_codegen.cpp +++ b/modules/gdscript/gdscript_byte_codegen.cpp @@ -872,8 +872,12 @@ void GDScriptByteCodeGenerator::write_assign_false(const Address &p_target) { append(p_target); } -void GDScriptByteCodeGenerator::write_assign_default_parameter(const Address &p_dst, const Address &p_src) { - write_assign(p_dst, p_src); +void GDScriptByteCodeGenerator::write_assign_default_parameter(const Address &p_dst, const Address &p_src, bool p_use_conversion) { + if (p_use_conversion) { + write_assign_with_conversion(p_dst, p_src); + } else { + write_assign(p_dst, p_src); + } function->default_arguments.push_back(opcodes.size()); } diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h index ac9c4c8fb5..171c505116 100644 --- a/modules/gdscript/gdscript_byte_codegen.h +++ b/modules/gdscript/gdscript_byte_codegen.h @@ -460,7 +460,7 @@ public: virtual void write_assign_with_conversion(const Address &p_target, const Address &p_source) override; virtual void write_assign_true(const Address &p_target) override; virtual void write_assign_false(const Address &p_target) override; - virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src) override; + virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src, bool p_use_conversion) override; virtual void write_store_global(const Address &p_dst, int p_global_index) override; virtual void write_store_named_global(const Address &p_dst, const StringName &p_global) override; virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) override; diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h index c7a1bcb9e9..e885938eba 100644 --- a/modules/gdscript/gdscript_codegen.h +++ b/modules/gdscript/gdscript_codegen.h @@ -113,7 +113,7 @@ public: virtual void write_assign_with_conversion(const Address &p_target, const Address &p_source) = 0; virtual void write_assign_true(const Address &p_target) = 0; virtual void write_assign_false(const Address &p_target) = 0; - virtual void write_assign_default_parameter(const Address &dst, const Address &src) = 0; + virtual void write_assign_default_parameter(const Address &dst, const Address &src, bool p_use_conversion) = 0; virtual void write_store_global(const Address &p_dst, int p_global_index) = 0; virtual void write_store_named_global(const Address &p_dst, const StringName &p_global) = 0; virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) = 0; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index beed6e90d2..77c6690d20 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -2116,7 +2116,7 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ } } - codegen.generator->write_assign_default_parameter(dst_addr, src_addr); + codegen.generator->write_assign_default_parameter(dst_addr, src_addr, parameter->use_conversion_assign); if (src_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); } diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index a6b8537074..97d5c1d8b2 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -1321,14 +1321,8 @@ GDScriptParser::EnumNode *GDScriptParser::parse_enum() { if (elements.has(item.identifier->name)) { push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier); } else if (!named) { - // TODO: Abstract this recursive member check. - ClassNode *parent = current_class; - while (parent != nullptr) { - if (parent->members_indices.has(item.identifier->name)) { - push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, parent->get_member(item.identifier->name).get_type_name())); - break; - } - parent = parent->outer; + if (current_class->members_indices.has(item.identifier->name)) { + push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, current_class->get_member(item.identifier->name).get_type_name())); } } @@ -3800,6 +3794,26 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node variable->export_info.type = Variant::INT; } } + if (p_annotation->name == SNAME("@export_multiline")) { + if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) { + DataType inner_type = export_type.get_container_element_type(); + if (inner_type.builtin_type != Variant::STRING) { + push_error(vformat(R"("%s" annotation on arrays requires a string type but type "%s" was given instead.)", p_annotation->name.operator String(), inner_type.to_string()), variable); + return false; + } + + String hint_prefix = itos(inner_type.builtin_type) + "/" + itos(variable->export_info.hint); + variable->export_info.hint = PROPERTY_HINT_TYPE_STRING; + variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string; + variable->export_info.type = Variant::ARRAY; + + return true; + } else if (export_type.builtin_type == Variant::DICTIONARY) { + variable->export_info.type = Variant::DICTIONARY; + + return true; + } + } if (p_annotation->name == SNAME("@export")) { if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) { diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 4bb02c4ea3..0903f62061 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -360,6 +360,7 @@ public: ExpressionNode *initializer = nullptr; TypeNode *datatype_specifier = nullptr; bool infer_datatype = false; + bool use_conversion_assign = false; int usages = 0; virtual ~AssignableNode() {} @@ -1182,7 +1183,6 @@ public: bool onready = false; PropertyInfo export_info; int assignments = 0; - bool use_conversion_assign = false; #ifdef TOOLS_ENABLED String doc_description; #endif // TOOLS_ENABLED diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index 04612c6793..e17a804003 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -164,6 +164,7 @@ bool GDScriptTokenizer::Token::is_identifier() const { switch (type) { case IDENTIFIER: case MATCH: // Used in String.match(). + case CONST_INF: // Used in Vector{2,3,4}.INF return true; default: return false; diff --git a/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.gd b/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.gd new file mode 100644 index 0000000000..38c2faa859 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.gd @@ -0,0 +1,2 @@ +func test(): + CanvasItem.new() diff --git a/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.out b/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.out new file mode 100644 index 0000000000..9eff912b59 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/abstract_class_instantiate.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Native class "CanvasItem" cannot be constructed as it is abstract. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.gd b/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.gd new file mode 100644 index 0000000000..118e7e8a45 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.gd @@ -0,0 +1,9 @@ +class A extends CanvasItem: + func _init(): + print('no') + +class B extends A: + pass + +func test(): + B.new() diff --git a/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.out b/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.out new file mode 100644 index 0000000000..8b956f5974 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/abstract_script_instantiate.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Class "abstract_script_instantiate.gd::B" cannot be constructed as it is based on abstract native class "CanvasItem". diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.gd b/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.gd deleted file mode 100644 index f3f3b5ffeb..0000000000 --- a/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.gd +++ /dev/null @@ -1,7 +0,0 @@ -enum { V } - -class InnerClass: - enum { V } - -func test(): - pass diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.out b/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.out deleted file mode 100644 index c9706003e1..0000000000 --- a/modules/gdscript/tests/scripts/analyzer/errors/enum_shadows_outer_enum.out +++ /dev/null @@ -1,2 +0,0 @@ -GDTEST_PARSER_ERROR -Name "V" is already used as a class enum value. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.gd b/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.gd new file mode 100644 index 0000000000..664e364493 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.gd @@ -0,0 +1,3 @@ +func test(): + var foo: bool = true + foo += 'bar' diff --git a/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.out b/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.out new file mode 100644 index 0000000000..358b096a64 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/incompatible_assignment.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Invalid operands "bool" and "String" for assignment operator. diff --git a/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.gd b/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.gd new file mode 100644 index 0000000000..2d2c2bef19 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.gd @@ -0,0 +1,19 @@ +func test(): + var one_0 = 0 + one_0 = 1 + var one_1 := one_0 + print(one_1) + + var two: Variant = 0 + two += 2 + print(two) + + var three_0: Variant = 1 + var three_1: int = 2 + three_0 += three_1 + print(three_0) + + var four_0: int = 3 + var four_1: Variant = 1 + four_0 += four_1 + print(four_0) diff --git a/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.out b/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.out new file mode 100644 index 0000000000..7536c38490 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/assignments_with_untyped.out @@ -0,0 +1,5 @@ +GDTEST_OK +1 +2 +3 +4 diff --git a/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.gd b/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.gd new file mode 100644 index 0000000000..95c3268130 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.gd @@ -0,0 +1,12 @@ +class A extends CanvasItem: + func _init(): + pass + +class B extends A: + pass + +class C extends CanvasItem: + pass + +func test(): + print('ok') diff --git a/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.out b/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.out new file mode 100644 index 0000000000..1b47ed10dc --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/extend_abstract_class.out @@ -0,0 +1,2 @@ +GDTEST_OK +ok diff --git a/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.gd b/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.gd new file mode 100644 index 0000000000..da24c06b2e --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.gd @@ -0,0 +1,6 @@ +class Check extends Node: + func _set(_property: StringName, _value: Variant) -> bool: + return true + +func test() -> void: + print('OK') diff --git a/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.out b/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.out new file mode 100644 index 0000000000..1ccb591560 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/variant_arg_in_virtual_method.out @@ -0,0 +1,2 @@ +GDTEST_OK +OK diff --git a/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.gd b/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.gd new file mode 100644 index 0000000000..4cbb464f59 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.gd @@ -0,0 +1,17 @@ +class A: + enum { X = 1 } + + class B: + enum { X = 2 } + +class C: + const X = 3 + + class D: + enum { X = 4 } + +func test(): + print(A.X) + print(A.B.X) + print(C.X) + print(C.D.X) diff --git a/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.out b/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.out new file mode 100644 index 0000000000..7536c38490 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/unnamed_enums_outer_conflicts.out @@ -0,0 +1,5 @@ +GDTEST_OK +1 +2 +3 +4 diff --git a/modules/gdscript/tests/scripts/parser/features/vector_inf.gd b/modules/gdscript/tests/scripts/parser/features/vector_inf.gd new file mode 100644 index 0000000000..039d51d9ed --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/vector_inf.gd @@ -0,0 +1,6 @@ +func test(): + var vec2: = Vector2.INF + var vec3: = Vector3.INF + + print(vec2.x == INF) + print(vec3.z == INF) diff --git a/modules/gdscript/tests/scripts/parser/features/vector_inf.out b/modules/gdscript/tests/scripts/parser/features/vector_inf.out new file mode 100644 index 0000000000..9d111a8322 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/features/vector_inf.out @@ -0,0 +1,3 @@ +GDTEST_OK +true +true diff --git a/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.gd b/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.gd new file mode 100644 index 0000000000..a72ac9b5ee --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.gd @@ -0,0 +1,8 @@ +var weakling = 'not float' +func weak(x: float = weakling): + print(x) + print('typeof x is', typeof(x)) + +func test(): + print(typeof(weak())) + print('not ok') diff --git a/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.out b/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.out new file mode 100644 index 0000000000..8543cf976e --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/errors/bad_conversion_for_default_parameter.out @@ -0,0 +1,8 @@ +GDTEST_RUNTIME_ERROR +>> SCRIPT ERROR +>> on function: weak() +>> runtime/errors/bad_conversion_for_default_parameter.gd +>> 2 +>> Trying to assign value of type 'String' to a variable of type 'float'. +0 +not ok diff --git a/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.gd b/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.gd new file mode 100644 index 0000000000..9d0c6317b3 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.gd @@ -0,0 +1,19 @@ +func literal(x: float = 1): + print('x is ', x) + print('typeof x is ', typeof(x)) + +var inferring := 2 +func inferred(x: float = inferring): + print('x is ', x) + print('typeof x is ', typeof(x)) + +var weakling = 3 +func weak(x: float = weakling): + print('x is ', x) + print('typeof x is ', typeof(x)) + +func test(): + literal() + inferred() + weak() + print('ok') diff --git a/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.out b/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.out new file mode 100644 index 0000000000..a9ef4919cf --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/conversion_for_default_parameter.out @@ -0,0 +1,8 @@ +GDTEST_OK +x is 1 +typeof x is 3 +x is 2 +typeof x is 3 +x is 3 +typeof x is 3 +ok diff --git a/modules/gdscript/tests/scripts/runtime/features/gdscript.gd b/modules/gdscript/tests/scripts/runtime/features/gdscript.gd new file mode 100644 index 0000000000..f2368643de --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/gdscript.gd @@ -0,0 +1,20 @@ +func test(): + var gdscr: = GDScript.new() + gdscr.source_code = ''' +extends Resource + +func test() -> void: + prints("Outer") + var inner = InnerClass.new() + +class InnerClass: + func _init() -> void: + prints("Inner") +''' + @warning_ignore(return_value_discarded) + gdscr.reload() + + var inst = gdscr.new() + + @warning_ignore(unsafe_method_access) + inst.test() diff --git a/modules/gdscript/tests/scripts/runtime/features/gdscript.out b/modules/gdscript/tests/scripts/runtime/features/gdscript.out new file mode 100644 index 0000000000..16114f57f7 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/gdscript.out @@ -0,0 +1,3 @@ +GDTEST_OK +Outer +Inner diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index c45fdda75c..e39127e0a1 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -688,7 +688,7 @@ bool CSharpLanguage::is_assembly_reloading_needed() { return false; // Already up to date } } else { - String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name"); + String assembly_name = GLOBAL_GET("dotnet/project/assembly_name"); if (assembly_name.is_empty()) { assembly_name = ProjectSettings::get_singleton()->get_safe_project_name(); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs index a2916d4ae8..13a21ae8bc 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs @@ -586,6 +586,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this <see cref="AABB"/> is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return _position.IsFinite() && _size.IsFinite(); + } + + /// <summary> /// Returns a larger <see cref="AABB"/> that contains this <see cref="AABB"/> and <paramref name="with"/>. /// </summary> /// <param name="with">The other <see cref="AABB"/>.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs index 5d390a298d..5aa1622bf8 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs @@ -709,6 +709,16 @@ namespace Godot ); } + /// <summary> + /// Returns <see langword="true"/> if this basis is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return Row0.IsFinite() && Row1.IsFinite() && Row2.IsFinite(); + } + internal readonly Basis Lerp(Basis to, real_t weight) { Basis b = this; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs index 3f9e986f62..b2cb0f5e6b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs @@ -440,6 +440,17 @@ namespace Godot } /// <summary> + /// Returns whether <paramref name="s"/> is a finite value, i.e. it is not + /// <see cref="NaN"/>, positive infinite, or negative infinity. + /// </summary> + /// <param name="s">The value to check.</param> + /// <returns>A <see langword="bool"/> for whether or not the value is a finite value.</returns> + public static bool IsFinite(real_t s) + { + return real_t.IsFinite(s); + } + + /// <summary> /// Returns whether <paramref name="s"/> is an infinity value (either positive infinity or negative infinity). /// </summary> /// <param name="s">The value to check.</param> @@ -460,10 +471,11 @@ namespace Godot } /// <summary> - /// Returns <see langword="true"/> if <paramref name="s"/> is approximately zero. + /// Returns <see langword="true"/> if <paramref name="s"/> is zero or almost zero. /// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>. /// - /// This method is faster than using <see cref="IsEqualApprox(real_t, real_t)"/> with one value as zero. + /// This method is faster than using <see cref="IsEqualApprox(real_t, real_t)"/> with + /// one value as zero. /// </summary> /// <param name="s">The value to check.</param> /// <returns>A <see langword="bool"/> for whether or not the value is nearly zero.</returns> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs index 42c6b0a37e..9e5f7c4f9e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs @@ -205,6 +205,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this plane is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return _normal.IsFinite() && Mathf.IsFinite(D); + } + + /// <summary> /// Returns <see langword="true"/> if <paramref name="point"/> is located above the plane. /// </summary> /// <param name="point">The point to check.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs index bd0dea0c1c..10116e9fa4 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs @@ -340,6 +340,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this quaternion is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return Mathf.IsFinite(x) && Mathf.IsFinite(y) && Mathf.IsFinite(z) && Mathf.IsFinite(w); + } + + /// <summary> /// Returns whether the quaternion is normalized or not. /// </summary> /// <returns>A <see langword="bool"/> for whether the quaternion is normalized or not.</returns> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs index b0e0e75a34..1a8696d3bc 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs @@ -101,6 +101,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this <see cref="Rect2"/> is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public bool IsFinite() + { + return _position.IsFinite() && _size.IsFinite(); + } + + /// <summary> /// Returns <see langword="true"/> if this <see cref="Rect2"/> completely encloses another one. /// </summary> /// <param name="b">The other <see cref="Rect2"/> that may be enclosed.</param> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs index 756f71e5b2..c99d91bff1 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs @@ -271,6 +271,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this transform is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return x.IsFinite() && y.IsFinite() && origin.IsFinite(); + } + + /// <summary> /// Returns the transform with the basis orthogonal (90 degrees), /// and normalized axis vectors (scale of 1 or -1). /// </summary> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs index 39167bd116..dee1e91512 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs @@ -140,6 +140,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this transform is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return basis.IsFinite() && origin.IsFinite(); + } + + /// <summary> /// Returns a copy of the transform rotated such that its /// -Z axis (forward) points towards the <paramref name="target"/> position. /// diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs index 4c60080ee9..57cbef1c5c 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs @@ -334,6 +334,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return Mathf.IsFinite(x) && Mathf.IsFinite(y); + } + + /// <summary> /// Returns <see langword="true"/> if the vector is normalized, and <see langword="false"/> otherwise. /// </summary> /// <returns>A <see langword="bool"/> indicating whether or not the vector is normalized.</returns> @@ -989,6 +999,18 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector's values are approximately zero, + /// by running <see cref="Mathf.IsZeroApprox(real_t)"/> on each component. + /// This method is faster than using <see cref="IsEqualApprox"/> with one value + /// as a zero vector. + /// </summary> + /// <returns>Whether or not the vector is approximately zero.</returns> + public readonly bool IsZeroApprox() + { + return Mathf.IsZeroApprox(x) && Mathf.IsZeroApprox(y); + } + + /// <summary> /// Serves as the hash function for <see cref="Vector2"/>. /// </summary> /// <returns>A hash code for this vector.</returns> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs index fefdee33a5..031464dcc6 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs @@ -331,6 +331,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return Mathf.IsFinite(x) && Mathf.IsFinite(y) && Mathf.IsFinite(z); + } + + /// <summary> /// Returns <see langword="true"/> if the vector is normalized, and <see langword="false"/> otherwise. /// </summary> /// <returns>A <see langword="bool"/> indicating whether or not the vector is normalized.</returns> @@ -1060,6 +1070,18 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector's values are approximately zero, + /// by running <see cref="Mathf.IsZeroApprox(real_t)"/> on each component. + /// This method is faster than using <see cref="IsEqualApprox"/> with one value + /// as a zero vector. + /// </summary> + /// <returns>Whether or not the vector is approximately zero.</returns> + public readonly bool IsZeroApprox() + { + return Mathf.IsZeroApprox(x) && Mathf.IsZeroApprox(y) && Mathf.IsZeroApprox(z); + } + + /// <summary> /// Serves as the hash function for <see cref="Vector3"/>. /// </summary> /// <returns>A hash code for this vector.</returns> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs index 3191e8adc0..0f4528bb40 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector4.cs @@ -280,6 +280,16 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector is finite, by calling + /// <see cref="Mathf.IsFinite"/> on each component. + /// </summary> + /// <returns>Whether this vector is finite or not.</returns> + public readonly bool IsFinite() + { + return Mathf.IsFinite(x) && Mathf.IsFinite(y) && Mathf.IsFinite(z) && Mathf.IsFinite(w); + } + + /// <summary> /// Returns <see langword="true"/> if the vector is normalized, and <see langword="false"/> otherwise. /// </summary> /// <returns>A <see langword="bool"/> indicating whether or not the vector is normalized.</returns> @@ -857,6 +867,18 @@ namespace Godot } /// <summary> + /// Returns <see langword="true"/> if this vector's values are approximately zero, + /// by running <see cref="Mathf.IsZeroApprox(real_t)"/> on each component. + /// This method is faster than using <see cref="IsEqualApprox"/> with one value + /// as a zero vector. + /// </summary> + /// <returns>Whether or not the vector is approximately zero.</returns> + public readonly bool IsZeroApprox() + { + return Mathf.IsZeroApprox(x) && Mathf.IsZeroApprox(y) && Mathf.IsZeroApprox(z) && Mathf.IsZeroApprox(w); + } + + /// <summary> /// Serves as the hash function for <see cref="Vector4"/>. /// </summary> /// <returns>A hash code for this vector.</returns> diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 6664dfb2dd..86b0e04206 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -289,7 +289,7 @@ godot_plugins_initialize_fn initialize_hostfxr_and_godot_plugins(bool &r_runtime } #else static String get_assembly_name() { - String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name"); + String assembly_name = GLOBAL_GET("dotnet/project/assembly_name"); if (assembly_name.is_empty()) { assembly_name = ProjectSettings::get_singleton()->get_safe_project_name(); @@ -466,7 +466,7 @@ void GDMono::_init_godot_api_hashes() { #ifdef TOOLS_ENABLED bool GDMono::_load_project_assembly() { - String assembly_name = ProjectSettings::get_singleton()->get_setting("dotnet/project/assembly_name"); + String assembly_name = GLOBAL_GET("dotnet/project/assembly_name"); if (assembly_name.is_empty()) { assembly_name = ProjectSettings::get_singleton()->get_safe_project_name(); diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp index b9b92b77c9..9b5d78d465 100644 --- a/modules/navigation/godot_navigation_server.cpp +++ b/modules/navigation/godot_navigation_server.cpp @@ -829,6 +829,15 @@ void GodotNavigationServer::process(real_t p_delta_time) { return; } + int _new_pm_region_count = 0; + int _new_pm_agent_count = 0; + int _new_pm_link_count = 0; + int _new_pm_polygon_count = 0; + int _new_pm_edge_count = 0; + int _new_pm_edge_merge_count = 0; + int _new_pm_edge_connection_count = 0; + int _new_pm_edge_free_count = 0; + // In c++ we can't be sure that this is performed in the main thread // even with mutable functions. MutexLock lock(operations_mutex); @@ -837,6 +846,15 @@ void GodotNavigationServer::process(real_t p_delta_time) { active_maps[i]->step(p_delta_time); active_maps[i]->dispatch_callbacks(); + _new_pm_region_count += active_maps[i]->get_pm_region_count(); + _new_pm_agent_count += active_maps[i]->get_pm_agent_count(); + _new_pm_link_count += active_maps[i]->get_pm_link_count(); + _new_pm_polygon_count += active_maps[i]->get_pm_polygon_count(); + _new_pm_edge_count += active_maps[i]->get_pm_edge_count(); + _new_pm_edge_merge_count += active_maps[i]->get_pm_edge_merge_count(); + _new_pm_edge_connection_count += active_maps[i]->get_pm_edge_connection_count(); + _new_pm_edge_free_count += active_maps[i]->get_pm_edge_free_count(); + // Emit a signal if a map changed. const uint32_t new_map_update_id = active_maps[i]->get_map_update_id(); if (new_map_update_id != active_maps_update_id[i]) { @@ -844,6 +862,15 @@ void GodotNavigationServer::process(real_t p_delta_time) { active_maps_update_id[i] = new_map_update_id; } } + + pm_region_count = _new_pm_region_count; + pm_agent_count = _new_pm_agent_count; + pm_link_count = _new_pm_link_count; + pm_polygon_count = _new_pm_polygon_count; + pm_edge_count = _new_pm_edge_count; + pm_edge_merge_count = _new_pm_edge_merge_count; + pm_edge_connection_count = _new_pm_edge_connection_count; + pm_edge_free_count = _new_pm_edge_free_count; } PathQueryResult GodotNavigationServer::_query_path(const PathQueryParameters &p_parameters) const { @@ -886,6 +913,40 @@ PathQueryResult GodotNavigationServer::_query_path(const PathQueryParameters &p_ return r_query_result; } +int GodotNavigationServer::get_process_info(ProcessInfo p_info) const { + switch (p_info) { + case INFO_ACTIVE_MAPS: { + return active_maps.size(); + } break; + case INFO_REGION_COUNT: { + return pm_region_count; + } break; + case INFO_AGENT_COUNT: { + return pm_agent_count; + } break; + case INFO_LINK_COUNT: { + return pm_link_count; + } break; + case INFO_POLYGON_COUNT: { + return pm_polygon_count; + } break; + case INFO_EDGE_COUNT: { + return pm_edge_count; + } break; + case INFO_EDGE_MERGE_COUNT: { + return pm_edge_merge_count; + } break; + case INFO_EDGE_CONNECTION_COUNT: { + return pm_edge_connection_count; + } break; + case INFO_EDGE_FREE_COUNT: { + return pm_edge_free_count; + } break; + } + + return 0; +} + #undef COMMAND_1 #undef COMMAND_2 #undef COMMAND_4 diff --git a/modules/navigation/godot_navigation_server.h b/modules/navigation/godot_navigation_server.h index 7a6e5bb208..a87a88d3bc 100644 --- a/modules/navigation/godot_navigation_server.h +++ b/modules/navigation/godot_navigation_server.h @@ -81,6 +81,16 @@ class GodotNavigationServer : public NavigationServer3D { LocalVector<NavMap *> active_maps; LocalVector<uint32_t> active_maps_update_id; + // Performance Monitor + int pm_region_count = 0; + int pm_agent_count = 0; + int pm_link_count = 0; + int pm_polygon_count = 0; + int pm_edge_count = 0; + int pm_edge_merge_count = 0; + int pm_edge_connection_count = 0; + int pm_edge_free_count = 0; + public: GodotNavigationServer(); virtual ~GodotNavigationServer(); @@ -182,6 +192,8 @@ public: virtual void process(real_t p_delta_time) override; virtual NavigationUtilities::PathQueryResult _query_path(const NavigationUtilities::PathQueryParameters &p_parameters) const override; + + int get_process_info(ProcessInfo p_info) const override; }; #undef COMMAND_1 diff --git a/modules/navigation/nav_map.cpp b/modules/navigation/nav_map.cpp index 2a2f8aa1b7..fd735f8793 100644 --- a/modules/navigation/nav_map.cpp +++ b/modules/navigation/nav_map.cpp @@ -611,6 +611,16 @@ void NavMap::remove_agent_as_controlled(RvoAgent *agent) { } void NavMap::sync() { + // Performance Monitor + int _new_pm_region_count = regions.size(); + int _new_pm_agent_count = agents.size(); + int _new_pm_link_count = links.size(); + int _new_pm_polygon_count = pm_polygon_count; + int _new_pm_edge_count = pm_edge_count; + int _new_pm_edge_merge_count = pm_edge_merge_count; + int _new_pm_edge_connection_count = pm_edge_connection_count; + int _new_pm_edge_free_count = pm_edge_free_count; + // Check if we need to update the links. if (regenerate_polygons) { for (uint32_t r = 0; r < regions.size(); r++) { @@ -632,6 +642,12 @@ void NavMap::sync() { } if (regenerate_links) { + _new_pm_polygon_count = 0; + _new_pm_edge_count = 0; + _new_pm_edge_merge_count = 0; + _new_pm_edge_connection_count = 0; + _new_pm_edge_free_count = 0; + // Remove regions connections. for (uint32_t r = 0; r < regions.size(); r++) { regions[r]->get_connections().clear(); @@ -654,6 +670,8 @@ void NavMap::sync() { count += regions[r]->get_polygons().size(); } + _new_pm_polygon_count = polygons.size(); + // Group all edges per key. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections; for (uint32_t poly_id = 0; poly_id < polygons.size(); poly_id++) { @@ -666,6 +684,7 @@ void NavMap::sync() { HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek); if (!connection) { connections[ek] = Vector<gd::Edge::Connection>(); + _new_pm_edge_count += 1; } if (connections[ek].size() <= 1) { // Add the polygon/edge tuple to this key. @@ -691,6 +710,7 @@ void NavMap::sync() { c1.polygon->edges[c1.edge].connections.push_back(c2); c2.polygon->edges[c2.edge].connections.push_back(c1); // Note: The pathway_start/end are full for those connection and do not need to be modified. + _new_pm_edge_merge_count += 1; } else { CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size())); free_edges.push_back(E.value[0]); @@ -704,6 +724,8 @@ void NavMap::sync() { // to be connected, create new polygons to remove that small gap is // not really useful and would result in wasteful computation during // connection, integration and path finding. + _new_pm_edge_free_count = free_edges.size(); + for (int i = 0; i < free_edges.size(); i++) { const gd::Edge::Connection &free_edge = free_edges[i]; Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos; @@ -757,6 +779,7 @@ void NavMap::sync() { // Add the connection to the region_connection map. ((NavRegion *)free_edge.polygon->owner)->get_connections().push_back(new_connection); + _new_pm_edge_connection_count += 1; } } @@ -892,6 +915,16 @@ void NavMap::sync() { regenerate_polygons = false; regenerate_links = false; agents_dirty = false; + + // Performance Monitor + pm_region_count = _new_pm_region_count; + pm_agent_count = _new_pm_agent_count; + pm_link_count = _new_pm_link_count; + pm_polygon_count = _new_pm_polygon_count; + pm_edge_count = _new_pm_edge_count; + pm_edge_merge_count = _new_pm_edge_merge_count; + pm_edge_connection_count = _new_pm_edge_connection_count; + pm_edge_free_count = _new_pm_edge_free_count; } void NavMap::compute_single_step(uint32_t index, RvoAgent **agent) { diff --git a/modules/navigation/nav_map.h b/modules/navigation/nav_map.h index 321d5560f0..fce7aff3ba 100644 --- a/modules/navigation/nav_map.h +++ b/modules/navigation/nav_map.h @@ -89,6 +89,16 @@ class NavMap : public NavRid { /// Change the id each time the map is updated. uint32_t map_update_id = 0; + // Performance Monitor + int pm_region_count = 0; + int pm_agent_count = 0; + int pm_link_count = 0; + int pm_polygon_count = 0; + int pm_edge_count = 0; + int pm_edge_merge_count = 0; + int pm_edge_connection_count = 0; + int pm_edge_free_count = 0; + public: NavMap(); ~NavMap(); @@ -152,6 +162,16 @@ public: void step(real_t p_deltatime); void dispatch_callbacks(); + // Performance Monitor + int get_pm_region_count() const { return pm_region_count; } + int get_pm_agent_count() const { return pm_agent_count; } + int get_pm_link_count() const { return pm_link_count; } + int get_pm_polygon_count() const { return pm_polygon_count; } + int get_pm_edge_count() const { return pm_edge_count; } + int get_pm_edge_merge_count() const { return pm_edge_merge_count; } + int get_pm_edge_connection_count() const { return pm_edge_connection_count; } + int get_pm_edge_free_count() const { return pm_edge_free_count; } + private: void compute_single_step(uint32_t index, RvoAgent **agent); void clip_path(const LocalVector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly, Vector<int32_t> *r_path_types, TypedArray<RID> *r_path_rids, Vector<int64_t> *r_path_owners) const; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index 568e8b9b26..fff7a02fc4 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -207,11 +207,11 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans List<uint32_t> shape_owners; static_body->get_shape_owners(&shape_owners); for (uint32_t shape_owner : shape_owners) { + if (static_body->is_shape_owner_disabled(shape_owner)) { + continue; + } const int shape_count = static_body->shape_owner_get_shape_count(shape_owner); for (int i = 0; i < shape_count; i++) { - if (static_body->is_shape_owner_disabled(i)) { - continue; - } Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, i); if (s.is_null()) { continue; diff --git a/modules/openxr/extensions/openxr_opengl_extension.cpp b/modules/openxr/extensions/openxr_opengl_extension.cpp index cd371b9ed9..6ce8f0805f 100644 --- a/modules/openxr/extensions/openxr_opengl_extension.cpp +++ b/modules/openxr/extensions/openxr_opengl_extension.cpp @@ -157,7 +157,6 @@ void *OpenXROpenGLExtension::set_session_create_and_get_next_pointer(void *p_nex } void OpenXROpenGLExtension::get_usable_swapchain_formats(Vector<int64_t> &p_usable_swap_chains) { - p_usable_swap_chains.push_back(GL_SRGB8_ALPHA8); p_usable_swap_chains.push_back(GL_RGBA8); } diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index 44a2c76727..e52b87741e 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -42,7 +42,7 @@ using namespace godot; -#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) +#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get_setting_with_override(m_var) #else // Headers for building as built-in module. diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 809bfbe41a..034f88e387 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -42,7 +42,7 @@ using namespace godot; -#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) +#define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get_setting_with_override(m_var) #else // Headers for building as built-in module. diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp index 0bb7b57a35..bb1ad3d83b 100644 --- a/platform/android/export/export_plugin.cpp +++ b/platform/android/export/export_plugin.cpp @@ -43,10 +43,16 @@ #include "editor/editor_log.h" #include "editor/editor_node.h" #include "editor/editor_paths.h" +#include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "main/splash.gen.h" -#include "platform/android/logo.gen.h" -#include "platform/android/run_icon.gen.h" +#include "platform/android/logo_svg.gen.h" +#include "platform/android/run_icon_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif #include <string.h> @@ -1025,7 +1031,7 @@ void EditorExportPlatformAndroid::_fix_manifest(const Ref<EditorExportPreset> &p string_table.write[attr_value] = "com.oculus.handtracking.version"; } - if (tname == "meta-data" && attrname == "name" && value == "xr_hand_tracking_version_value") { + if (tname == "meta-data" && attrname == "value" && value == "xr_hand_tracking_version_value") { string_table.write[attr_value] = "V2.0"; } } @@ -3238,8 +3244,17 @@ void EditorExportPlatformAndroid::resolve_platform_feature_priorities(const Ref< } EditorExportPlatformAndroid::EditorExportPlatformAndroid() { - logo = ImageTexture::create_from_image(memnew(Image(_android_logo))); - run_icon = ImageTexture::create_from_image(memnew(Image(_android_run_icon))); +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _android_logo_svg, EDSCALE, upsample, false); + logo = ImageTexture::create_from_image(img); + + img_loader.create_image_from_string(img, _android_run_icon_svg, EDSCALE, upsample, false); + run_icon = ImageTexture::create_from_image(img); +#endif devices_changed.set(); plugins_changed.set(); diff --git a/platform/android/logo.png b/platform/android/logo.png Binary files differdeleted file mode 100644 index 9c8be93646..0000000000 --- a/platform/android/logo.png +++ /dev/null diff --git a/platform/android/logo.svg b/platform/android/logo.svg new file mode 100644 index 0000000000..f154e55d11 --- /dev/null +++ b/platform/android/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M22.904 20.192a1.25 1.25 0 1 1 1.25-1.25 1.25 1.25 0 0 1-1.25 1.25m-13.808 0a1.25 1.25 0 1 1 1.25-1.25 1.25 1.25 0 0 1-1.25 1.25m14.256-7.525 2.496-4.323a.52.52 0 1 0-.899-.52l-2.528 4.378a15.69 15.69 0 0 0-12.842 0L7.051 7.823a.52.52 0 1 0-.9.521l2.497 4.323C4.361 15 1.43 19.34 1 24.467h30c-.43-5.128-3.361-9.468-7.648-11.8" fill="#56d881"/></svg> diff --git a/platform/android/run_icon.png b/platform/android/run_icon.png Binary files differdeleted file mode 100644 index b687c9ac31..0000000000 --- a/platform/android/run_icon.png +++ /dev/null diff --git a/platform/android/run_icon.svg b/platform/android/run_icon.svg new file mode 100644 index 0000000000..24d930fece --- /dev/null +++ b/platform/android/run_icon.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="M11.187 9.936a.577.577 0 1 1 .578-.578.577.577 0 0 1-.578.578m-6.374 0a.577.577 0 1 1 .577-.578.577.577 0 0 1-.577.578m6.581-3.475 1.153-1.996a.24.24 0 1 0-.415-.24l-1.167 2.021a7.244 7.244 0 0 0-5.93 0L3.868 4.225a.24.24 0 1 0-.415.24l1.153 1.996a6.806 6.806 0 0 0-3.532 5.448h13.852a6.807 6.807 0 0 0-3.532-5.448" fill="#56d881" style="fill:#e0e0e0;fill-opacity:1"/></svg> diff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cpp index 43eb0f4b1f..ccd3480d11 100644 --- a/platform/ios/export/export_plugin.cpp +++ b/platform/ios/export/export_plugin.cpp @@ -32,6 +32,13 @@ #include "core/string/translation.h" #include "editor/editor_node.h" +#include "editor/editor_scale.h" +#include "platform/ios/logo_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif void EditorExportPlatformIOS::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const { // Vulkan and OpenGL ES 3.0 both mandate ETC2 support. @@ -1926,7 +1933,15 @@ bool EditorExportPlatformIOS::has_valid_project_configuration(const Ref<EditorEx } EditorExportPlatformIOS::EditorExportPlatformIOS() { - logo = ImageTexture::create_from_image(memnew(Image(_ios_logo))); +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _ios_logo_svg, EDSCALE, upsample, false); + logo = ImageTexture::create_from_image(img); +#endif + plugins_changed.set(); #ifndef ANDROID_ENABLED check_for_changes_thread.start(_check_for_changes_poll_thread, this); diff --git a/platform/ios/export/export_plugin.h b/platform/ios/export/export_plugin.h index deadec4b43..628dae2e6f 100644 --- a/platform/ios/export/export_plugin.h +++ b/platform/ios/export/export_plugin.h @@ -43,7 +43,6 @@ #include "editor/editor_settings.h" #include "editor/export/editor_export_platform.h" #include "main/splash.gen.h" -#include "platform/ios/logo.gen.h" #include "string.h" #include "godot_plugin_config.h" diff --git a/platform/ios/logo.png b/platform/ios/logo.png Binary files differdeleted file mode 100644 index 966d8aa70a..0000000000 --- a/platform/ios/logo.png +++ /dev/null diff --git a/platform/ios/logo.svg b/platform/ios/logo.svg new file mode 100644 index 0000000000..47a72bcf49 --- /dev/null +++ b/platform/ios/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M1 23.27h2.504V12.61H1zm1.247-12.057c.784 0 1.398-.603 1.398-1.358 0-.764-.614-1.367-1.398-1.367-.774 0-1.388.603-1.388 1.367 0 .755.614 1.358 1.388 1.358zm9.594-2.695c-4.233 0-6.888 2.886-6.888 7.502s2.654 7.492 6.888 7.492c4.224 0 6.88-2.876 6.88-7.492s-2.656-7.502-6.88-7.502zm0 2.212c2.585 0 4.234 2.052 4.234 5.29 0 3.228-1.649 5.28-4.234 5.28-2.594 0-4.233-2.052-4.233-5.28 0-3.238 1.639-5.29 4.233-5.29zm7.936 8.458c.11 2.675 2.303 4.324 5.641 4.324 3.51 0 5.723-1.73 5.723-4.485 0-2.162-1.247-3.379-4.194-4.053l-1.67-.382c-1.78-.422-2.513-.985-2.513-1.95 0-1.208 1.106-2.012 2.745-2.012 1.66 0 2.796.814 2.916 2.172H30.9c-.06-2.554-2.172-4.284-5.37-4.284-3.158 0-5.4 1.74-5.4 4.314 0 2.072 1.267 3.36 3.942 3.973l1.88.442c1.83.433 2.575 1.036 2.575 2.082 0 1.207-1.217 2.072-2.967 2.072-1.77 0-3.107-.875-3.268-2.213h-2.514z" fill="#bfbfbf"/></svg> diff --git a/platform/linuxbsd/export/export.cpp b/platform/linuxbsd/export/export.cpp index e6925a2011..2c5a945b6c 100644 --- a/platform/linuxbsd/export/export.cpp +++ b/platform/linuxbsd/export/export.cpp @@ -36,7 +36,6 @@ void register_linuxbsd_exporter() { Ref<EditorExportPlatformLinuxBSD> platform; platform.instantiate(); - platform->set_logo(ImageTexture::create_from_image(memnew(Image(_linuxbsd_logo)))); platform->set_name("Linux/X11"); platform->set_os_name("Linux"); platform->set_chmod_flags(0755); diff --git a/platform/linuxbsd/export/export_plugin.cpp b/platform/linuxbsd/export/export_plugin.cpp index f6e59bf465..c900cad007 100644 --- a/platform/linuxbsd/export/export_plugin.cpp +++ b/platform/linuxbsd/export/export_plugin.cpp @@ -32,6 +32,15 @@ #include "core/config/project_settings.h" #include "editor/editor_node.h" +#include "editor/editor_paths.h" +#include "editor/editor_scale.h" +#include "platform/linuxbsd/logo_svg.gen.h" +#include "platform/linuxbsd/run_icon_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif Error EditorExportPlatformLinuxBSD::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) { Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); @@ -49,26 +58,47 @@ Error EditorExportPlatformLinuxBSD::_export_debug_script(const Ref<EditorExportP } Error EditorExportPlatformLinuxBSD::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) { - Error err = EditorExportPlatformPC::export_project(p_preset, p_debug, p_path, p_flags); - - if (err != OK) { - return err; - } + bool export_as_zip = p_path.ends_with("zip"); - String app_name; + String pkg_name; if (String(GLOBAL_GET("application/config/name")) != "") { - app_name = String(GLOBAL_GET("application/config/name")); + pkg_name = String(GLOBAL_GET("application/config/name")); } else { - app_name = "Unnamed"; + pkg_name = "Unnamed"; + } + + pkg_name = OS::get_singleton()->get_safe_dir_name(pkg_name); + + // Setup temp folder. + String path = p_path; + String tmp_dir_path = EditorPaths::get_singleton()->get_cache_dir().path_join(pkg_name); + + Ref<DirAccess> tmp_app_dir = DirAccess::create_for_path(tmp_dir_path); + if (export_as_zip) { + if (tmp_app_dir.is_null()) { + return ERR_CANT_CREATE; + } + if (DirAccess::exists(tmp_dir_path)) { + if (tmp_app_dir->change_dir(tmp_dir_path) == OK) { + tmp_app_dir->erase_contents_recursive(); + } + } + tmp_app_dir->make_dir_recursive(tmp_dir_path); + path = tmp_dir_path.path_join(p_path.get_file().get_basename()); + } + + // Export project. + Error err = EditorExportPlatformPC::export_project(p_preset, p_debug, path, p_flags); + if (err != OK) { + return err; } - app_name = OS::get_singleton()->get_safe_dir_name(app_name); // Save console script. if (err == OK) { int con_scr = p_preset->get("debug/export_console_script"); if ((con_scr == 1 && p_debug) || (con_scr == 2)) { - String scr_path = p_path.get_basename() + ".sh"; - err = _export_debug_script(p_preset, app_name, p_path.get_file(), scr_path); + String scr_path = path.get_basename() + ".sh"; + err = _export_debug_script(p_preset, pkg_name, path.get_file(), scr_path); FileAccess::set_unix_permissions(scr_path, 0755); if (err != OK) { add_message(EXPORT_MESSAGE_ERROR, TTR("Debug Script Export"), TTR("Could not create console script.")); @@ -76,6 +106,27 @@ Error EditorExportPlatformLinuxBSD::export_project(const Ref<EditorExportPreset> } } + // ZIP project. + if (export_as_zip) { + if (FileAccess::exists(p_path)) { + OS::get_singleton()->move_to_trash(p_path); + } + + Ref<FileAccess> io_fa_dst; + zlib_filefunc_def io_dst = zipio_create_io(&io_fa_dst); + zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io_dst); + + zip_folder_recursive(zip, tmp_dir_path, "", pkg_name); + + zipClose(zip, nullptr); + + if (tmp_app_dir->change_dir(tmp_dir_path) == OK) { + tmp_app_dir->erase_contents_recursive(); + tmp_app_dir->change_dir(".."); + tmp_app_dir->remove(pkg_name); + } + } + return err; } @@ -86,12 +137,51 @@ String EditorExportPlatformLinuxBSD::get_template_file_name(const String &p_targ List<String> EditorExportPlatformLinuxBSD::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const { List<String> list; list.push_back(p_preset->get("binary_format/architecture")); + list.push_back("zip"); + return list; } void EditorExportPlatformLinuxBSD::get_export_options(List<ExportOption> *r_options) { EditorExportPlatformPC::get_export_options(r_options); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "binary_format/architecture", PROPERTY_HINT_ENUM, "x86_64,x86_32,arm64,arm32,rv64,ppc64,ppc32"), "x86_64")); + + String run_script = "#!/usr/bin/env bash\n" + "export DISPLAY=:0\n" + "unzip -o -q \"{temp_dir}/{archive_name}\" -d \"{temp_dir}\"\n" + "\"{temp_dir}/{exe_name}\" {cmd_args}"; + + String cleanup_script = "#!/usr/bin/env bash\n" + "kill $(pgrep -x -f \"{temp_dir}/{exe_name} {cmd_args}\")\n" + "rm -rf \"{temp_dir}\""; + + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "ssh_remote_deploy/enabled"), false)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/host"), "user@host_ip")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/port"), "22")); + + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_ssh", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_scp", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/run_script", PROPERTY_HINT_MULTILINE_TEXT), run_script)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/cleanup_script", PROPERTY_HINT_MULTILINE_TEXT), cleanup_script)); +} + +bool EditorExportPlatformLinuxBSD::is_elf(const String &p_path) const { + Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("Can't open file: \"%s\".", p_path)); + uint32_t magic = fb->get_32(); + return (magic == 0x464c457f); +} + +bool EditorExportPlatformLinuxBSD::is_shebang(const String &p_path) const { + Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("Can't open file: \"%s\".", p_path)); + uint16_t magic = fb->get_16(); + return (magic == 0x2123); +} + +bool EditorExportPlatformLinuxBSD::is_executable(const String &p_path) const { + return is_elf(p_path) || is_shebang(p_path); } Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) { @@ -200,3 +290,235 @@ Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int } return OK; } + +Ref<Texture2D> EditorExportPlatformLinuxBSD::get_run_icon() const { + return run_icon; +} + +bool EditorExportPlatformLinuxBSD::poll_export() { + Ref<EditorExportPreset> preset; + + for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i); + if (ep->is_runnable() && ep->get_platform() == this) { + preset = ep; + break; + } + } + + int prev = menu_options; + menu_options = (preset.is_valid() && preset->get("ssh_remote_deploy/enabled").operator bool()); + if (ssh_pid != 0 || !cleanup_commands.is_empty()) { + if (menu_options == 0) { + cleanup(); + } else { + menu_options += 1; + } + } + return menu_options != prev; +} + +Ref<ImageTexture> EditorExportPlatformLinuxBSD::get_option_icon(int p_index) const { + return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index); +} + +int EditorExportPlatformLinuxBSD::get_options_count() const { + return menu_options; +} + +String EditorExportPlatformLinuxBSD::get_option_label(int p_index) const { + return (p_index) ? TTR("Stop and uninstall") : TTR("Run on remote Linux/BSD system"); +} + +String EditorExportPlatformLinuxBSD::get_option_tooltip(int p_index) const { + return (p_index) ? TTR("Stop and uninstall running project from the remote system") : TTR("Run exported project on remote Linux/BSD system"); +} + +void EditorExportPlatformLinuxBSD::cleanup() { + if (ssh_pid != 0 && OS::get_singleton()->is_process_running(ssh_pid)) { + print_line("Terminating connection..."); + OS::get_singleton()->kill(ssh_pid); + OS::get_singleton()->delay_usec(1000); + } + + if (!cleanup_commands.is_empty()) { + print_line("Stopping and deleting previous version..."); + for (const SSHCleanupCommand &cmd : cleanup_commands) { + if (cmd.wait) { + ssh_run_on_remote(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } else { + ssh_run_on_remote_no_wait(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } + } + } + ssh_pid = 0; + cleanup_commands.clear(); +} + +Error EditorExportPlatformLinuxBSD::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) { + cleanup(); + if (p_device) { // Stop command, cleanup only. + return OK; + } + + EditorProgress ep("run", TTR("Running..."), 5); + + const String dest = EditorPaths::get_singleton()->get_cache_dir().path_join("linuxbsd"); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (!da->dir_exists(dest)) { + Error err = da->make_dir_recursive(dest); + if (err != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not create temp directory:") + "\n" + dest); + return err; + } + } + + String host = p_preset->get("ssh_remote_deploy/host").operator String(); + String port = p_preset->get("ssh_remote_deploy/port").operator String(); + if (port.is_empty()) { + port = "22"; + } + Vector<String> extra_args_ssh = p_preset->get("ssh_remote_deploy/extra_args_ssh").operator String().split(" "); + Vector<String> extra_args_scp = p_preset->get("ssh_remote_deploy/extra_args_scp").operator String().split(" "); + + const String basepath = dest.path_join("tmp_linuxbsd_export"); + +#define CLEANUP_AND_RETURN(m_err) \ + { \ + if (da->file_exists(basepath + ".zip")) { \ + da->remove(basepath + ".zip"); \ + } \ + if (da->file_exists(basepath + "_start.sh")) { \ + da->remove(basepath + "_start.sh"); \ + } \ + if (da->file_exists(basepath + "_clean.sh")) { \ + da->remove(basepath + "_clean.sh"); \ + } \ + return m_err; \ + } \ + ((void)0) + + if (ep.step(TTR("Exporting project..."), 1)) { + return ERR_SKIP; + } + Error err = export_project(p_preset, true, basepath + ".zip", p_debug_flags); + if (err != OK) { + DirAccess::remove_file_or_error(basepath + ".zip"); + return err; + } + + String cmd_args; + { + Vector<String> cmd_args_list; + gen_debug_flags(cmd_args_list, p_debug_flags); + for (int i = 0; i < cmd_args_list.size(); i++) { + if (i != 0) { + cmd_args += " "; + } + cmd_args += cmd_args_list[i]; + } + } + + const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT); + int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port"); + + print_line("Creating temporary directory..."); + ep.step(TTR("Creating temporary directory..."), 2); + String temp_dir; + err = ssh_run_on_remote(host, port, extra_args_ssh, "mktemp -d", &temp_dir); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + + print_line("Uploading archive..."); + ep.step(TTR("Uploading archive..."), 3); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + ".zip", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + { + String run_script = p_preset->get("ssh_remote_deploy/run_script"); + run_script = run_script.replace("{temp_dir}", temp_dir); + run_script = run_script.replace("{archive_name}", basepath.get_file() + ".zip"); + run_script = run_script.replace("{exe_name}", basepath.get_file()); + run_script = run_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_start.sh", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(run_script); + } + + { + String clean_script = p_preset->get("ssh_remote_deploy/cleanup_script"); + clean_script = clean_script.replace("{temp_dir}", temp_dir); + clean_script = clean_script.replace("{archive_name}", basepath.get_file() + ".zip"); + clean_script = clean_script.replace("{exe_name}", basepath.get_file()); + clean_script = clean_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_clean.sh", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(clean_script); + } + + print_line("Uploading scripts..."); + ep.step(TTR("Uploading scripts..."), 4); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_start.sh", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + err = ssh_run_on_remote(host, port, extra_args_ssh, vformat("chmod +x \"%s/%s\"", temp_dir, basepath.get_file() + "_start.sh")); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_clean.sh", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + err = ssh_run_on_remote(host, port, extra_args_ssh, vformat("chmod +x \"%s/%s\"", temp_dir, basepath.get_file() + "_clean.sh")); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + + print_line("Starting project..."); + ep.step(TTR("Starting project..."), 5); + err = ssh_run_on_remote_no_wait(host, port, extra_args_ssh, vformat("\"%s/%s\"", temp_dir, basepath.get_file() + "_start.sh"), &ssh_pid, (use_remote) ? dbg_port : -1); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + cleanup_commands.clear(); + cleanup_commands.push_back(SSHCleanupCommand(host, port, extra_args_ssh, vformat("\"%s/%s\"", temp_dir, basepath.get_file() + "_clean.sh"))); + + print_line("Project started."); + + CLEANUP_AND_RETURN(OK); +#undef CLEANUP_AND_RETURN +} + +EditorExportPlatformLinuxBSD::EditorExportPlatformLinuxBSD() { +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _linuxbsd_logo_svg, EDSCALE, upsample, false); + set_logo(ImageTexture::create_from_image(img)); + + img_loader.create_image_from_string(img, _linuxbsd_run_icon_svg, EDSCALE, upsample, false); + run_icon = ImageTexture::create_from_image(img); +#endif + + Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme(); + if (theme.is_valid()) { + stop_icon = theme->get_icon(SNAME("Stop"), SNAME("EditorIcons")); + } else { + stop_icon.instantiate(); + } +} diff --git a/platform/linuxbsd/export/export_plugin.h b/platform/linuxbsd/export/export_plugin.h index 71cf18ff3e..4f860c3fd0 100644 --- a/platform/linuxbsd/export/export_plugin.h +++ b/platform/linuxbsd/export/export_plugin.h @@ -34,19 +34,58 @@ #include "core/io/file_access.h" #include "editor/editor_settings.h" #include "editor/export/editor_export_platform_pc.h" -#include "platform/linuxbsd/logo.gen.h" #include "scene/resources/texture.h" class EditorExportPlatformLinuxBSD : public EditorExportPlatformPC { + HashMap<String, String> extensions; + + struct SSHCleanupCommand { + String host; + String port; + Vector<String> ssh_args; + String cmd_args; + bool wait = false; + + SSHCleanupCommand(){}; + SSHCleanupCommand(const String &p_host, const String &p_port, const Vector<String> &p_ssh_arg, const String &p_cmd_args, bool p_wait = false) { + host = p_host; + port = p_port; + ssh_args = p_ssh_arg; + cmd_args = p_cmd_args; + wait = p_wait; + }; + }; + + Ref<ImageTexture> run_icon; + Ref<ImageTexture> stop_icon; + + Vector<SSHCleanupCommand> cleanup_commands; + OS::ProcessID ssh_pid = 0; + int menu_options = 0; + + bool is_elf(const String &p_path) const; + bool is_shebang(const String &p_path) const; + Error _export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path); public: - void set_extension(const String &p_extension, const String &p_feature_key = "default"); - virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override; virtual void get_export_options(List<ExportOption> *r_options) override; + virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override; virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override; virtual String get_template_file_name(const String &p_target, const String &p_arch) const override; virtual Error fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) override; + virtual bool is_executable(const String &p_path) const override; + + virtual Ref<Texture2D> get_run_icon() const override; + virtual bool poll_export() override; + virtual Ref<ImageTexture> get_option_icon(int p_index) const override; + virtual int get_options_count() const override; + virtual String get_option_label(int p_index) const override; + virtual String get_option_tooltip(int p_index) const override; + virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) override; + virtual void cleanup() override; + + EditorExportPlatformLinuxBSD(); }; #endif // LINUXBSD_EXPORT_PLUGIN_H diff --git a/platform/linuxbsd/logo.png b/platform/linuxbsd/logo.png Binary files differdeleted file mode 100644 index 078654b757..0000000000 --- a/platform/linuxbsd/logo.png +++ /dev/null diff --git a/platform/linuxbsd/logo.svg b/platform/linuxbsd/logo.svg new file mode 100644 index 0000000000..e5f9f03e0c --- /dev/null +++ b/platform/linuxbsd/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32"><path d="M13 31h6s3 0 6-6c2.864-5.727-6-17-6-17h-6S3.775 18.55 7 25c3 6 6 6 6 6z" fill="#fff"/><path d="M15.876 28.636c-.05.322-.116.637-.204.941-.142.496-.35.993-.659 1.416.32.02.649.023.985.007a9.1 9.1 0 0 0 .985-.007c-.309-.423-.516-.92-.659-1.416a7.666 7.666 0 0 1-.203-.94l-.123.003c-.04 0-.081-.003-.122-.004z" fill="#333"/><path d="M21.693 21.916c-.629.01-.934.633-1.497.7-.694.08-1.128-.722-2.11-.123-.98.6-1.826 7.473.45 8.409 2.274.935 6.506-4.545 6.23-5.662-.275-1.116-1.146-.853-1.582-1.399-.436-.545.003-1.41-.995-1.82a1.246 1.246 0 0 0-.496-.105zm-11.461 0a1.315 1.315 0 0 0-.421.105c-.998.41-.56 1.275-.995 1.82-.436.546-1.31.283-1.586 1.4-.275 1.116 3.956 6.596 6.232 5.66 2.275-.935 1.429-7.808.448-8.408-.981-.6-1.415.204-2.11.122-.584-.068-.888-.739-1.568-.7z" fill="#f4bb37"/><path d="M15.998.99c-2.934 0-4.657 1.79-4.982 4.204-.324 2.414.198 2.856-.614 5.328-.813 2.472-4.456 6.71-4.37 10.62.026 1.217.166 2.27.41 3.192.3-.496.743-.846 1.066-.995.253-.117.375-.173.432-.194.008-.062.04-.205.098-.485.08-.386.387-.99.91-1.386-.005-.12-.01-.239-.013-.363-.06-3.033 3.073-6.318 3.65-8.236.577-1.917.326-2.114.421-2.59.096-.477.463-1.032.992-1.475a.23.23 0 0 1 .15-.06c.482-.005.965 1.75 1.898 1.752.933 0 1.419-2.141 1.956-1.692.529.443.896.998.992 1.474.095.477-.156.674.42 2.591.578 1.918 3.708 5.203 3.648 8.236-.003.123-.008.24-.014.36.526.396.834 1.002.914 1.389.058.28.09.423.098.485.057.021.18.08.432.197.323.15.764.499 1.063.995.244-.922.387-1.976.414-3.195.085-3.91-3.562-8.148-4.374-10.62-.813-2.472-.287-2.914-.611-5.328C20.659 2.78 18.933.99 15.998.99z" fill="#333"/></svg> diff --git a/platform/linuxbsd/run_icon.svg b/platform/linuxbsd/run_icon.svg new file mode 100644 index 0000000000..56465a0df3 --- /dev/null +++ b/platform/linuxbsd/run_icon.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="M7.941 13.966a3.62 3.62 0 0 1-.096.444 2.129 2.129 0 0 1-.31.668c.15.01.305.01.464.003.16.008.314.007.465-.003a2.129 2.129 0 0 1-.31-.668 3.62 3.62 0 0 1-.097-.444l-.058.001-.058-.001z" fill="#333" style="stroke-width:.472092;fill:#e0e0e0;fill-opacity:1"/><path d="M10.688 10.793c-.297.005-.441.299-.707.33-.328.038-.533-.34-.996-.058-.463.283-.862 3.528.212 3.97 1.074.442 3.072-2.146 2.942-2.673-.13-.527-.542-.403-.747-.66-.206-.258 0-.666-.47-.86a.588.588 0 0 0-.234-.05zm-5.411 0a.62.62 0 0 0-.199.05c-.47.193-.264.601-.47.859-.205.257-.618.133-.748.66s1.867 3.115 2.942 2.673c1.074-.442.674-3.687.211-3.97-.463-.283-.668.096-.995.058-.277-.032-.42-.349-.741-.33z" fill="#f4bb37" style="stroke-width:.472092;fill:#e0e0e0;fill-opacity:1"/><path d="M8 .914c-1.386 0-2.2.845-2.353 1.985-.153 1.14.094 1.348-.29 2.515s-2.103 3.168-2.063 5.013c.012.575.078 1.072.194 1.507a1.25 1.25 0 0 1 .503-.47 4.37 4.37 0 0 1 .204-.09c.004-.03.019-.098.046-.23.038-.182.183-.467.43-.654a4.773 4.773 0 0 1-.006-.172c-.029-1.431 1.45-2.982 1.723-3.888.272-.905.154-.998.199-1.223.045-.225.218-.487.468-.696a.11.11 0 0 1 .07-.028c.228-.003.456.826.897.827.44 0 .67-1.01.923-.799.25.21.423.471.468.696.045.225-.073.318.199 1.223.272.906 1.75 2.457 1.722 3.888-.001.058-.004.114-.007.17a1.2 1.2 0 0 1 .432.656c.027.132.042.2.046.23.027.01.085.037.204.092.153.07.36.236.502.47.115-.435.183-.933.195-1.509.04-1.845-1.681-3.846-2.065-5.013-.383-1.167-.135-1.376-.288-2.515C10.2 1.759 9.385.914 7.999.914Z" fill="#333" style="stroke-width:.472092;fill:#e0e0e0;fill-opacity:1"/></svg> diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm index 759ae03d95..865b8d9711 100644 --- a/platform/macos/display_server_macos.mm +++ b/platform/macos/display_server_macos.mm @@ -166,6 +166,17 @@ DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mod layer.contentsScale = scale; } + NSColor *bg_color = [NSColor windowBackgroundColor]; + Color _bg_color; + if (_get_window_early_clear_override(_bg_color)) { + bg_color = [NSColor colorWithCalibratedRed:_bg_color.r green:_bg_color.g blue:_bg_color.b alpha:1.f]; + } + + [wd.window_object setBackgroundColor:bg_color]; + if (layer) { + [layer setBackgroundColor:bg_color.CGColor]; + } + #if defined(VULKAN_ENABLED) if (context_vulkan) { Error err = context_vulkan->window_create(window_id_counter, p_vsync_mode, wd.window_view, p_rect.size.width, p_rect.size.height); @@ -273,12 +284,17 @@ void DisplayServerMacOS::_set_window_per_pixel_transparency_enabled(bool p_enabl #endif wd.layered_window = true; } else { - [wd.window_object setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1]]; + NSColor *bg_color = [NSColor windowBackgroundColor]; + Color _bg_color; + if (_get_window_early_clear_override(_bg_color)) { + bg_color = [NSColor colorWithCalibratedRed:_bg_color.r green:_bg_color.g blue:_bg_color.b alpha:1.f]; + } + [wd.window_object setBackgroundColor:bg_color]; [wd.window_object setOpaque:YES]; [wd.window_object setHasShadow:YES]; CALayer *layer = [(NSView *)wd.window_view layer]; if (layer) { - [layer setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1].CGColor]; + [layer setBackgroundColor:bg_color.CGColor]; [layer setOpaque:YES]; } #if defined(GLES3_ENABLED) diff --git a/platform/macos/export/export_plugin.cpp b/platform/macos/export/export_plugin.cpp index 46485da783..73fbd45400 100644 --- a/platform/macos/export/export_plugin.cpp +++ b/platform/macos/export/export_plugin.cpp @@ -38,8 +38,14 @@ #include "core/string/translation.h" #include "editor/editor_node.h" #include "editor/editor_paths.h" +#include "editor/editor_scale.h" +#include "platform/macos/logo_svg.gen.h" +#include "platform/macos/run_icon_svg.gen.h" -#include "modules/modules_enabled.gen.h" // For regex. +#include "modules/modules_enabled.gen.h" // For svg and regex. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif void EditorExportPlatformMacOS::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const { if (p_preset->get("texture_format/s3tc")) { @@ -207,6 +213,23 @@ void EditorExportPlatformMacOS::get_export_options(List<ExportOption> *r_options r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/s3tc"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc"), false)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc2"), false)); + + String run_script = "#!/usr/bin/env bash\n" + "unzip -o -q \"{temp_dir}/{archive_name}\" -d \"{temp_dir}\"\n" + "open \"{temp_dir}/{exe_name}.app\" --args {cmd_args}"; + + String cleanup_script = "#!/usr/bin/env bash\n" + "kill $(pgrep -x -f \"{temp_dir}/{exe_name}.app/Contents/MacOS/{exe_name} {cmd_args}\")\n" + "rm -rf \"{temp_dir}\""; + + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "ssh_remote_deploy/enabled"), false)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/host"), "user@host_ip")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/port"), "22")); + + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_ssh", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_scp", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/run_script", PROPERTY_HINT_MULTILINE_TEXT), run_script)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/cleanup_script", PROPERTY_HINT_MULTILINE_TEXT), cleanup_script)); } void _rgba8_to_packbits_encode(int p_ch, int p_size, Vector<uint8_t> &p_source, Vector<uint8_t> &p_dest) { @@ -993,7 +1016,7 @@ Error EditorExportPlatformMacOS::_create_dmg(const String &p_dmg_path, const Str return OK; } -bool EditorExportPlatformMacOS::is_shbang(const String &p_path) const { +bool EditorExportPlatformMacOS::is_shebang(const String &p_path) const { Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("Can't open file: \"%s\".", p_path)); uint16_t magic = fb->get_16(); @@ -1001,7 +1024,7 @@ bool EditorExportPlatformMacOS::is_shbang(const String &p_path) const { } bool EditorExportPlatformMacOS::is_executable(const String &p_path) const { - return MachO::is_macho(p_path) || LipO::is_lipo(p_path) || is_shbang(p_path); + return MachO::is_macho(p_path) || LipO::is_lipo(p_path) || is_shebang(p_path); } Error EditorExportPlatformMacOS::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) { @@ -1082,7 +1105,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p } else { pkg_name = "Unnamed"; } - pkg_name = OS::get_singleton()->get_safe_dir_name(pkg_name); String export_format; @@ -1684,7 +1706,7 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p zlib_filefunc_def io_dst = zipio_create_io(&io_fa_dst); zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io_dst); - _zip_folder_recursive(zip, tmp_base_path_name, "", pkg_name); + zip_folder_recursive(zip, tmp_base_path_name, "", pkg_name); zipClose(zip, nullptr); } @@ -1723,119 +1745,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p return err; } -void EditorExportPlatformMacOS::_zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name) { - String dir = p_folder.is_empty() ? p_root_path : p_root_path.path_join(p_folder); - - Ref<DirAccess> da = DirAccess::open(dir); - da->list_dir_begin(); - String f = da->get_next(); - while (!f.is_empty()) { - if (f == "." || f == "..") { - f = da->get_next(); - continue; - } - if (da->is_link(f)) { - OS::DateTime dt = OS::get_singleton()->get_datetime(); - - zip_fileinfo zipfi; - zipfi.tmz_date.tm_year = dt.year; - zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ - zipfi.tmz_date.tm_mday = dt.day; - zipfi.tmz_date.tm_hour = dt.hour; - zipfi.tmz_date.tm_min = dt.minute; - zipfi.tmz_date.tm_sec = dt.second; - zipfi.dosDate = 0; - // 0120000: symbolic link type - // 0000755: permissions rwxr-xr-x - // 0000644: permissions rw-r--r-- - uint32_t _mode = 0120644; - zipfi.external_fa = (_mode << 16L) | !(_mode & 0200); - zipfi.internal_fa = 0; - - zipOpenNewFileInZip4(p_zip, - p_folder.path_join(f).utf8().get_data(), - &zipfi, - nullptr, - 0, - nullptr, - 0, - nullptr, - Z_DEFLATED, - Z_DEFAULT_COMPRESSION, - 0, - -MAX_WBITS, - DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, - nullptr, - 0, - 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions - 0); - - String target = da->read_link(f); - zipWriteInFileInZip(p_zip, target.utf8().get_data(), target.utf8().size()); - zipCloseFileInZip(p_zip); - } else if (da->current_is_dir()) { - _zip_folder_recursive(p_zip, p_root_path, p_folder.path_join(f), p_pkg_name); - } else { - OS::DateTime dt = OS::get_singleton()->get_datetime(); - - zip_fileinfo zipfi; - zipfi.tmz_date.tm_year = dt.year; - zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ - zipfi.tmz_date.tm_mday = dt.day; - zipfi.tmz_date.tm_hour = dt.hour; - zipfi.tmz_date.tm_min = dt.minute; - zipfi.tmz_date.tm_sec = dt.second; - zipfi.dosDate = 0; - // 0100000: regular file type - // 0000755: permissions rwxr-xr-x - // 0000644: permissions rw-r--r-- - uint32_t _mode = (is_executable(dir.path_join(f)) ? 0100755 : 0100644); - zipfi.external_fa = (_mode << 16L) | !(_mode & 0200); - zipfi.internal_fa = 0; - - zipOpenNewFileInZip4(p_zip, - p_folder.path_join(f).utf8().get_data(), - &zipfi, - nullptr, - 0, - nullptr, - 0, - nullptr, - Z_DEFLATED, - Z_DEFAULT_COMPRESSION, - 0, - -MAX_WBITS, - DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, - nullptr, - 0, - 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions - 0); - - Ref<FileAccess> fa = FileAccess::open(dir.path_join(f), FileAccess::READ); - if (fa.is_null()) { - add_message(EXPORT_MESSAGE_ERROR, TTR("ZIP Creation"), vformat(TTR("Could not open file to read from path \"%s\"."), dir.path_join(f))); - return; - } - const int bufsize = 16384; - uint8_t buf[bufsize]; - - while (true) { - uint64_t got = fa->get_buffer(buf, bufsize); - if (got == 0) { - break; - } - zipWriteInFileInZip(p_zip, buf, got); - } - - zipCloseFileInZip(p_zip); - } - f = da->get_next(); - } - da->list_dir_end(); -} - bool EditorExportPlatformMacOS::has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const { String err; bool valid = false; @@ -1937,6 +1846,10 @@ bool EditorExportPlatformMacOS::has_valid_project_configuration(const Ref<Editor } } } + if (notary_tool == 2 && p_preset->get("notarization/apple_team_id") == "") { + err += TTR("Notarization: Apple Team ID not specified.") + "\n"; + valid = false; + } } else if (notary_tool == 1) { if (p_preset->get("notarization/api_uuid") == "") { err += TTR("Notarization: App Store Connect issuer ID name not specified.") + "\n"; @@ -2008,9 +1921,242 @@ bool EditorExportPlatformMacOS::has_valid_project_configuration(const Ref<Editor return valid; } -EditorExportPlatformMacOS::EditorExportPlatformMacOS() { - logo = ImageTexture::create_from_image(memnew(Image(_macos_logo))); +Ref<Texture2D> EditorExportPlatformMacOS::get_run_icon() const { + return run_icon; +} + +bool EditorExportPlatformMacOS::poll_export() { + Ref<EditorExportPreset> preset; + + for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i); + if (ep->is_runnable() && ep->get_platform() == this) { + preset = ep; + break; + } + } + + int prev = menu_options; + menu_options = (preset.is_valid() && preset->get("ssh_remote_deploy/enabled").operator bool()); + if (ssh_pid != 0 || !cleanup_commands.is_empty()) { + if (menu_options == 0) { + cleanup(); + } else { + menu_options += 1; + } + } + return menu_options != prev; +} + +Ref<ImageTexture> EditorExportPlatformMacOS::get_option_icon(int p_index) const { + return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index); +} + +int EditorExportPlatformMacOS::get_options_count() const { + return menu_options; +} + +String EditorExportPlatformMacOS::get_option_label(int p_index) const { + return (p_index) ? TTR("Stop and uninstall") : TTR("Run on remote macOS system"); +} + +String EditorExportPlatformMacOS::get_option_tooltip(int p_index) const { + return (p_index) ? TTR("Stop and uninstall running project from the remote system") : TTR("Run exported project on remote macOS system"); +} + +void EditorExportPlatformMacOS::cleanup() { + if (ssh_pid != 0 && OS::get_singleton()->is_process_running(ssh_pid)) { + print_line("Terminating connection..."); + OS::get_singleton()->kill(ssh_pid); + OS::get_singleton()->delay_usec(1000); + } + + if (!cleanup_commands.is_empty()) { + print_line("Stopping and deleting previous version..."); + for (const SSHCleanupCommand &cmd : cleanup_commands) { + if (cmd.wait) { + ssh_run_on_remote(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } else { + ssh_run_on_remote_no_wait(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } + } + } + ssh_pid = 0; + cleanup_commands.clear(); +} + +Error EditorExportPlatformMacOS::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) { + cleanup(); + if (p_device) { // Stop command, cleanup only. + return OK; + } + + EditorProgress ep("run", TTR("Running..."), 5); + + const String dest = EditorPaths::get_singleton()->get_cache_dir().path_join("macos"); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (!da->dir_exists(dest)) { + Error err = da->make_dir_recursive(dest); + if (err != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not create temp directory:") + "\n" + dest); + return err; + } + } + + String pkg_name; + if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "") { + pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name")); + } else { + pkg_name = "Unnamed"; + } + pkg_name = OS::get_singleton()->get_safe_dir_name(pkg_name); + + String host = p_preset->get("ssh_remote_deploy/host").operator String(); + String port = p_preset->get("ssh_remote_deploy/port").operator String(); + if (port.is_empty()) { + port = "22"; + } + Vector<String> extra_args_ssh = p_preset->get("ssh_remote_deploy/extra_args_ssh").operator String().split(" "); + Vector<String> extra_args_scp = p_preset->get("ssh_remote_deploy/extra_args_scp").operator String().split(" "); + + const String basepath = dest.path_join("tmp_macos_export"); + +#define CLEANUP_AND_RETURN(m_err) \ + { \ + if (da->file_exists(basepath + ".zip")) { \ + da->remove(basepath + ".zip"); \ + } \ + if (da->file_exists(basepath + "_start.sh")) { \ + da->remove(basepath + "_start.sh"); \ + } \ + if (da->file_exists(basepath + "_clean.sh")) { \ + da->remove(basepath + "_clean.sh"); \ + } \ + return m_err; \ + } \ + ((void)0) + + if (ep.step(TTR("Exporting project..."), 1)) { + return ERR_SKIP; + } + Error err = export_project(p_preset, true, basepath + ".zip", p_debug_flags); + if (err != OK) { + DirAccess::remove_file_or_error(basepath + ".zip"); + return err; + } + + String cmd_args; + { + Vector<String> cmd_args_list; + gen_debug_flags(cmd_args_list, p_debug_flags); + for (int i = 0; i < cmd_args_list.size(); i++) { + if (i != 0) { + cmd_args += " "; + } + cmd_args += cmd_args_list[i]; + } + } + + const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT); + int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port"); + + print_line("Creating temporary directory..."); + ep.step(TTR("Creating temporary directory..."), 2); + String temp_dir; + err = ssh_run_on_remote(host, port, extra_args_ssh, "mktemp -d", &temp_dir); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + + print_line("Uploading archive..."); + ep.step(TTR("Uploading archive..."), 3); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + ".zip", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + { + String run_script = p_preset->get("ssh_remote_deploy/run_script"); + run_script = run_script.replace("{temp_dir}", temp_dir); + run_script = run_script.replace("{archive_name}", basepath.get_file() + ".zip"); + run_script = run_script.replace("{exe_name}", pkg_name); + run_script = run_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_start.sh", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(run_script); + } + + { + String clean_script = p_preset->get("ssh_remote_deploy/cleanup_script"); + clean_script = clean_script.replace("{temp_dir}", temp_dir); + clean_script = clean_script.replace("{archive_name}", basepath.get_file() + ".zip"); + clean_script = clean_script.replace("{exe_name}", pkg_name); + clean_script = clean_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_clean.sh", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(clean_script); + } + + print_line("Uploading scripts..."); + ep.step(TTR("Uploading scripts..."), 4); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_start.sh", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + err = ssh_run_on_remote(host, port, extra_args_ssh, vformat("chmod +x \"%s/%s\"", temp_dir, basepath.get_file() + "_start.sh")); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_clean.sh", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + err = ssh_run_on_remote(host, port, extra_args_ssh, vformat("chmod +x \"%s/%s\"", temp_dir, basepath.get_file() + "_clean.sh")); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + + print_line("Starting project..."); + ep.step(TTR("Starting project..."), 5); + err = ssh_run_on_remote_no_wait(host, port, extra_args_ssh, vformat("\"%s/%s\"", temp_dir, basepath.get_file() + "_start.sh"), &ssh_pid, (use_remote) ? dbg_port : -1); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + cleanup_commands.clear(); + cleanup_commands.push_back(SSHCleanupCommand(host, port, extra_args_ssh, vformat("\"%s/%s\"", temp_dir, basepath.get_file() + "_clean.sh"))); + + print_line("Project started."); + + CLEANUP_AND_RETURN(OK); +#undef CLEANUP_AND_RETURN } -EditorExportPlatformMacOS::~EditorExportPlatformMacOS() { +EditorExportPlatformMacOS::EditorExportPlatformMacOS() { +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _macos_logo_svg, EDSCALE, upsample, false); + logo = ImageTexture::create_from_image(img); + + img_loader.create_image_from_string(img, _macos_run_icon_svg, EDSCALE, upsample, false); + run_icon = ImageTexture::create_from_image(img); +#endif + + Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme(); + if (theme.is_valid()) { + stop_icon = theme->get_icon(SNAME("Stop"), SNAME("EditorIcons")); + } else { + stop_icon.instantiate(); + } } diff --git a/platform/macos/export/export_plugin.h b/platform/macos/export/export_plugin.h index 7de6ddf304..c10192949c 100644 --- a/platform/macos/export/export_plugin.h +++ b/platform/macos/export/export_plugin.h @@ -36,12 +36,10 @@ #include "core/io/file_access.h" #include "core/io/marshalls.h" #include "core/io/resource_saver.h" -#include "core/io/zip_io.h" #include "core/os/os.h" #include "core/version.h" #include "editor/editor_settings.h" #include "editor/export/editor_export.h" -#include "platform/macos/logo.gen.h" #include <sys/stat.h> @@ -52,6 +50,30 @@ class EditorExportPlatformMacOS : public EditorExportPlatform { Ref<ImageTexture> logo; + struct SSHCleanupCommand { + String host; + String port; + Vector<String> ssh_args; + String cmd_args; + bool wait = false; + + SSHCleanupCommand(){}; + SSHCleanupCommand(const String &p_host, const String &p_port, const Vector<String> &p_ssh_arg, const String &p_cmd_args, bool p_wait = false) { + host = p_host; + port = p_port; + ssh_args = p_ssh_arg; + cmd_args = p_cmd_args; + wait = p_wait; + }; + }; + + Ref<ImageTexture> run_icon; + Ref<ImageTexture> stop_icon; + + Vector<SSHCleanupCommand> cleanup_commands; + OS::ProcessID ssh_pid = 0; + int menu_options = 0; + void _fix_plist(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &plist, const String &p_binary); void _make_icon(const Ref<EditorExportPreset> &p_preset, const Ref<Image> &p_icon, Vector<uint8_t> &p_data); @@ -65,14 +87,17 @@ class EditorExportPlatformMacOS : public EditorExportPlatform { Ref<DirAccess> &dir_access, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, const String &p_ent_path); Error _create_dmg(const String &p_dmg_path, const String &p_pkg_name, const String &p_app_path_name); - void _zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name); Error _export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path); bool use_codesign() const { return true; } #ifdef MACOS_ENABLED - bool use_dmg() const { return true; } + bool use_dmg() const { + return true; + } #else - bool use_dmg() const { return false; } + bool use_dmg() const { + return false; + } #endif bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const { @@ -97,7 +122,7 @@ class EditorExportPlatformMacOS : public EditorExportPlatform { return true; } - bool is_shbang(const String &p_path) const; + bool is_shebang(const String &p_path) const; protected: virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const override; @@ -105,9 +130,15 @@ protected: virtual bool get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option, const HashMap<StringName, Variant> &p_options) const override; public: - virtual String get_name() const override { return "macOS"; } - virtual String get_os_name() const override { return "macOS"; } - virtual Ref<Texture2D> get_logo() const override { return logo; } + virtual String get_name() const override { + return "macOS"; + } + virtual String get_os_name() const override { + return "macOS"; + } + virtual Ref<Texture2D> get_logo() const override { + return logo; + } virtual bool is_executable(const String &p_path) const override; virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override { @@ -133,8 +164,16 @@ public: virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, HashSet<String> &p_features) override { } + virtual Ref<Texture2D> get_run_icon() const override; + virtual bool poll_export() override; + virtual Ref<ImageTexture> get_option_icon(int p_index) const override; + virtual int get_options_count() const override; + virtual String get_option_label(int p_index) const override; + virtual String get_option_tooltip(int p_index) const override; + virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) override; + virtual void cleanup() override; + EditorExportPlatformMacOS(); - ~EditorExportPlatformMacOS(); }; #endif // MACOS_EXPORT_PLUGIN_H diff --git a/platform/macos/logo.png b/platform/macos/logo.png Binary files differdeleted file mode 100644 index b5a660b165..0000000000 --- a/platform/macos/logo.png +++ /dev/null diff --git a/platform/macos/logo.svg b/platform/macos/logo.svg new file mode 100644 index 0000000000..759583d76b --- /dev/null +++ b/platform/macos/logo.svg @@ -0,0 +1 @@ +<svg height="32" viewBox="0 0 25.6 25.6" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M.948 19.474V6.126c0-2.767 2.42-5.178 5.178-5.178h6.904s-2.992 7.506-2.992 13.233c0 .346.337.69.69.69h2.877c0 6.648.906 8.436 1.266 9.781H6.126c-2.75 0-5.178-2.407-5.178-5.178z" fill="#1c9ef8"/><path d="M7.162 8.312v1.496" fill="none" stroke="#323232" stroke-linecap="round" stroke-width="1.036"/><path d="M10.729 14.871c-.352 0-.69-.344-.69-.69C10.038 8.414 13.03.948 13.03.948h6.444c2.77 0 5.178 2.416 5.178 5.178v13.348c0 2.754-2.407 5.178-5.178 5.178h-4.603c-.357-1.333-1.266-2.887-1.266-9.78z" fill="#e1e6ed"/><g fill="none" stroke="#323232" stroke-linecap="round"><path d="M17.575 8.255V9.75" stroke-width="1.036"/><path d="M5.55 16.943c1.037 1.794 3.907 2.876 6.79 2.876 2.877 0 5.745-1.068 6.789-2.876" stroke-width=".69"/></g></svg> diff --git a/platform/macos/run_icon.svg b/platform/macos/run_icon.svg new file mode 100644 index 0000000000..c7067bb4b6 --- /dev/null +++ b/platform/macos/run_icon.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path style="color:#000;fill:#e0e0e0;fill-opacity:1;stroke-width:.93168;-inkscape-stroke:none" d="M4.418 1.055c-1.82 0-3.365 1.537-3.365 3.363v7.164c0 1.829 1.548 3.363 3.365 3.363h7.164c1.828 0 3.363-1.544 3.363-3.363V4.418c0-1.822-1.537-3.363-3.363-3.363H7.729Zm3.875 1.164h3.291c1.149 0 2.2 1.053 2.2 2.199v7.164c0 1.14-1.052 2.2-2.2 2.2h-2.15a8.884 8.884 0 0 1-.358-1.598c-.135.02-.487.082-.693.117a3.947 3.947 0 0 1-.049.004l-.008-.002a7.345 7.345 0 0 1-1.205-.004 7.114 7.114 0 0 1-.926-.139 6.057 6.057 0 0 1-.867-.271 3.843 3.843 0 0 1-.988-.566 3.214 3.214 0 0 1-.397-.378 2.8 2.8 0 0 1-.318-.441.558.558 0 0 1-.059-.424.564.564 0 0 1 .881-.299.56.56 0 0 1 .145.164c.083.138.188.26.312.362.096.082.2.158.307.224.12.075.243.142.371.201.285.139.583.247.89.319a5.35 5.35 0 0 0 1.282.158c.065 0 .129-.005.184-.006.056 0 .102-.005.148-.008l.096-.006c.114-.009.228-.02.31-.032.083-.013.11-.021.143-.028.099-.022.204-.058.327-.089a28.438 28.438 0 0 1-.06-1.929V8.53H6.887c.048-1.963.746-4.357 1.181-5.677.1-.293.184-.527.225-.633ZM4.973 5.03h.002a.562.562 0 0 1 .558.559v.805a.556.556 0 0 1-.558.558.56.56 0 0 1-.397-.162.565.565 0 0 1-.164-.396V5.59a.561.561 0 0 1 .559-.559Z"/><path style="color:#000;fill:#e0e0e0;fill-opacity:1;stroke-linecap:round;-inkscape-stroke:none" d="M26.117 11.467c.008.11.014.225.022.328.022.283.052.565.088.846l.012.053c1.238-.252 2.448-.829 3.011-1.803a.6.6 0 1 0-1.039-.6c-.28.486-1.161.936-2.094 1.176z" transform="translate(-15.37 .357) scale(.93168)"/><g style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-opacity:1"><path style="color:#000;fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:1.2;stroke-linecap:round;stroke-opacity:1;-inkscape-stroke:none" d="M27.836 5.585v.862" transform="translate(-15.37 .357) scale(.93168)"/><path style="color:#000;fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-linecap:round;stroke-opacity:1;-inkscape-stroke:none" d="M27.836 4.984a.6.6 0 0 0-.6.6v.863a.6.6 0 0 0 .6.6.6.6 0 0 0 .6-.6v-.863a.6.6 0 0 0-.6-.6Z" transform="translate(-15.37 .357) scale(.93168)"/></g></svg> diff --git a/platform/uwp/export/export_plugin.cpp b/platform/uwp/export/export_plugin.cpp index 6eb74fd90a..f810cb0ca9 100644 --- a/platform/uwp/export/export_plugin.cpp +++ b/platform/uwp/export/export_plugin.cpp @@ -30,8 +30,14 @@ #include "export_plugin.h" +#include "editor/editor_scale.h" #include "editor/editor_settings.h" -#include "platform/uwp/logo.gen.h" +#include "platform/uwp/logo_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg and regex. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif String EditorExportPlatformUWP::get_name() const { return "UWP"; @@ -504,5 +510,13 @@ void EditorExportPlatformUWP::resolve_platform_feature_priorities(const Ref<Edit } EditorExportPlatformUWP::EditorExportPlatformUWP() { - logo = ImageTexture::create_from_image(memnew(Image(_uwp_logo))); +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _uwp_logo_svg, EDSCALE, upsample, false); + + logo = ImageTexture::create_from_image(img); +#endif } diff --git a/platform/uwp/logo.png b/platform/uwp/logo.png Binary files differdeleted file mode 100644 index 9017a30636..0000000000 --- a/platform/uwp/logo.png +++ /dev/null diff --git a/platform/uwp/logo.svg b/platform/uwp/logo.svg new file mode 100644 index 0000000000..5bcbdcfcd4 --- /dev/null +++ b/platform/uwp/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><g transform="translate(8.981 1.816)"><circle style="fill:#2f75bb;fill-opacity:1;stroke:none;stroke-width:.815427" cx="7.019" cy="14.184" r="13.825"/><path d="m-1.192 8.234 6.73-.927v6.503h-6.73Zm0 11.899 6.73.927v-6.422h-6.73Zm7.47 1.026 8.952 1.236v-7.757H6.278Zm0-13.951v6.602h8.952V5.973Z" fill="#00abed" style="fill:#fff;fill-opacity:1"/></g></svg> diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 40c19056b3..38df68c764 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -680,7 +680,7 @@ bool OS_UWP::set_environment(const String &p_var, const String &p_value) const { return false; } -String OS_UWP::get_stdin_string(bool p_block) { +String OS_UWP::get_stdin_string() { return String(); } diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 02a81f1a47..153656add7 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -162,7 +162,7 @@ public: HANDLE mouse_mode_changed; virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); - String get_stdin_string(bool p_block); + String get_stdin_string(); void set_mouse_mode(MouseMode p_mode); MouseMode get_mouse_mode() const; diff --git a/platform/web/export/export_plugin.cpp b/platform/web/export/export_plugin.cpp index 3e11db6887..d8e04904c7 100644 --- a/platform/web/export/export_plugin.cpp +++ b/platform/web/export/export_plugin.cpp @@ -31,7 +31,15 @@ #include "export_plugin.h" #include "core/config/project_settings.h" +#include "editor/editor_scale.h" #include "editor/editor_settings.h" +#include "platform/web/logo_svg.gen.h" +#include "platform/web/run_icon_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif Error EditorExportPlatformWeb::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) { Ref<FileAccess> io_fa; @@ -153,7 +161,7 @@ void EditorExportPlatformWeb::_fix_html(Vector<uint8_t> &p_html, const Ref<Edito const String custom_head_include = p_preset->get("html/head_include"); HashMap<String, String> replaces; replaces["$GODOT_URL"] = p_name + ".js"; - replaces["$GODOT_PROJECT_NAME"] = ProjectSettings::get_singleton()->get_setting("application/config/name"); + replaces["$GODOT_PROJECT_NAME"] = GLOBAL_GET("application/config/name"); replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include; replaces["$GODOT_CONFIG"] = str_config; _replace_strings(replaces, p_html); @@ -193,7 +201,7 @@ Error EditorExportPlatformWeb::_add_manifest_icon(const String &p_path, const St } Error EditorExportPlatformWeb::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) { - String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name"); + String proj_name = GLOBAL_GET("application/config/name"); if (proj_name.is_empty()) { proj_name = "Godot Game"; } @@ -651,8 +659,17 @@ EditorExportPlatformWeb::EditorExportPlatformWeb() { server.instantiate(); server_thread.start(_server_thread_poll, this); - logo = ImageTexture::create_from_image(memnew(Image(_web_logo))); - run_icon = ImageTexture::create_from_image(memnew(Image(_web_run_icon))); +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _web_logo_svg, EDSCALE, upsample, false); + logo = ImageTexture::create_from_image(img); + + img_loader.create_image_from_string(img, _web_run_icon_svg, EDSCALE, upsample, false); + run_icon = ImageTexture::create_from_image(img); +#endif Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme(); if (theme.is_valid()) { diff --git a/platform/web/export/export_plugin.h b/platform/web/export/export_plugin.h index b85492b66f..e74c945837 100644 --- a/platform/web/export/export_plugin.h +++ b/platform/web/export/export_plugin.h @@ -38,11 +38,8 @@ #include "core/io/zip_io.h" #include "editor/editor_node.h" #include "editor/export/editor_export_platform.h" -#include "main/splash.gen.h" -#include "platform/web/logo.gen.h" -#include "platform/web/run_icon.gen.h" - #include "editor_http_server.h" +#include "main/splash.gen.h" class EditorExportPlatformWeb : public EditorExportPlatform { GDCLASS(EditorExportPlatformWeb, EditorExportPlatform); diff --git a/platform/web/logo.png b/platform/web/logo.png Binary files differdeleted file mode 100644 index c046d87dc4..0000000000 --- a/platform/web/logo.png +++ /dev/null diff --git a/platform/web/logo.svg b/platform/web/logo.svg new file mode 100644 index 0000000000..567b6f3c77 --- /dev/null +++ b/platform/web/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M7 5h18v21H7z" fill="#fff"/><path d="M3.143 1 5.48 27.504 15.967 31l10.553-3.496L28.857 1zM23.78 9.565H11.473l.275 3.308h11.759l-.911 9.937-6.556 1.808v.02h-.073l-6.61-1.828-.402-5.076h3.195l.234 2.552 3.583.97 3.595-.97.402-4.165H8.788L7.93 6.37h16.145z" fill="#eb6428"/></svg> diff --git a/platform/web/run_icon.png b/platform/web/run_icon.png Binary files differdeleted file mode 100644 index 574abb0150..0000000000 --- a/platform/web/run_icon.png +++ /dev/null diff --git a/platform/web/run_icon.svg b/platform/web/run_icon.svg new file mode 100644 index 0000000000..494f53cb90 --- /dev/null +++ b/platform/web/run_icon.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="M3.143 1 5.48 27.504 15.967 31l10.553-3.496L28.857 1ZM23.78 9.565H11.473l.275 3.308h11.759l-.911 9.937-6.556 1.808v.02h-.073l-6.61-1.828-.402-5.076h3.195l.234 2.552 3.583.97 3.595-.97.402-4.165H8.788L7.93 6.37h16.145Z" fill="#eb6428" style="fill:#e0e0e0;fill-opacity:1" transform="translate(.586 .586) scale(.46337)"/></svg> diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 99b80c2e2a..2d787c84e2 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -2543,6 +2543,25 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA return 0; } } break; + case WM_ERASEBKGND: { + Color early_color; + if (!_get_window_early_clear_override(early_color)) { + break; + } + bool must_recreate_brush = !window_bkg_brush || window_bkg_brush_color != early_color.to_argb32(); + if (must_recreate_brush) { + if (window_bkg_brush) { + DeleteObject(window_bkg_brush); + } + window_bkg_brush = CreateSolidBrush(RGB(early_color.get_r8(), early_color.get_g8(), early_color.get_b8())); + } + HDC hdc = (HDC)wParam; + RECT rect = {}; + if (GetUpdateRect(hWnd, &rect, true)) { + FillRect(hdc, &rect, window_bkg_brush); + } + return 1; + } break; case WM_PAINT: { Main::force_redraw(); } break; @@ -3982,7 +4001,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win memset(&wc, 0, sizeof(WNDCLASSEXW)); wc.cbSize = sizeof(WNDCLASSEXW); - wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS; + wc.style = CS_OWNDC | CS_DBLCLKS; wc.lpfnWndProc = (WNDPROC)::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index e9f30024b2..84f2dee35e 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -452,6 +452,8 @@ class DisplayServerWindows : public DisplayServer { bool in_dispatch_input_event = false; WNDCLASSEXW wc; + HBRUSH window_bkg_brush = nullptr; + uint32_t window_bkg_brush_color = 0; HCURSOR cursors[CURSOR_MAX] = { nullptr }; CursorShape cursor_shape = CursorShape::CURSOR_ARROW; diff --git a/platform/windows/export/export.cpp b/platform/windows/export/export.cpp index b0e2f5a05b..4112bb84b5 100644 --- a/platform/windows/export/export.cpp +++ b/platform/windows/export/export.cpp @@ -51,7 +51,6 @@ void register_windows_exporter() { Ref<EditorExportPlatformWindows> platform; platform.instantiate(); - platform->set_logo(ImageTexture::create_from_image(memnew(Image(_windows_logo)))); platform->set_name("Windows Desktop"); platform->set_os_name("Windows"); diff --git a/platform/windows/export/export_plugin.cpp b/platform/windows/export/export_plugin.cpp index 7c61a79fc8..bf32b16018 100644 --- a/platform/windows/export/export_plugin.cpp +++ b/platform/windows/export/export_plugin.cpp @@ -34,6 +34,14 @@ #include "core/io/image_loader.h" #include "editor/editor_node.h" #include "editor/editor_paths.h" +#include "editor/editor_scale.h" +#include "platform/windows/logo_svg.gen.h" +#include "platform/windows/run_icon_svg.gen.h" + +#include "modules/modules_enabled.gen.h" // For svg. +#ifdef MODULE_SVG_ENABLED +#include "modules/svg/image_loader_svg.h" +#endif Error EditorExportPlatformWindows::_process_icon(const Ref<EditorExportPreset> &p_preset, const String &p_src_path, const String &p_dst_path) { static const uint8_t icon_size[] = { 16, 32, 48, 64, 128, 0 /*256*/ }; @@ -168,9 +176,39 @@ Error EditorExportPlatformWindows::modify_template(const Ref<EditorExportPreset> } Error EditorExportPlatformWindows::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) { - String pck_path = p_path; - if (p_preset->get("binary_format/embed_pck")) { - pck_path = p_path.get_basename() + ".tmp"; + bool export_as_zip = p_path.ends_with("zip"); + bool embedded = p_preset->get("binary_format/embed_pck"); + + String pkg_name; + if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "") { + pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name")); + } else { + pkg_name = "Unnamed"; + } + + pkg_name = OS::get_singleton()->get_safe_dir_name(pkg_name); + + // Setup temp folder. + String path = p_path; + String tmp_dir_path = EditorPaths::get_singleton()->get_cache_dir().path_join(pkg_name); + Ref<DirAccess> tmp_app_dir = DirAccess::create_for_path(tmp_dir_path); + if (export_as_zip) { + if (tmp_app_dir.is_null()) { + return ERR_CANT_CREATE; + } + if (DirAccess::exists(tmp_dir_path)) { + if (tmp_app_dir->change_dir(tmp_dir_path) == OK) { + tmp_app_dir->erase_contents_recursive(); + } + } + tmp_app_dir->make_dir_recursive(tmp_dir_path); + path = tmp_dir_path.path_join(p_path.get_file().get_basename() + ".exe"); + } + + // Export project. + String pck_path = path; + if (embedded) { + pck_path = pck_path.get_basename() + ".tmp"; } Error err = EditorExportPlatformPC::export_project(p_preset, p_debug, pck_path, p_flags); if (p_preset->get("codesign/enable") && err == OK) { @@ -181,7 +219,7 @@ Error EditorExportPlatformWindows::export_project(const Ref<EditorExportPreset> } } - if (p_preset->get("binary_format/embed_pck") && err == OK) { + if (embedded && err == OK) { Ref<DirAccess> tmp_dir = DirAccess::create_for_path(p_path.get_base_dir()); err = tmp_dir->rename(pck_path, p_path); if (err != OK) { @@ -189,6 +227,27 @@ Error EditorExportPlatformWindows::export_project(const Ref<EditorExportPreset> } } + // ZIP project. + if (export_as_zip) { + if (FileAccess::exists(p_path)) { + OS::get_singleton()->move_to_trash(p_path); + } + + Ref<FileAccess> io_fa_dst; + zlib_filefunc_def io_dst = zipio_create_io(&io_fa_dst); + zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io_dst); + + zip_folder_recursive(zip, tmp_dir_path, "", pkg_name); + + zipClose(zip, nullptr); + + if (tmp_app_dir->change_dir(tmp_dir_path) == OK) { + tmp_app_dir->erase_contents_recursive(); + tmp_app_dir->change_dir(".."); + tmp_app_dir->remove(pkg_name); + } + } + return err; } @@ -199,6 +258,7 @@ String EditorExportPlatformWindows::get_template_file_name(const String &p_targe List<String> EditorExportPlatformWindows::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const { List<String> list; list.push_back("exe"); + list.push_back("zip"); return list; } @@ -212,6 +272,7 @@ bool EditorExportPlatformWindows::get_export_option_visibility(const EditorExpor void EditorExportPlatformWindows::get_export_options(List<ExportOption> *r_options) { EditorExportPlatformPC::get_export_options(r_options); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "binary_format/architecture", PROPERTY_HINT_ENUM, "x86_64,x86_32,arm64"), "x86_64")); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "codesign/enable"), false)); @@ -235,6 +296,29 @@ void EditorExportPlatformWindows::get_export_options(List<ExportOption> *r_optio r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_description"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/trademarks"), "")); + + String run_script = "Expand-Archive -LiteralPath '{temp_dir}\\{archive_name}' -DestinationPath '{temp_dir}'\n" + "$action = New-ScheduledTaskAction -Execute '{temp_dir}\\{exe_name}' -Argument '{cmd_args}'\n" + "$trigger = New-ScheduledTaskTrigger -Once -At 00:00\n" + "$settings = New-ScheduledTaskSettingsSet\n" + "$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings\n" + "Register-ScheduledTask godot_remote_debug -InputObject $task -Force:$true\n" + "Start-ScheduledTask -TaskName godot_remote_debug\n" + "while (Get-ScheduledTask -TaskName godot_remote_debug | ? State -eq running) { Start-Sleep -Milliseconds 100 }\n" + "Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue"; + + String cleanup_script = "Stop-ScheduledTask -TaskName godot_remote_debug -ErrorAction:SilentlyContinue\n" + "Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue\n" + "Remove-Item -Recurse -Force '{temp_dir}'"; + + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "ssh_remote_deploy/enabled"), false)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/host"), "user@host_ip")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/port"), "22")); + + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_ssh", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/extra_args_scp", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/run_script", PROPERTY_HINT_MULTILINE_TEXT), run_script)); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "ssh_remote_deploy/cleanup_script", PROPERTY_HINT_MULTILINE_TEXT), cleanup_script)); } Error EditorExportPlatformWindows::_rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path, bool p_console_icon) { @@ -659,3 +743,227 @@ Error EditorExportPlatformWindows::fixup_embedded_pck(const String &p_path, int6 } return OK; } + +Ref<Texture2D> EditorExportPlatformWindows::get_run_icon() const { + return run_icon; +} + +bool EditorExportPlatformWindows::poll_export() { + Ref<EditorExportPreset> preset; + + for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i); + if (ep->is_runnable() && ep->get_platform() == this) { + preset = ep; + break; + } + } + + int prev = menu_options; + menu_options = (preset.is_valid() && preset->get("ssh_remote_deploy/enabled").operator bool()); + if (ssh_pid != 0 || !cleanup_commands.is_empty()) { + if (menu_options == 0) { + cleanup(); + } else { + menu_options += 1; + } + } + return menu_options != prev; +} + +Ref<ImageTexture> EditorExportPlatformWindows::get_option_icon(int p_index) const { + return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index); +} + +int EditorExportPlatformWindows::get_options_count() const { + return menu_options; +} + +String EditorExportPlatformWindows::get_option_label(int p_index) const { + return (p_index) ? TTR("Stop and uninstall") : TTR("Run on remote Windows system"); +} + +String EditorExportPlatformWindows::get_option_tooltip(int p_index) const { + return (p_index) ? TTR("Stop and uninstall running project from the remote system") : TTR("Run exported project on remote Windows system"); +} + +void EditorExportPlatformWindows::cleanup() { + if (ssh_pid != 0 && OS::get_singleton()->is_process_running(ssh_pid)) { + print_line("Terminating connection..."); + OS::get_singleton()->kill(ssh_pid); + OS::get_singleton()->delay_usec(1000); + } + + if (!cleanup_commands.is_empty()) { + print_line("Stopping and deleting previous version..."); + for (const SSHCleanupCommand &cmd : cleanup_commands) { + if (cmd.wait) { + ssh_run_on_remote(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } else { + ssh_run_on_remote_no_wait(cmd.host, cmd.port, cmd.ssh_args, cmd.cmd_args); + } + } + } + ssh_pid = 0; + cleanup_commands.clear(); +} + +Error EditorExportPlatformWindows::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) { + cleanup(); + if (p_device) { // Stop command, cleanup only. + return OK; + } + + EditorProgress ep("run", TTR("Running..."), 5); + + const String dest = EditorPaths::get_singleton()->get_cache_dir().path_join("windows"); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (!da->dir_exists(dest)) { + Error err = da->make_dir_recursive(dest); + if (err != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not create temp directory:") + "\n" + dest); + return err; + } + } + + String host = p_preset->get("ssh_remote_deploy/host").operator String(); + String port = p_preset->get("ssh_remote_deploy/port").operator String(); + if (port.is_empty()) { + port = "22"; + } + Vector<String> extra_args_ssh = p_preset->get("ssh_remote_deploy/extra_args_ssh").operator String().split(" "); + Vector<String> extra_args_scp = p_preset->get("ssh_remote_deploy/extra_args_scp").operator String().split(" "); + + const String basepath = dest.path_join("tmp_windows_export"); + +#define CLEANUP_AND_RETURN(m_err) \ + { \ + if (da->file_exists(basepath + ".zip")) { \ + da->remove(basepath + ".zip"); \ + } \ + if (da->file_exists(basepath + "_start.ps1")) { \ + da->remove(basepath + "_start.ps1"); \ + } \ + if (da->file_exists(basepath + "_clean.ps1")) { \ + da->remove(basepath + "_clean.ps1"); \ + } \ + return m_err; \ + } \ + ((void)0) + + if (ep.step(TTR("Exporting project..."), 1)) { + return ERR_SKIP; + } + Error err = export_project(p_preset, true, basepath + ".zip", p_debug_flags); + if (err != OK) { + DirAccess::remove_file_or_error(basepath + ".zip"); + return err; + } + + String cmd_args; + { + Vector<String> cmd_args_list; + gen_debug_flags(cmd_args_list, p_debug_flags); + for (int i = 0; i < cmd_args_list.size(); i++) { + if (i != 0) { + cmd_args += " "; + } + cmd_args += cmd_args_list[i]; + } + } + + const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT); + int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port"); + + print_line("Creating temporary directory..."); + ep.step(TTR("Creating temporary directory..."), 2); + String temp_dir; + err = ssh_run_on_remote(host, port, extra_args_ssh, "powershell -command \\\"\\$tmp = Join-Path \\$Env:Temp \\$(New-Guid); New-Item -Type Directory -Path \\$tmp | Out-Null; Write-Output \\$tmp\\\"", &temp_dir); + if (err != OK || temp_dir.is_empty()) { + CLEANUP_AND_RETURN(err); + } + + print_line("Uploading archive..."); + ep.step(TTR("Uploading archive..."), 3); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + ".zip", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + { + String run_script = p_preset->get("ssh_remote_deploy/run_script"); + run_script = run_script.replace("{temp_dir}", temp_dir); + run_script = run_script.replace("{archive_name}", basepath.get_file() + ".zip"); + run_script = run_script.replace("{exe_name}", basepath.get_file() + ".exe"); + run_script = run_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_start.ps1", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(run_script); + } + + { + String clean_script = p_preset->get("ssh_remote_deploy/cleanup_script"); + clean_script = clean_script.replace("{temp_dir}", temp_dir); + clean_script = clean_script.replace("{archive_name}", basepath.get_file() + ".zip"); + clean_script = clean_script.replace("{exe_name}", basepath.get_file() + ".exe"); + clean_script = clean_script.replace("{cmd_args}", cmd_args); + + Ref<FileAccess> f = FileAccess::open(basepath + "_clean.ps1", FileAccess::WRITE); + if (f.is_null()) { + CLEANUP_AND_RETURN(err); + } + + f->store_string(clean_script); + } + + print_line("Uploading scripts..."); + ep.step(TTR("Uploading scripts..."), 4); + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_start.ps1", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + err = ssh_push_to_remote(host, port, extra_args_scp, basepath + "_clean.ps1", temp_dir); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + print_line("Starting project..."); + ep.step(TTR("Starting project..."), 5); + err = ssh_run_on_remote_no_wait(host, port, extra_args_ssh, vformat("powershell -file \"%s\\%s\"", temp_dir, basepath.get_file() + "_start.ps1"), &ssh_pid, (use_remote) ? dbg_port : -1); + if (err != OK) { + CLEANUP_AND_RETURN(err); + } + + cleanup_commands.clear(); + cleanup_commands.push_back(SSHCleanupCommand(host, port, extra_args_ssh, vformat("powershell -file \"%s\\%s\"", temp_dir, basepath.get_file() + "_clean.ps1"))); + + print_line("Project started."); + + CLEANUP_AND_RETURN(OK); +#undef CLEANUP_AND_RETURN +} + +EditorExportPlatformWindows::EditorExportPlatformWindows() { +#ifdef MODULE_SVG_ENABLED + Ref<Image> img = memnew(Image); + const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE); + + ImageLoaderSVG img_loader; + img_loader.create_image_from_string(img, _windows_logo_svg, EDSCALE, upsample, false); + set_logo(ImageTexture::create_from_image(img)); + + img_loader.create_image_from_string(img, _windows_run_icon_svg, EDSCALE, upsample, false); + run_icon = ImageTexture::create_from_image(img); +#endif + + Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme(); + if (theme.is_valid()) { + stop_icon = theme->get_icon(SNAME("Stop"), SNAME("EditorIcons")); + } else { + stop_icon.instantiate(); + } +} diff --git a/platform/windows/export/export_plugin.h b/platform/windows/export/export_plugin.h index 96608728d3..fa75a17a1f 100644 --- a/platform/windows/export/export_plugin.h +++ b/platform/windows/export/export_plugin.h @@ -35,9 +35,32 @@ #include "core/os/os.h" #include "editor/editor_settings.h" #include "editor/export/editor_export_platform_pc.h" -#include "platform/windows/logo.gen.h" class EditorExportPlatformWindows : public EditorExportPlatformPC { + struct SSHCleanupCommand { + String host; + String port; + Vector<String> ssh_args; + String cmd_args; + bool wait = false; + + SSHCleanupCommand(){}; + SSHCleanupCommand(const String &p_host, const String &p_port, const Vector<String> &p_ssh_arg, const String &p_cmd_args, bool p_wait = false) { + host = p_host; + port = p_port; + ssh_args = p_ssh_arg; + cmd_args = p_cmd_args; + wait = p_wait; + }; + }; + + Ref<ImageTexture> run_icon; + Ref<ImageTexture> stop_icon; + + Vector<SSHCleanupCommand> cleanup_commands; + OS::ProcessID ssh_pid = 0; + int menu_options = 0; + Error _process_icon(const Ref<EditorExportPreset> &p_preset, const String &p_src_path, const String &p_dst_path); Error _rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path, bool p_console_icon); Error _code_sign(const Ref<EditorExportPreset> &p_preset, const String &p_path); @@ -53,6 +76,17 @@ public: virtual bool get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option, const HashMap<StringName, Variant> &p_options) const override; virtual String get_template_file_name(const String &p_target, const String &p_arch) const override; virtual Error fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) override; + + virtual Ref<Texture2D> get_run_icon() const override; + virtual bool poll_export() override; + virtual Ref<ImageTexture> get_option_icon(int p_index) const override; + virtual int get_options_count() const override; + virtual String get_option_label(int p_index) const override; + virtual String get_option_tooltip(int p_index) const override; + virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) override; + virtual void cleanup() override; + + EditorExportPlatformWindows(); }; #endif // WINDOWS_EXPORT_PLUGIN_H diff --git a/platform/windows/logo.png b/platform/windows/logo.png Binary files differdeleted file mode 100644 index f06b463850..0000000000 --- a/platform/windows/logo.png +++ /dev/null diff --git a/platform/windows/logo.svg b/platform/windows/logo.svg new file mode 100644 index 0000000000..77a0b20766 --- /dev/null +++ b/platform/windows/logo.svg @@ -0,0 +1 @@ +<svg height="32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="m1 5.132 12.295-1.694v11.879H1zm0 21.736 12.295 1.695V16.83H1zm13.647 1.875L31 31V16.83H14.647zm0-25.486v12.06H31V1z" fill="#00abed"/></svg> diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index 2a44a19085..b3831573cf 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -718,15 +718,23 @@ Error OS_Windows::create_process(const String &p_path, const List<String> &p_arg } Error OS_Windows::kill(const ProcessID &p_pid) { - ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED); + int ret = 0; + if (process_map->has(p_pid)) { + const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi; + process_map->erase(p_pid); - const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi; - process_map->erase(p_pid); + ret = TerminateProcess(pi.hProcess, 0); - const int ret = TerminateProcess(pi.hProcess, 0); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + } else { + HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, false, (DWORD)p_pid); + if (hProcess != NULL) { + ret = TerminateProcess(hProcess, 0); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); + CloseHandle(hProcess); + } + } return ret != 0 ? OK : FAILED; } @@ -1162,13 +1170,11 @@ bool OS_Windows::set_environment(const String &p_var, const String &p_value) con return (bool)SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), (LPCWSTR)(p_value.utf16().get_data())); } -String OS_Windows::get_stdin_string(bool p_block) { - if (p_block) { - WCHAR buff[1024]; - DWORD count = 0; - if (ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), buff, 1024, &count, nullptr)) { - return String::utf16((const char16_t *)buff, count); - } +String OS_Windows::get_stdin_string() { + WCHAR buff[1024]; + DWORD count = 0; + if (ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), buff, 1024, &count, nullptr)) { + return String::utf16((const char16_t *)buff, count); } return String(); diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 9cb3977030..c33e0f6740 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -140,7 +140,7 @@ protected: virtual void finalize() override; virtual void finalize_core() override; - virtual String get_stdin_string(bool p_block) override; + virtual String get_stdin_string() override; String _quote_command_line_argument(const String &p_text) const; diff --git a/platform/windows/run_icon.svg b/platform/windows/run_icon.svg new file mode 100644 index 0000000000..0897276ef7 --- /dev/null +++ b/platform/windows/run_icon.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="m1.095 2.997 5.66-.78v5.469h-5.66zm0 10.006 5.66.78v-5.4h-5.66zm6.282.863 7.528 1.04V8.381H7.377Zm0-11.732v5.552h7.528V1.095Z" fill="#00abed" style="stroke-width:.460341;fill:#e0e0e0;fill-opacity:1"/></svg> diff --git a/scene/2d/mesh_instance_2d.cpp b/scene/2d/mesh_instance_2d.cpp index f69b3728f7..4fc375ff8d 100644 --- a/scene/2d/mesh_instance_2d.cpp +++ b/scene/2d/mesh_instance_2d.cpp @@ -49,14 +49,10 @@ void MeshInstance2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &MeshInstance2D::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &MeshInstance2D::get_texture); - ClassDB::bind_method(D_METHOD("set_normal_map", "normal_map"), &MeshInstance2D::set_normal_map); - ClassDB::bind_method(D_METHOD("get_normal_map"), &MeshInstance2D::get_normal_map); - ADD_SIGNAL(MethodInfo("texture_changed")); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal_map", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_normal_map", "get_normal_map"); } void MeshInstance2D::set_mesh(const Ref<Mesh> &p_mesh) { @@ -77,15 +73,6 @@ void MeshInstance2D::set_texture(const Ref<Texture2D> &p_texture) { emit_signal(SceneStringNames::get_singleton()->texture_changed); } -void MeshInstance2D::set_normal_map(const Ref<Texture2D> &p_texture) { - normal_map = p_texture; - queue_redraw(); -} - -Ref<Texture2D> MeshInstance2D::get_normal_map() const { - return normal_map; -} - Ref<Texture2D> MeshInstance2D::get_texture() const { return texture; } diff --git a/scene/2d/mesh_instance_2d.h b/scene/2d/mesh_instance_2d.h index 795b3758e3..c914f13ade 100644 --- a/scene/2d/mesh_instance_2d.h +++ b/scene/2d/mesh_instance_2d.h @@ -39,7 +39,6 @@ class MeshInstance2D : public Node2D { Ref<Mesh> mesh; Ref<Texture2D> texture; - Ref<Texture2D> normal_map; protected: void _notification(int p_what); @@ -57,9 +56,6 @@ public: void set_texture(const Ref<Texture2D> &p_texture); Ref<Texture2D> get_texture() const; - void set_normal_map(const Ref<Texture2D> &p_texture); - Ref<Texture2D> get_normal_map() const; - MeshInstance2D(); }; diff --git a/scene/2d/multimesh_instance_2d.cpp b/scene/2d/multimesh_instance_2d.cpp index ac7c350751..f347eb6520 100644 --- a/scene/2d/multimesh_instance_2d.cpp +++ b/scene/2d/multimesh_instance_2d.cpp @@ -50,14 +50,10 @@ void MultiMeshInstance2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &MultiMeshInstance2D::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &MultiMeshInstance2D::get_texture); - ClassDB::bind_method(D_METHOD("set_normal_map", "normal_map"), &MultiMeshInstance2D::set_normal_map); - ClassDB::bind_method(D_METHOD("get_normal_map"), &MultiMeshInstance2D::get_normal_map); - ADD_SIGNAL(MethodInfo("texture_changed")); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multimesh", PROPERTY_HINT_RESOURCE_TYPE, "MultiMesh"), "set_multimesh", "get_multimesh"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal_map", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_normal_map", "get_normal_map"); } void MultiMeshInstance2D::set_multimesh(const Ref<MultiMesh> &p_multimesh) { @@ -91,15 +87,6 @@ Ref<Texture2D> MultiMeshInstance2D::get_texture() const { return texture; } -void MultiMeshInstance2D::set_normal_map(const Ref<Texture2D> &p_texture) { - normal_map = p_texture; - queue_redraw(); -} - -Ref<Texture2D> MultiMeshInstance2D::get_normal_map() const { - return normal_map; -} - #ifdef TOOLS_ENABLED Rect2 MultiMeshInstance2D::_edit_get_rect() const { if (multimesh.is_valid()) { diff --git a/scene/2d/multimesh_instance_2d.h b/scene/2d/multimesh_instance_2d.h index 64ecae6d6c..0647412294 100644 --- a/scene/2d/multimesh_instance_2d.h +++ b/scene/2d/multimesh_instance_2d.h @@ -40,7 +40,6 @@ class MultiMeshInstance2D : public Node2D { Ref<MultiMesh> multimesh; Ref<Texture2D> texture; - Ref<Texture2D> normal_map; protected: void _notification(int p_what); @@ -57,9 +56,6 @@ public: void set_texture(const Ref<Texture2D> &p_texture); Ref<Texture2D> get_texture() const; - void set_normal_map(const Ref<Texture2D> &p_texture); - Ref<Texture2D> get_normal_map() const; - MultiMeshInstance2D(); ~MultiMeshInstance2D(); }; diff --git a/scene/2d/navigation_agent_2d.cpp b/scene/2d/navigation_agent_2d.cpp index 4f6ba093cb..6b842e6e6b 100644 --- a/scene/2d/navigation_agent_2d.cpp +++ b/scene/2d/navigation_agent_2d.cpp @@ -94,9 +94,9 @@ void NavigationAgent2D::_bind_methods() { ADD_GROUP("Pathfinding", ""); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "target_location", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_target_location", "get_target_location"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:px"), "set_path_desired_distance", "get_path_desired_distance"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:px"), "set_target_desired_distance", "get_target_desired_distance"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "10,100,1,suffix:px"), "set_path_max_distance", "get_path_max_distance"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_desired_distance", PROPERTY_HINT_RANGE, "0.1,1000,0.01,suffix:px"), "set_path_desired_distance", "get_path_desired_distance"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_desired_distance", PROPERTY_HINT_RANGE, "0.1,1000,0.01,suffix:px"), "set_target_desired_distance", "get_target_desired_distance"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "10,1000,1,suffix:px"), "set_path_max_distance", "get_path_max_distance"); ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers"); ADD_PROPERTY(PropertyInfo(Variant::INT, "path_metadata_flags", PROPERTY_HINT_FLAGS, "Include Types,Include RIDs,Include Owners"), "set_path_metadata_flags", "get_path_metadata_flags"); @@ -105,8 +105,8 @@ void NavigationAgent2D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.1,500,0.01,suffix:px"), "set_radius", "get_radius"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_distance", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px"), "set_neighbor_distance", "get_neighbor_distance"); ADD_PROPERTY(PropertyInfo(Variant::INT, "max_neighbors", PROPERTY_HINT_RANGE, "1,10000,1"), "set_max_neighbors", "get_max_neighbors"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:s"), "set_time_horizon", "get_time_horizon"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px/s"), "set_max_speed", "get_max_speed"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.1,10,0.01,suffix:s"), "set_time_horizon", "get_time_horizon"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:px/s"), "set_max_speed", "get_max_speed"); ADD_SIGNAL(MethodInfo("path_changed")); ADD_SIGNAL(MethodInfo("target_reached")); @@ -182,11 +182,11 @@ void NavigationAgent2D::_notification(int p_what) { NavigationAgent2D::NavigationAgent2D() { agent = NavigationServer2D::get_singleton()->agent_create(); - set_neighbor_distance(500.0); - set_max_neighbors(10); - set_time_horizon(20.0); - set_radius(10.0); - set_max_speed(200.0); + set_neighbor_distance(neighbor_distance); + set_max_neighbors(max_neighbors); + set_time_horizon(time_horizon); + set_radius(radius); + set_max_speed(max_speed); // Preallocate query and result objects to improve performance. navigation_query = Ref<NavigationPathQueryParameters2D>(); diff --git a/scene/2d/navigation_agent_2d.h b/scene/2d/navigation_agent_2d.h index 113b1e9623..190a2fcbda 100644 --- a/scene/2d/navigation_agent_2d.h +++ b/scene/2d/navigation_agent_2d.h @@ -50,15 +50,15 @@ class NavigationAgent2D : public Node { uint32_t navigation_layers = 1; BitField<NavigationPathQueryParameters2D::PathMetadataFlags> path_metadata_flags = NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_ALL; - real_t path_desired_distance = 1.0; - real_t target_desired_distance = 1.0; - real_t radius = 0.0; - real_t neighbor_distance = 0.0; - int max_neighbors = 0; - real_t time_horizon = 0.0; - real_t max_speed = 0.0; - - real_t path_max_distance = 3.0; + real_t path_desired_distance = 20.0; + real_t target_desired_distance = 10.0; + real_t radius = 10.0; + real_t neighbor_distance = 500.0; + int max_neighbors = 10; + real_t time_horizon = 1.0; + real_t max_speed = 100.0; + + real_t path_max_distance = 100.0; Vector2 target_location; bool target_position_submitted = false; diff --git a/scene/3d/bone_attachment_3d.cpp b/scene/3d/bone_attachment_3d.cpp index a44e66ce2a..fe7f6837f0 100644 --- a/scene/3d/bone_attachment_3d.cpp +++ b/scene/3d/bone_attachment_3d.cpp @@ -61,11 +61,7 @@ void BoneAttachment3D::_validate_property(PropertyInfo &p_property) const { } bool BoneAttachment3D::_set(const StringName &p_path, const Variant &p_value) { - if (p_path == SNAME("override_pose")) { - set_override_pose(p_value); - } else if (p_path == SNAME("override_mode")) { - set_override_mode(p_value); - } else if (p_path == SNAME("use_external_skeleton")) { + if (p_path == SNAME("use_external_skeleton")) { set_use_external_skeleton(p_value); } else if (p_path == SNAME("external_skeleton")) { set_external_skeleton(p_value); @@ -75,11 +71,7 @@ bool BoneAttachment3D::_set(const StringName &p_path, const Variant &p_value) { } bool BoneAttachment3D::_get(const StringName &p_path, Variant &r_ret) const { - if (p_path == SNAME("override_pose")) { - r_ret = get_override_pose(); - } else if (p_path == SNAME("override_mode")) { - r_ret = get_override_mode(); - } else if (p_path == SNAME("use_external_skeleton")) { + if (p_path == SNAME("use_external_skeleton")) { r_ret = get_use_external_skeleton(); } else if (p_path == SNAME("external_skeleton")) { r_ret = get_external_skeleton(); @@ -208,14 +200,10 @@ void BoneAttachment3D::_transform_changed() { Transform3D our_trans = get_transform(); if (use_external_skeleton) { - our_trans = sk->world_transform_to_global_pose(get_global_transform()); + our_trans = sk->get_global_transform().affine_inverse() * get_global_transform(); } - if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) { - sk->set_bone_global_pose_override(bone_idx, our_trans, 1.0, true); - } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) { - sk->set_bone_local_pose_override(bone_idx, sk->global_pose_to_local_pose(bone_idx, our_trans), 1.0, true); - } + sk->set_bone_global_pose_override(bone_idx, our_trans, 1.0, true); } } @@ -267,11 +255,7 @@ void BoneAttachment3D::set_override_pose(bool p_override) { if (!override_pose) { Skeleton3D *sk = _get_skeleton3d(); if (sk) { - if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) { - sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false); - } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) { - sk->set_bone_local_pose_override(bone_idx, Transform3D(), 0.0, false); - } + sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false); } _transform_changed(); } @@ -282,27 +266,6 @@ bool BoneAttachment3D::get_override_pose() const { return override_pose; } -void BoneAttachment3D::set_override_mode(int p_mode) { - if (override_pose) { - Skeleton3D *sk = _get_skeleton3d(); - if (sk) { - if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) { - sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false); - } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) { - sk->set_bone_local_pose_override(bone_idx, Transform3D(), 0.0, false); - } - } - override_mode = p_mode; - _transform_changed(); - return; - } - override_mode = p_mode; -} - -int BoneAttachment3D::get_override_mode() const { - return override_mode; -} - void BoneAttachment3D::set_use_external_skeleton(bool p_use_external) { use_external_skeleton = p_use_external; @@ -361,7 +324,7 @@ void BoneAttachment3D::on_bone_pose_update(int p_bone_index) { if (sk) { if (!override_pose) { if (use_external_skeleton) { - set_global_transform(sk->global_pose_to_world_transform(sk->get_bone_global_pose(bone_idx))); + set_global_transform(sk->get_global_transform() * sk->get_bone_global_pose(bone_idx)); } else { set_transform(sk->get_bone_global_pose(bone_idx)); } @@ -407,8 +370,6 @@ void BoneAttachment3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_override_pose", "override_pose"), &BoneAttachment3D::set_override_pose); ClassDB::bind_method(D_METHOD("get_override_pose"), &BoneAttachment3D::get_override_pose); - ClassDB::bind_method(D_METHOD("set_override_mode", "override_mode"), &BoneAttachment3D::set_override_mode); - ClassDB::bind_method(D_METHOD("get_override_mode"), &BoneAttachment3D::get_override_mode); ClassDB::bind_method(D_METHOD("set_use_external_skeleton", "use_external_skeleton"), &BoneAttachment3D::set_use_external_skeleton); ClassDB::bind_method(D_METHOD("get_use_external_skeleton"), &BoneAttachment3D::get_use_external_skeleton); @@ -420,4 +381,5 @@ void BoneAttachment3D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bone_name"), "set_bone_name", "get_bone_name"); ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_idx"), "set_bone_idx", "get_bone_idx"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "override_pose"), "set_override_pose", "get_override_pose"); } diff --git a/scene/3d/bone_attachment_3d.h b/scene/3d/bone_attachment_3d.h index 2065271bbe..327cbaa0ab 100644 --- a/scene/3d/bone_attachment_3d.h +++ b/scene/3d/bone_attachment_3d.h @@ -44,14 +44,8 @@ class BoneAttachment3D : public Node3D { int bone_idx = -1; bool override_pose = false; - int override_mode = 0; bool _override_dirty = false; - enum OVERRIDE_MODES { - MODE_GLOBAL_POSE, - MODE_LOCAL_POSE, - }; - bool use_external_skeleton = false; NodePath external_skeleton_node; ObjectID external_skeleton_node_cache; @@ -86,8 +80,6 @@ public: void set_override_pose(bool p_override); bool get_override_pose() const; - void set_override_mode(int p_mode); - int get_override_mode() const; void set_use_external_skeleton(bool p_external_skeleton); bool get_use_external_skeleton() const; diff --git a/scene/3d/shape_cast_3d.cpp b/scene/3d/shape_cast_3d.cpp index 358da2b6d0..87361d6b38 100644 --- a/scene/3d/shape_cast_3d.cpp +++ b/scene/3d/shape_cast_3d.cpp @@ -30,8 +30,9 @@ #include "shape_cast_3d.h" -#include "collision_object_3d.h" -#include "mesh_instance_3d.h" +#include "core/core_string_names.h" +#include "scene/3d/collision_object_3d.h" +#include "scene/3d/mesh_instance_3d.h" #include "scene/resources/concave_polygon_shape_3d.h" void ShapeCast3D::_notification(int p_what) { @@ -318,25 +319,35 @@ void ShapeCast3D::resource_changed(Ref<Resource> p_res) { update_gizmos(); } +void ShapeCast3D::_shape_changed() { + update_gizmos(); + bool is_editor = Engine::get_singleton()->is_editor_hint(); + if (is_inside_tree() && (is_editor || get_tree()->is_debugging_collisions_hint())) { + _update_debug_shape(); + } +} + void ShapeCast3D::set_shape(const Ref<Shape3D> &p_shape) { if (p_shape == shape) { return; } if (!shape.is_null()) { + shape->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &ShapeCast3D::_shape_changed)); shape->unregister_owner(this); } shape = p_shape; if (!shape.is_null()) { shape->register_owner(this); + shape->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &ShapeCast3D::_shape_changed)); } if (p_shape.is_valid()) { shape_rid = shape->get_rid(); } - if (is_inside_tree() && get_tree()->is_debugging_collisions_hint()) { + bool is_editor = Engine::get_singleton()->is_editor_hint(); + if (is_inside_tree() && (is_editor || get_tree()->is_debugging_collisions_hint())) { _update_debug_shape(); } - update_gizmos(); update_configuration_warnings(); } diff --git a/scene/3d/shape_cast_3d.h b/scene/3d/shape_cast_3d.h index 483364472f..344f1d3b8a 100644 --- a/scene/3d/shape_cast_3d.h +++ b/scene/3d/shape_cast_3d.h @@ -77,6 +77,7 @@ class ShapeCast3D : public Node3D { protected: void _notification(int p_what); void _update_shapecast_state(); + void _shape_changed(); static void _bind_methods(); public: diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp index 4eadaa603f..1b46879079 100644 --- a/scene/3d/skeleton_3d.cpp +++ b/scene/3d/skeleton_3d.cpp @@ -33,7 +33,6 @@ #include "core/object/message_queue.h" #include "core/variant/type_info.h" #include "scene/3d/physics_body_3d.h" -#include "scene/resources/skeleton_modification_3d.h" #include "scene/resources/surface_tool.h" #include "scene/scene_string_names.h" @@ -70,13 +69,6 @@ SkinReference::~SkinReference() { bool Skeleton3D::_set(const StringName &p_path, const Variant &p_value) { String path = p_path; -#ifndef _3D_DISABLED - if (path.begins_with("modification_stack")) { - set_modification_stack(p_value); - return true; - } -#endif //_3D_DISABLED - if (!path.begins_with("bones/")) { return false; } @@ -113,13 +105,6 @@ bool Skeleton3D::_set(const StringName &p_path, const Variant &p_value) { bool Skeleton3D::_get(const StringName &p_path, Variant &r_ret) const { String path = p_path; -#ifndef _3D_DISABLED - if (path.begins_with("modification_stack")) { - r_ret = modification_stack; - return true; - } -#endif //_3D_DISABLED - if (!path.begins_with("bones/")) { return false; } @@ -162,14 +147,6 @@ void Skeleton3D::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::VECTOR3, prep + PNAME("scale"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR)); } -#ifndef _3D_DISABLED - p_list->push_back( - PropertyInfo(Variant::OBJECT, "modification_stack", - PROPERTY_HINT_RESOURCE_TYPE, - "SkeletonModificationStack3D", - PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); -#endif //_3D_DISABLED - for (PropertyInfo &E : *p_list) { _validate_property(E); } @@ -330,24 +307,10 @@ void Skeleton3D::_notification(int p_what) { } } } - - if (modification_stack.is_valid()) { - execute_modifications(get_physics_process_delta_time(), SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_physics_process); - } - } break; - - case NOTIFICATION_INTERNAL_PROCESS: { - if (modification_stack.is_valid()) { - execute_modifications(get_process_delta_time(), SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_process); - } } break; - case NOTIFICATION_READY: { - set_physics_process_internal(true); - set_process_internal(true); - - if (modification_stack.is_valid()) { - set_modification_stack(modification_stack); + if (Engine::get_singleton()->is_editor_hint()) { + set_physics_process_internal(true); } } break; #endif // _3D_DISABLED @@ -395,99 +358,6 @@ Transform3D Skeleton3D::get_bone_global_pose_no_override(int p_bone) const { return bones[p_bone].pose_global_no_override; } -void Skeleton3D::clear_bones_local_pose_override() { - for (int i = 0; i < bones.size(); i += 1) { - bones.write[i].local_pose_override_amount = 0; - } - _make_dirty(); -} - -void Skeleton3D::set_bone_local_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX(p_bone, bone_size); - bones.write[p_bone].local_pose_override_amount = p_amount; - bones.write[p_bone].local_pose_override = p_pose; - bones.write[p_bone].local_pose_override_reset = !p_persistent; - _make_dirty(); -} - -Transform3D Skeleton3D::get_bone_local_pose_override(int p_bone) const { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D()); - return bones[p_bone].local_pose_override; -} - -void Skeleton3D::update_bone_rest_forward_vector(int p_bone, bool p_force_update) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX(p_bone, bone_size); - - if (bones[p_bone].rest_bone_forward_vector.length_squared() > 0 && p_force_update == false) { - update_bone_rest_forward_axis(p_bone, p_force_update); - } - - // If it is a child/leaf bone... - if (get_bone_parent(p_bone) > 0) { - bones.write[p_bone].rest_bone_forward_vector = bones[p_bone].rest.origin.normalized(); - } else { - // If it has children... - Vector<int> child_bones = get_bone_children(p_bone); - if (child_bones.size() > 0) { - Vector3 combined_child_dir = Vector3(0, 0, 0); - for (int i = 0; i < child_bones.size(); i++) { - combined_child_dir += bones[child_bones[i]].rest.origin.normalized(); - } - combined_child_dir = combined_child_dir / child_bones.size(); - bones.write[p_bone].rest_bone_forward_vector = combined_child_dir.normalized(); - } else { - WARN_PRINT_ONCE("Cannot calculate forward direction for bone " + itos(p_bone)); - WARN_PRINT_ONCE("Assuming direction of (0, 1, 0) for bone"); - bones.write[p_bone].rest_bone_forward_vector = Vector3(0, 1, 0); - } - } - update_bone_rest_forward_axis(p_bone, p_force_update); -} - -void Skeleton3D::update_bone_rest_forward_axis(int p_bone, bool p_force_update) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX(p_bone, bone_size); - if (bones[p_bone].rest_bone_forward_axis > -1 && p_force_update == false) { - return; - } - - Vector3 forward_axis_absolute = bones[p_bone].rest_bone_forward_vector.abs(); - if (forward_axis_absolute.x > forward_axis_absolute.y && forward_axis_absolute.x > forward_axis_absolute.z) { - if (bones[p_bone].rest_bone_forward_vector.x > 0) { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_X_FORWARD; - } else { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_X_FORWARD; - } - } else if (forward_axis_absolute.y > forward_axis_absolute.x && forward_axis_absolute.y > forward_axis_absolute.z) { - if (bones[p_bone].rest_bone_forward_vector.y > 0) { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_Y_FORWARD; - } else { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_Y_FORWARD; - } - } else { - if (bones[p_bone].rest_bone_forward_vector.z > 0) { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_Z_FORWARD; - } else { - bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_Z_FORWARD; - } - } -} - -Vector3 Skeleton3D::get_bone_axis_forward_vector(int p_bone) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone, bone_size, Vector3(0, 0, 0)); - return bones[p_bone].rest_bone_forward_vector; -} - -int Skeleton3D::get_bone_axis_forward_enum(int p_bone) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone, bone_size, -1); - return bones[p_bone].rest_bone_forward_axis; -} - void Skeleton3D::set_motion_scale(float p_motion_scale) { if (p_motion_scale <= 0) { motion_scale = 1; @@ -503,6 +373,10 @@ float Skeleton3D::get_motion_scale() const { // Skeleton creation api +uint64_t Skeleton3D::get_version() const { + return version; +} + void Skeleton3D::add_bone(const String &p_name) { ERR_FAIL_COND(p_name.is_empty() || p_name.contains(":") || p_name.contains("/")); @@ -546,6 +420,7 @@ void Skeleton3D::set_bone_name(int p_bone, const String &p_name) { } bones.write[p_bone].name = p_name; + version++; } bool Skeleton3D::is_bone_parent_of(int p_bone, int p_parent_bone_id) const { @@ -1068,23 +943,10 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) { b.global_rest = b.parent >= 0 ? bonesptr[b.parent].global_rest * b.rest : b.rest; } - if (b.local_pose_override_amount >= CMP_EPSILON) { - Transform3D override_local_pose; - if (b.parent >= 0) { - override_local_pose = bonesptr[b.parent].pose_global * b.local_pose_override; - } else { - override_local_pose = b.local_pose_override; - } - b.pose_global = b.pose_global.interpolate_with(override_local_pose, b.local_pose_override_amount); - } - if (b.global_pose_override_amount >= CMP_EPSILON) { b.pose_global = b.pose_global.interpolate_with(b.global_pose_override, b.global_pose_override_amount); } - if (b.local_pose_override_reset) { - b.local_pose_override_amount = 0.0; - } if (b.global_pose_override_reset) { b.global_pose_override_amount = 0.0; } @@ -1100,100 +962,6 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) { rest_dirty = false; } -// Helper functions - -Transform3D Skeleton3D::global_pose_to_world_transform(Transform3D p_global_pose) { - return get_global_transform() * p_global_pose; -} - -Transform3D Skeleton3D::world_transform_to_global_pose(Transform3D p_world_transform) { - return get_global_transform().affine_inverse() * p_world_transform; -} - -Transform3D Skeleton3D::global_pose_to_local_pose(int p_bone_idx, Transform3D p_global_pose) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Transform3D()); - if (bones[p_bone_idx].parent >= 0) { - int parent_bone_idx = bones[p_bone_idx].parent; - Transform3D conversion_transform = get_bone_global_pose(parent_bone_idx).affine_inverse(); - return conversion_transform * p_global_pose; - } else { - return p_global_pose; - } -} - -Transform3D Skeleton3D::local_pose_to_global_pose(int p_bone_idx, Transform3D p_local_pose) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Transform3D()); - if (bones[p_bone_idx].parent >= 0) { - int parent_bone_idx = bones[p_bone_idx].parent; - return bones[parent_bone_idx].pose_global * p_local_pose; - } else { - return p_local_pose; - } -} - -Basis Skeleton3D::global_pose_z_forward_to_bone_forward(int p_bone_idx, Basis p_basis) { - const int bone_size = bones.size(); - ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Basis()); - Basis return_basis = p_basis; - - if (bones[p_bone_idx].rest_bone_forward_axis < 0) { - update_bone_rest_forward_vector(p_bone_idx, true); - } - - if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_X_FORWARD) { - return_basis.rotate_local(Vector3(0, 1, 0), (Math_PI / 2.0)); - } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_X_FORWARD) { - return_basis.rotate_local(Vector3(0, 1, 0), -(Math_PI / 2.0)); - } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_Y_FORWARD) { - return_basis.rotate_local(Vector3(1, 0, 0), -(Math_PI / 2.0)); - } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_Y_FORWARD) { - return_basis.rotate_local(Vector3(1, 0, 0), (Math_PI / 2.0)); - } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_Z_FORWARD) { - // Do nothing! - } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_Z_FORWARD) { - return_basis.rotate_local(Vector3(0, 0, 1), Math_PI); - } - - return return_basis; -} - -// Modifications - -#ifndef _3D_DISABLED - -void Skeleton3D::set_modification_stack(Ref<SkeletonModificationStack3D> p_stack) { - if (modification_stack.is_valid()) { - modification_stack->is_setup = false; - modification_stack->set_skeleton(nullptr); - } - - modification_stack = p_stack; - if (modification_stack.is_valid()) { - modification_stack->set_skeleton(this); - modification_stack->setup(); - } -} -Ref<SkeletonModificationStack3D> Skeleton3D::get_modification_stack() { - return modification_stack; -} - -void Skeleton3D::execute_modifications(real_t p_delta, int p_execution_mode) { - if (!modification_stack.is_valid()) { - return; - } - - // Needed to avoid the issue where the stack looses reference to the skeleton when the scene is saved. - if (modification_stack->skeleton != this) { - modification_stack->set_skeleton(this); - } - - modification_stack->execute(p_delta, p_execution_mode); -} - -#endif // _3D_DISABLED - void Skeleton3D::_bind_methods() { ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton3D::add_bone); ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton3D::find_bone); @@ -1204,6 +972,7 @@ void Skeleton3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bone_parent", "bone_idx", "parent_idx"), &Skeleton3D::set_bone_parent); ClassDB::bind_method(D_METHOD("get_bone_count"), &Skeleton3D::get_bone_count); + ClassDB::bind_method(D_METHOD("get_version"), &Skeleton3D::get_version); ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton3D::unparent_bone_and_rest); @@ -1243,23 +1012,12 @@ void Skeleton3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_bone_global_pose", "bone_idx"), &Skeleton3D::get_bone_global_pose); ClassDB::bind_method(D_METHOD("get_bone_global_pose_no_override", "bone_idx"), &Skeleton3D::get_bone_global_pose_no_override); - ClassDB::bind_method(D_METHOD("clear_bones_local_pose_override"), &Skeleton3D::clear_bones_local_pose_override); - ClassDB::bind_method(D_METHOD("set_bone_local_pose_override", "bone_idx", "pose", "amount", "persistent"), &Skeleton3D::set_bone_local_pose_override, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_bone_local_pose_override", "bone_idx"), &Skeleton3D::get_bone_local_pose_override); - ClassDB::bind_method(D_METHOD("force_update_all_bone_transforms"), &Skeleton3D::force_update_all_bone_transforms); ClassDB::bind_method(D_METHOD("force_update_bone_child_transform", "bone_idx"), &Skeleton3D::force_update_bone_children_transforms); ClassDB::bind_method(D_METHOD("set_motion_scale", "motion_scale"), &Skeleton3D::set_motion_scale); ClassDB::bind_method(D_METHOD("get_motion_scale"), &Skeleton3D::get_motion_scale); - // Helper functions - ClassDB::bind_method(D_METHOD("global_pose_to_world_transform", "global_pose"), &Skeleton3D::global_pose_to_world_transform); - ClassDB::bind_method(D_METHOD("world_transform_to_global_pose", "world_transform"), &Skeleton3D::world_transform_to_global_pose); - ClassDB::bind_method(D_METHOD("global_pose_to_local_pose", "bone_idx", "global_pose"), &Skeleton3D::global_pose_to_local_pose); - ClassDB::bind_method(D_METHOD("local_pose_to_global_pose", "bone_idx", "local_pose"), &Skeleton3D::local_pose_to_global_pose); - ClassDB::bind_method(D_METHOD("global_pose_z_forward_to_bone_forward", "bone_idx", "basis"), &Skeleton3D::global_pose_z_forward_to_bone_forward); - ClassDB::bind_method(D_METHOD("set_show_rest_only", "enabled"), &Skeleton3D::set_show_rest_only); ClassDB::bind_method(D_METHOD("is_show_rest_only"), &Skeleton3D::is_show_rest_only); @@ -1271,11 +1029,6 @@ void Skeleton3D::_bind_methods() { ClassDB::bind_method(D_METHOD("physical_bones_add_collision_exception", "exception"), &Skeleton3D::physical_bones_add_collision_exception); ClassDB::bind_method(D_METHOD("physical_bones_remove_collision_exception", "exception"), &Skeleton3D::physical_bones_remove_collision_exception); - // Modifications - ClassDB::bind_method(D_METHOD("set_modification_stack", "modification_stack"), &Skeleton3D::set_modification_stack); - ClassDB::bind_method(D_METHOD("get_modification_stack"), &Skeleton3D::get_modification_stack); - ClassDB::bind_method(D_METHOD("execute_modifications", "delta", "execution_mode"), &Skeleton3D::execute_modifications); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "motion_scale", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater"), "set_motion_scale", "get_motion_scale"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_rest_only"), "set_show_rest_only", "is_show_rest_only"); #ifndef _3D_DISABLED diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h index f66cc2f9ed..3df909d936 100644 --- a/scene/3d/skeleton_3d.h +++ b/scene/3d/skeleton_3d.h @@ -32,7 +32,6 @@ #define SKELETON_3D_H #include "scene/3d/node_3d.h" -#include "scene/resources/skeleton_modification_3d.h" #include "scene/resources/skin.h" typedef int BoneId; @@ -64,8 +63,6 @@ public: ~SkinReference(); }; -class SkeletonModificationStack3D; - class Skeleton3D : public Node3D { GDCLASS(Skeleton3D, Node3D); @@ -104,17 +101,8 @@ private: PhysicalBone3D *physical_bone = nullptr; PhysicalBone3D *cache_parent_physical_bone = nullptr; - real_t local_pose_override_amount; - bool local_pose_override_reset; - Transform3D local_pose_override; - Vector<int> child_bones; - // The forward direction vector and rest bone forward axis are cached because they do not change - // 99% of the time, but recalculating them can be expensive on models with many bones. - Vector3 rest_bone_forward_vector; - int rest_bone_forward_axis = -1; - Bone() { parent = -1; enabled = true; @@ -124,12 +112,7 @@ private: physical_bone = nullptr; cache_parent_physical_bone = nullptr; #endif // _3D_DISABLED - local_pose_override_amount = 0; - local_pose_override_reset = false; child_bones = Vector<int>(); - - rest_bone_forward_vector = Vector3(0, 0, 0); - rest_bone_forward_axis = -1; } }; @@ -162,25 +145,13 @@ protected: void _notification(int p_what); static void _bind_methods(); -#ifndef _3D_DISABLED - Ref<SkeletonModificationStack3D> modification_stack; -#endif // _3D_DISABLED - public: - enum Bone_Forward_Axis { - BONE_AXIS_X_FORWARD = 0, - BONE_AXIS_Y_FORWARD = 1, - BONE_AXIS_Z_FORWARD = 2, - BONE_AXIS_NEGATIVE_X_FORWARD = 3, - BONE_AXIS_NEGATIVE_Y_FORWARD = 4, - BONE_AXIS_NEGATIVE_Z_FORWARD = 5, - }; - enum { NOTIFICATION_UPDATE_SKELETON = 50 }; // skeleton creation api + uint64_t get_version() const; void add_bone(const String &p_name); int find_bone(const String &p_name) const; String get_bone_name(int p_bone) const; @@ -233,10 +204,6 @@ public: Transform3D get_bone_global_pose_override(int p_bone) const; void set_bone_global_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent = false); - void clear_bones_local_pose_override(); - Transform3D get_bone_local_pose_override(int p_bone) const; - void set_bone_local_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent = false); - void localize_rests(); // used for loaders and tools Ref<Skin> create_skin_from_rest_transforms(); @@ -247,26 +214,6 @@ public: void force_update_all_bone_transforms(); void force_update_bone_children_transforms(int bone_idx); - void update_bone_rest_forward_vector(int p_bone, bool p_force_update = false); - void update_bone_rest_forward_axis(int p_bone, bool p_force_update = false); - Vector3 get_bone_axis_forward_vector(int p_bone); - int get_bone_axis_forward_enum(int p_bone); - - // Helper functions - Transform3D global_pose_to_world_transform(Transform3D p_global_pose); - Transform3D world_transform_to_global_pose(Transform3D p_transform); - Transform3D global_pose_to_local_pose(int p_bone_idx, Transform3D p_global_pose); - Transform3D local_pose_to_global_pose(int p_bone_idx, Transform3D p_local_pose); - - Basis global_pose_z_forward_to_bone_forward(int p_bone_idx, Basis p_basis); - - // Modifications -#ifndef _3D_DISABLED - Ref<SkeletonModificationStack3D> get_modification_stack(); - void set_modification_stack(Ref<SkeletonModificationStack3D> p_stack); - void execute_modifications(real_t p_delta, int p_execution_mode); -#endif // _3D_DISABLED - // Physical bone API void set_animate_physical_bones(bool p_enabled); diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp index f35cd3fbc5..75f54a925b 100644 --- a/scene/3d/skeleton_ik_3d.cpp +++ b/scene/3d/skeleton_ik_3d.cpp @@ -249,6 +249,26 @@ void FabrikInverseKinematic::make_goal(Task *p_task, const Transform3D &p_invers } } +static Vector3 get_bone_axis_forward_vector(Skeleton3D *skeleton, int p_bone) { + // If it is a child/leaf bone... + if (skeleton->get_bone_parent(p_bone) > 0) { + return skeleton->get_bone_rest(p_bone).origin.normalized(); + } + // If it has children... + Vector<int> child_bones = skeleton->get_bone_children(p_bone); + if (child_bones.size() == 0) { + WARN_PRINT_ONCE("Cannot calculate forward direction for bone " + itos(p_bone)); + WARN_PRINT_ONCE("Assuming direction of (0, 1, 0) for bone"); + return Vector3(0, 1, 0); + } + Vector3 combined_child_dir = Vector3(0, 0, 0); + for (int i = 0; i < child_bones.size(); i++) { + combined_child_dir += skeleton->get_bone_rest(child_bones[i]).origin.normalized(); + } + combined_child_dir = combined_child_dir / child_bones.size(); + return combined_child_dir.normalized(); +} + void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool override_tip_basis, bool p_use_magnet, const Vector3 &p_magnet_position) { if (blending_delta <= 0.01f) { // Before skipping, make sure we undo the global pose overrides @@ -287,8 +307,7 @@ void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool ove new_bone_pose.origin = ci->current_pos; if (!ci->children.is_empty()) { - p_task->skeleton->update_bone_rest_forward_vector(ci->bone); - Vector3 forward_vector = p_task->skeleton->get_bone_axis_forward_vector(ci->bone); + Vector3 forward_vector = get_bone_axis_forward_vector(p_task->skeleton, ci->bone); // Rotate the bone towards the next bone in the chain: new_bone_pose.basis.rotate_to_align(forward_vector, new_bone_pose.origin.direction_to(ci->children[0].current_pos)); diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index 7f42c8fac3..d0875c2ba6 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -745,7 +745,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double } break; case Animation::TYPE_METHOD: { - if (!nc->node) { + if (!nc->node || is_stopping) { continue; } if (!p_is_current) { @@ -808,7 +808,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double } break; case Animation::TYPE_AUDIO: { - if (!nc->node) { + if (!nc->node || is_stopping) { continue; } @@ -915,6 +915,10 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double } break; case Animation::TYPE_ANIMATION: { + if (is_stopping) { + continue; + } + AnimationPlayer *player = Object::cast_to<AnimationPlayer>(nc->node); if (!player) { continue; @@ -1658,7 +1662,7 @@ void AnimationPlayer::play(const StringName &p_name, double p_custom_blend, floa } if (get_current_animation() != p_name) { - _stop_playing_caches(); + _stop_playing_caches(false); } c.current.from = &animation_set[name]; @@ -1731,18 +1735,12 @@ String AnimationPlayer::get_assigned_animation() const { return playback.assigned; } -void AnimationPlayer::stop(bool p_reset) { - _stop_playing_caches(); - Playback &c = playback; - c.blend.clear(); - if (p_reset) { - c.current.from = nullptr; - c.current.speed_scale = 1; - c.current.pos = 0; - } - _set_process(false); - queued.clear(); - playing = false; +void AnimationPlayer::pause() { + _stop_internal(false); +} + +void AnimationPlayer::stop() { + _stop_internal(true); } void AnimationPlayer::set_speed_scale(float p_speed) { @@ -1814,7 +1812,7 @@ void AnimationPlayer::_animation_changed(const StringName &p_name) { } } -void AnimationPlayer::_stop_playing_caches() { +void AnimationPlayer::_stop_playing_caches(bool p_reset) { for (TrackNodeCache *E : playing_caches) { if (E->node && E->audio_playing) { E->node->call(SNAME("stop")); @@ -1824,7 +1822,12 @@ void AnimationPlayer::_stop_playing_caches() { if (!player) { continue; } - player->stop(); + + if (p_reset) { + player->stop(); + } else { + player->pause(); + } } } @@ -1836,7 +1839,7 @@ void AnimationPlayer::_node_removed(Node *p_node) { } void AnimationPlayer::clear_caches() { - _stop_playing_caches(); + _stop_playing_caches(true); node_cache_map.clear(); @@ -1957,6 +1960,22 @@ void AnimationPlayer::_set_process(bool p_process, bool p_force) { processing = p_process; } +void AnimationPlayer::_stop_internal(bool p_reset) { + _stop_playing_caches(p_reset); + Playback &c = playback; + c.blend.clear(); + if (p_reset) { + is_stopping = true; + seek(0, true); + is_stopping = false; + c.current.from = nullptr; + c.current.speed_scale = 1; + } + _set_process(false); + queued.clear(); + playing = false; +} + void AnimationPlayer::animation_set_next(const StringName &p_animation, const StringName &p_next) { ERR_FAIL_COND_MSG(!animation_set.has(p_animation), vformat("Animation not found: %s.", p_animation)); animation_set[p_animation].next = p_next; @@ -2119,7 +2138,8 @@ void AnimationPlayer::_bind_methods() { ClassDB::bind_method(D_METHOD("play", "name", "custom_blend", "custom_speed", "from_end"), &AnimationPlayer::play, DEFVAL(""), DEFVAL(-1), DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("play_backwards", "name", "custom_blend"), &AnimationPlayer::play_backwards, DEFVAL(""), DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("stop", "reset"), &AnimationPlayer::stop, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("pause"), &AnimationPlayer::pause); + ClassDB::bind_method(D_METHOD("stop"), &AnimationPlayer::stop); ClassDB::bind_method(D_METHOD("is_playing"), &AnimationPlayer::is_playing); ClassDB::bind_method(D_METHOD("set_current_animation", "anim"), &AnimationPlayer::set_current_animation); diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h index f431253876..8dfa7aed27 100644 --- a/scene/animation/animation_player.h +++ b/scene/animation/animation_player.h @@ -192,6 +192,7 @@ private: uint64_t accum_pass = 1; float speed_scale = 1.0; double default_blend_time = 0.0; + bool is_stopping = false; struct AnimationData { String name; @@ -277,7 +278,7 @@ private: void _animation_process(double p_delta); void _node_removed(Node *p_node); - void _stop_playing_caches(); + void _stop_playing_caches(bool p_reset); // bind helpers Vector<String> _get_animation_list() const { @@ -294,6 +295,7 @@ private: void _animation_changed(const StringName &p_name); void _set_process(bool p_process, bool p_force = false); + void _stop_internal(bool p_reset); bool playing = false; @@ -346,7 +348,8 @@ public: void queue(const StringName &p_name); Vector<String> get_queue(); void clear_queue(); - void stop(bool p_reset = true); + void pause(); + void stop(); bool is_playing() const; String get_current_animation() const; void set_current_animation(const String &p_anim); diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp index b88695427e..be8c23844f 100644 --- a/scene/animation/tween.cpp +++ b/scene/animation/tween.cpp @@ -60,7 +60,7 @@ void Tweener::_bind_methods() { ADD_SIGNAL(MethodInfo("finished")); } -void Tween::start_tweeners() { +void Tween::_start_tweeners() { if (tweeners.is_empty()) { dead = true; ERR_FAIL_MSG("Tween without commands, aborting."); @@ -71,6 +71,15 @@ void Tween::start_tweeners() { } } +void Tween::_stop_internal(bool p_reset) { + running = false; + if (p_reset) { + started = false; + dead = false; + total_time = 0; + } +} + Ref<PropertyTweener> Tween::tween_property(Object *p_target, NodePath p_property, Variant p_to, double p_duration) { ERR_FAIL_NULL_V(p_target, nullptr); ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree."); @@ -135,14 +144,11 @@ void Tween::append(Ref<Tweener> p_tweener) { } void Tween::stop() { - started = false; - running = false; - dead = false; - total_time = 0; + _stop_internal(true); } void Tween::pause() { - running = false; + _stop_internal(false); } void Tween::play() { @@ -278,7 +284,7 @@ bool Tween::step(double p_delta) { current_step = 0; loops_done = 0; total_time = 0; - start_tweeners(); + _start_tweeners(); started = true; } @@ -319,7 +325,7 @@ bool Tween::step(double p_delta) { } else { emit_signal(SNAME("loop_finished"), loops_done); current_step = 0; - start_tweeners(); + _start_tweeners(); #ifdef DEBUG_ENABLED if (loops <= 0 && Math::is_equal_approx(rem_delta, initial_delta)) { if (!potential_infinite) { @@ -332,7 +338,7 @@ bool Tween::step(double p_delta) { #endif } } else { - start_tweeners(); + _start_tweeners(); } } } diff --git a/scene/animation/tween.h b/scene/animation/tween.h index 8f65416e71..08911d6623 100644 --- a/scene/animation/tween.h +++ b/scene/animation/tween.h @@ -123,7 +123,8 @@ private: typedef real_t (*interpolater)(real_t t, real_t b, real_t c, real_t d); static interpolater interpolaters[TRANS_MAX][EASE_MAX]; - void start_tweeners(); + void _start_tweeners(); + void _stop_internal(bool p_reset); protected: static void _bind_methods(); diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp index 9cc25bf743..d0326290ac 100644 --- a/scene/gui/base_button.cpp +++ b/scene/gui/base_button.cpp @@ -30,6 +30,7 @@ #include "base_button.h" +#include "core/config/project_settings.h" #include "core/os/keyboard.h" #include "scene/main/window.h" #include "scene/scene_string_names.h" @@ -127,7 +128,6 @@ void BaseButton::_notification(int p_what) { status.hovering = false; status.press_attempt = false; status.pressing_inside = false; - status.shortcut_press = false; } break; } } @@ -154,14 +154,10 @@ void BaseButton::on_action_event(Ref<InputEvent> p_event) { if (status.press_attempt && status.pressing_inside) { if (toggle_mode) { bool is_pressed = p_event->is_pressed(); - if (Object::cast_to<InputEventShortcut>(*p_event)) { - is_pressed = false; - } if ((is_pressed && action_mode == ACTION_MODE_BUTTON_PRESS) || (!is_pressed && action_mode == ACTION_MODE_BUTTON_RELEASE)) { if (action_mode == ACTION_MODE_BUTTON_PRESS) { status.press_attempt = false; status.pressing_inside = false; - status.shortcut_press = false; } status.pressed = !status.pressed; _unpress_group(); @@ -187,7 +183,6 @@ void BaseButton::on_action_event(Ref<InputEvent> p_event) { } status.press_attempt = false; status.pressing_inside = false; - status.shortcut_press = false; emit_signal(SNAME("button_up")); } @@ -212,7 +207,6 @@ void BaseButton::set_disabled(bool p_disabled) { } status.press_attempt = false; status.pressing_inside = false; - status.shortcut_press = false; } queue_redraw(); } @@ -267,6 +261,10 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const { return DRAW_DISABLED; } + if (in_shortcut_feedback) { + return DRAW_HOVER_PRESSED; + } + if (!status.press_attempt && status.hovering) { if (status.pressed) { return DRAW_HOVER_PRESSED; @@ -285,7 +283,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const { pressing = status.pressed; } - if ((shortcut_feedback || !status.shortcut_press) && pressing) { + if (pressing) { return DRAW_PRESSED; } else { return DRAW_NORMAL; @@ -339,6 +337,14 @@ bool BaseButton::is_keep_pressed_outside() const { return keep_pressed_outside; } +void BaseButton::set_shortcut_feedback(bool p_enable) { + shortcut_feedback = p_enable; +} + +bool BaseButton::is_shortcut_feedback() const { + return shortcut_feedback; +} + void BaseButton::set_shortcut(const Ref<Shortcut> &p_shortcut) { shortcut = p_shortcut; set_process_shortcut_input(shortcut.is_valid()); @@ -348,13 +354,45 @@ Ref<Shortcut> BaseButton::get_shortcut() const { return shortcut; } +void BaseButton::_shortcut_feedback_timeout() { + in_shortcut_feedback = false; + queue_redraw(); +} + void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); - if (!is_disabled() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) { - status.shortcut_press = true; - on_action_event(p_event); + if (!is_disabled() && p_event->is_pressed() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) { + if (toggle_mode) { + status.pressed = !status.pressed; + + if (status.pressed) { + _unpress_group(); + if (button_group.is_valid()) { + button_group->emit_signal(SNAME("pressed"), this); + } + } + + _toggled(status.pressed); + _pressed(); + + } else { + _pressed(); + } + queue_redraw(); accept_event(); + + if (shortcut_feedback) { + if (shortcut_feedback_timer == nullptr) { + shortcut_feedback_timer = memnew(Timer); + add_child(shortcut_feedback_timer); + shortcut_feedback_timer->set_wait_time(GLOBAL_GET("gui/timers/button_shortcut_feedback_highlight_time")); + shortcut_feedback_timer->connect("timeout", callable_mp(this, &BaseButton::_shortcut_feedback_timeout)); + } + + in_shortcut_feedback = true; + shortcut_feedback_timer->start(); + } } } @@ -393,14 +431,6 @@ bool BaseButton::_was_pressed_by_mouse() const { return was_mouse_pressed; } -void BaseButton::set_shortcut_feedback(bool p_feedback) { - shortcut_feedback = p_feedback; -} - -bool BaseButton::is_shortcut_feedback() const { - return shortcut_feedback; -} - PackedStringArray BaseButton::get_configuration_warnings() const { PackedStringArray warnings = Control::get_configuration_warnings(); @@ -429,6 +459,8 @@ void BaseButton::_bind_methods() { ClassDB::bind_method(D_METHOD("get_draw_mode"), &BaseButton::get_draw_mode); ClassDB::bind_method(D_METHOD("set_keep_pressed_outside", "enabled"), &BaseButton::set_keep_pressed_outside); ClassDB::bind_method(D_METHOD("is_keep_pressed_outside"), &BaseButton::is_keep_pressed_outside); + ClassDB::bind_method(D_METHOD("set_shortcut_feedback", "enabled"), &BaseButton::set_shortcut_feedback); + ClassDB::bind_method(D_METHOD("is_shortcut_feedback"), &BaseButton::is_shortcut_feedback); ClassDB::bind_method(D_METHOD("set_shortcut", "shortcut"), &BaseButton::set_shortcut); ClassDB::bind_method(D_METHOD("get_shortcut"), &BaseButton::get_shortcut); @@ -436,9 +468,6 @@ void BaseButton::_bind_methods() { ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group); ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group); - ClassDB::bind_method(D_METHOD("set_shortcut_feedback", "enabled"), &BaseButton::set_shortcut_feedback); - ClassDB::bind_method(D_METHOD("is_shortcut_feedback"), &BaseButton::is_shortcut_feedback); - GDVIRTUAL_BIND(_pressed); GDVIRTUAL_BIND(_toggled, "button_pressed"); @@ -466,6 +495,8 @@ void BaseButton::_bind_methods() { BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_PRESS); BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_RELEASE); + + GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "gui/timers/button_shortcut_feedback_highlight_time", PROPERTY_HINT_RANGE, "0.01,10,0.01,suffix:s"), 0.2); } BaseButton::BaseButton() { diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h index f7c864c5fb..962a16c453 100644 --- a/scene/gui/base_button.h +++ b/scene/gui/base_button.h @@ -51,9 +51,9 @@ private: bool shortcut_in_tooltip = true; bool was_mouse_pressed = false; bool keep_pressed_outside = false; + bool shortcut_feedback = true; Ref<Shortcut> shortcut; ObjectID shortcut_context; - bool shortcut_feedback = true; ActionMode action_mode = ACTION_MODE_BUTTON_RELEASE; struct Status { @@ -61,7 +61,6 @@ private: bool hovering = false; bool press_attempt = false; bool pressing_inside = false; - bool shortcut_press = false; bool disabled = false; @@ -75,6 +74,10 @@ private: void on_action_event(Ref<InputEvent> p_event); + Timer *shortcut_feedback_timer = nullptr; + bool in_shortcut_feedback = false; + void _shortcut_feedback_timeout(); + protected: virtual void pressed(); virtual void toggled(bool p_pressed); @@ -122,6 +125,9 @@ public: void set_keep_pressed_outside(bool p_on); bool is_keep_pressed_outside() const; + void set_shortcut_feedback(bool p_enable); + bool is_shortcut_feedback() const; + void set_button_mask(BitField<MouseButtonMask> p_mask); BitField<MouseButtonMask> get_button_mask() const; @@ -133,9 +139,6 @@ public: void set_button_group(const Ref<ButtonGroup> &p_group); Ref<ButtonGroup> get_button_group() const; - void set_shortcut_feedback(bool p_feedback); - bool is_shortcut_feedback() const; - PackedStringArray get_configuration_warnings() const override; BaseButton(); diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index dea61fcf66..5ab64b35fd 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -3336,6 +3336,7 @@ void RichTextLabel::push_table(int p_columns, InlineAlignment p_alignment, int p _stop_thread(); MutexLock data_lock(data_mutex); + ERR_FAIL_COND(current->type == ITEM_TABLE); ERR_FAIL_COND(p_columns < 1); ItemTable *item = memnew(ItemTable); diff --git a/scene/gui/texture_rect.cpp b/scene/gui/texture_rect.cpp index ac6d0cd453..20472ab46e 100644 --- a/scene/gui/texture_rect.cpp +++ b/scene/gui/texture_rect.cpp @@ -110,22 +110,45 @@ void TextureRect::_notification(int p_what) { draw_texture_rect(texture, Rect2(offset, size), tile); } } break; + case NOTIFICATION_RESIZED: { + update_minimum_size(); + } break; } } Size2 TextureRect::get_minimum_size() const { - if (!ignore_texture_size && !texture.is_null()) { - return texture->get_size(); - } else { - return Size2(); + if (!texture.is_null()) { + switch (expand_mode) { + case EXPAND_KEEP_SIZE: { + return texture->get_size(); + } break; + case EXPAND_IGNORE_SIZE: { + return Size2(); + } break; + case EXPAND_FIT_WIDTH: { + return Size2(get_size().y, 0); + } break; + case EXPAND_FIT_WIDTH_PROPORTIONAL: { + real_t ratio = real_t(texture->get_width()) / texture->get_height(); + return Size2(get_size().y * ratio, 0); + } break; + case EXPAND_FIT_HEIGHT: { + return Size2(0, get_size().x); + } break; + case EXPAND_FIT_HEIGHT_PROPORTIONAL: { + real_t ratio = real_t(texture->get_height()) / texture->get_width(); + return Size2(0, get_size().x * ratio); + } break; + } } + return Size2(); } void TextureRect::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TextureRect::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &TextureRect::get_texture); - ClassDB::bind_method(D_METHOD("set_ignore_texture_size", "ignore"), &TextureRect::set_ignore_texture_size); - ClassDB::bind_method(D_METHOD("get_ignore_texture_size"), &TextureRect::get_ignore_texture_size); + ClassDB::bind_method(D_METHOD("set_expand_mode", "expand_mode"), &TextureRect::set_expand_mode); + ClassDB::bind_method(D_METHOD("get_expand_mode"), &TextureRect::get_expand_mode); ClassDB::bind_method(D_METHOD("set_flip_h", "enable"), &TextureRect::set_flip_h); ClassDB::bind_method(D_METHOD("is_flipped_h"), &TextureRect::is_flipped_h); ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &TextureRect::set_flip_v); @@ -134,11 +157,18 @@ void TextureRect::_bind_methods() { ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureRect::get_stretch_mode); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_texture_size"), "set_ignore_texture_size", "get_ignore_texture_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "expand_mode", PROPERTY_HINT_ENUM, "Keep Size,Ignore Size,Fit Width,Fit Width Proportional,Fit Height,Fit Height Proportional"), "set_expand_mode", "get_expand_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); + BIND_ENUM_CONSTANT(EXPAND_KEEP_SIZE); + BIND_ENUM_CONSTANT(EXPAND_IGNORE_SIZE); + BIND_ENUM_CONSTANT(EXPAND_FIT_WIDTH); + BIND_ENUM_CONSTANT(EXPAND_FIT_WIDTH_PROPORTIONAL); + BIND_ENUM_CONSTANT(EXPAND_FIT_HEIGHT); + BIND_ENUM_CONSTANT(EXPAND_FIT_HEIGHT_PROPORTIONAL); + BIND_ENUM_CONSTANT(STRETCH_SCALE); BIND_ENUM_CONSTANT(STRETCH_TILE); BIND_ENUM_CONSTANT(STRETCH_KEEP); @@ -148,6 +178,16 @@ void TextureRect::_bind_methods() { BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED); } +#ifndef DISABLE_DEPRECATED +bool TextureRect::_set(const StringName &p_name, const Variant &p_value) { + if ((p_name == SNAME("expand") || p_name == SNAME("ignore_texture_size")) && p_value.operator bool()) { + expand_mode = EXPAND_IGNORE_SIZE; + return true; + } + return false; +} +#endif + void TextureRect::_texture_changed() { if (texture.is_valid()) { queue_redraw(); @@ -178,18 +218,18 @@ Ref<Texture2D> TextureRect::get_texture() const { return texture; } -void TextureRect::set_ignore_texture_size(bool p_ignore) { - if (ignore_texture_size == p_ignore) { +void TextureRect::set_expand_mode(ExpandMode p_mode) { + if (expand_mode == p_mode) { return; } - ignore_texture_size = p_ignore; + expand_mode = p_mode; queue_redraw(); update_minimum_size(); } -bool TextureRect::get_ignore_texture_size() const { - return ignore_texture_size; +TextureRect::ExpandMode TextureRect::get_expand_mode() const { + return expand_mode; } void TextureRect::set_stretch_mode(StretchMode p_mode) { diff --git a/scene/gui/texture_rect.h b/scene/gui/texture_rect.h index c56fee91e1..2425c6094b 100644 --- a/scene/gui/texture_rect.h +++ b/scene/gui/texture_rect.h @@ -37,6 +37,15 @@ class TextureRect : public Control { GDCLASS(TextureRect, Control); public: + enum ExpandMode { + EXPAND_KEEP_SIZE, + EXPAND_IGNORE_SIZE, + EXPAND_FIT_WIDTH, + EXPAND_FIT_WIDTH_PROPORTIONAL, + EXPAND_FIT_HEIGHT, + EXPAND_FIT_HEIGHT_PROPORTIONAL, + }; + enum StretchMode { STRETCH_SCALE, STRETCH_TILE, @@ -48,10 +57,10 @@ public: }; private: - bool ignore_texture_size = false; bool hflip = false; bool vflip = false; Ref<Texture2D> texture; + ExpandMode expand_mode = EXPAND_KEEP_SIZE; StretchMode stretch_mode = STRETCH_SCALE; void _texture_changed(); @@ -60,13 +69,16 @@ protected: void _notification(int p_what); virtual Size2 get_minimum_size() const override; static void _bind_methods(); +#ifndef DISABLE_DEPRECATED + bool _set(const StringName &p_name, const Variant &p_value); +#endif public: void set_texture(const Ref<Texture2D> &p_tex); Ref<Texture2D> get_texture() const; - void set_ignore_texture_size(bool p_ignore); - bool get_ignore_texture_size() const; + void set_expand_mode(ExpandMode p_mode); + ExpandMode get_expand_mode() const; void set_stretch_mode(StretchMode p_mode); StretchMode get_stretch_mode() const; @@ -81,6 +93,7 @@ public: ~TextureRect(); }; +VARIANT_ENUM_CAST(TextureRect::ExpandMode); VARIANT_ENUM_CAST(TextureRect::StretchMode); #endif // TEXTURE_RECT_H diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp index 3f98b540fc..05caad78a0 100644 --- a/scene/main/canvas_item.cpp +++ b/scene/main/canvas_item.cpp @@ -483,7 +483,7 @@ bool CanvasItem::is_y_sort_enabled() const { return y_sort_enabled; } -void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, real_t p_dash) { +void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, real_t p_dash, bool p_aligned) { ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); float length = (p_to - p_from).length(); @@ -492,14 +492,20 @@ void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, cons return; } - Point2 off = p_from; Vector2 step = p_dash * (p_to - p_from).normalized(); - int steps = length / p_dash / 2; - for (int i = 0; i < steps; i++) { - RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, (off + step), p_color, p_width); - off += 2 * step; + int steps = (p_aligned) ? Math::ceil(length / p_dash) : Math::floor(length / p_dash); + if (steps % 2 == 0) { + steps--; + } + + Point2 off = p_from; + if (p_aligned) { + off += (p_to - p_from).normalized() * (length - steps * p_dash) / 2.0; + } + for (int i = 0; i < steps; i += 2) { + RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, (i == 0) ? p_from : off, (p_aligned && i == steps - 1) ? p_to : (off + step), p_color, p_width); + off += step * 2; } - RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, p_to, p_color, p_width); } void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, bool p_antialiased) { @@ -963,7 +969,7 @@ void CanvasItem::_bind_methods() { ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled); ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash"), &CanvasItem::draw_dashed_line, DEFVAL(1.0), DEFVAL(2.0)); + ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash", "aligned"), &CanvasItem::draw_dashed_line, DEFVAL(1.0), DEFVAL(2.0), DEFVAL(true)); ClassDB::bind_method(D_METHOD("draw_polyline", "points", "color", "width", "antialiased"), &CanvasItem::draw_polyline, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_polyline_colors", "points", "colors", "width", "antialiased"), &CanvasItem::draw_polyline_colors, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_arc", "center", "radius", "start_angle", "end_angle", "point_count", "color", "width", "antialiased"), &CanvasItem::draw_arc, DEFVAL(1.0), DEFVAL(false)); diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h index 47b40c9b46..62357a1834 100644 --- a/scene/main/canvas_item.h +++ b/scene/main/canvas_item.h @@ -247,7 +247,7 @@ public: /* DRAWING API */ - void draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, real_t p_dash = 2.0); + void draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, real_t p_dash = 2.0, bool p_aligned = true); void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = 1.0, bool p_antialiased = false); diff --git a/scene/main/window.h b/scene/main/window.h index 97f8450628..b4887437a1 100644 --- a/scene/main/window.h +++ b/scene/main/window.h @@ -285,6 +285,7 @@ public: bool is_wrapping_controls() const; void child_controls_changed(); + Window *get_exclusive_child() const { return exclusive_child; }; Window *get_parent_visible_window() const; Viewport *get_parent_viewport() const; void popup(const Rect2i &p_rect = Rect2i()); diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 00c538976f..d56b94b6fe 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -184,15 +184,7 @@ #include "scene/resources/skeleton_modification_2d_physicalbones.h" #include "scene/resources/skeleton_modification_2d_stackholder.h" #include "scene/resources/skeleton_modification_2d_twoboneik.h" -#include "scene/resources/skeleton_modification_3d.h" -#include "scene/resources/skeleton_modification_3d_ccdik.h" -#include "scene/resources/skeleton_modification_3d_fabrik.h" -#include "scene/resources/skeleton_modification_3d_jiggle.h" -#include "scene/resources/skeleton_modification_3d_lookat.h" -#include "scene/resources/skeleton_modification_3d_stackholder.h" -#include "scene/resources/skeleton_modification_3d_twoboneik.h" #include "scene/resources/skeleton_modification_stack_2d.h" -#include "scene/resources/skeleton_modification_stack_3d.h" #include "scene/resources/skeleton_profile.h" #include "scene/resources/sky.h" #include "scene/resources/sky_material.h" @@ -833,15 +825,6 @@ void register_scene_types() { GDREGISTER_CLASS(ConvexPolygonShape3D); GDREGISTER_CLASS(ConcavePolygonShape3D); - GDREGISTER_CLASS(SkeletonModificationStack3D); - GDREGISTER_CLASS(SkeletonModification3D); - GDREGISTER_CLASS(SkeletonModification3DLookAt); - GDREGISTER_CLASS(SkeletonModification3DCCDIK); - GDREGISTER_CLASS(SkeletonModification3DFABRIK); - GDREGISTER_CLASS(SkeletonModification3DJiggle); - GDREGISTER_CLASS(SkeletonModification3DTwoBoneIK); - GDREGISTER_CLASS(SkeletonModification3DStackHolder); - OS::get_singleton()->yield(); // may take time to init #endif // _3D_DISABLED diff --git a/scene/resources/skeleton_modification_3d.cpp b/scene/resources/skeleton_modification_3d.cpp deleted file mode 100644 index 92fb4bfd78..0000000000 --- a/scene/resources/skeleton_modification_3d.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "skeleton_modification_3d.h" -#include "scene/3d/skeleton_3d.h" - -void SkeletonModification3D::_execute(real_t p_delta) { - GDVIRTUAL_CALL(_execute, p_delta); - - if (!enabled) { - return; - } -} - -void SkeletonModification3D::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack) { - is_setup = true; - } else { - WARN_PRINT("Could not setup modification with name " + this->get_name()); - } - - GDVIRTUAL_CALL(_setup_modification, Ref<SkeletonModificationStack3D>(p_stack)); -} - -void SkeletonModification3D::set_enabled(bool p_enabled) { - enabled = p_enabled; -} - -bool SkeletonModification3D::get_enabled() { - return enabled; -} - -// Helper function. Needed for CCDIK. -real_t SkeletonModification3D::clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert) { - // Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range. - if (p_angle < 0) { - p_angle = Math_TAU + p_angle; - } - - // Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order - if (p_min_bound < 0) { - p_min_bound = Math_TAU + p_min_bound; - } - if (p_max_bound < 0) { - p_max_bound = Math_TAU + p_max_bound; - } - if (p_min_bound > p_max_bound) { - SWAP(p_min_bound, p_max_bound); - } - - bool is_beyond_bounds = (p_angle < p_min_bound || p_angle > p_max_bound); - bool is_within_bounds = (p_angle > p_min_bound && p_angle < p_max_bound); - - // Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle. - if ((!p_invert && is_beyond_bounds) || (p_invert && is_within_bounds)) { - Vector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound)); - Vector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound)); - Vector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle)); - - if (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) { - p_angle = p_min_bound; - } else { - p_angle = p_max_bound; - } - } - - return p_angle; -} - -bool SkeletonModification3D::_print_execution_error(bool p_condition, String p_message) { - // If the modification is not setup, don't bother printing the error - if (!is_setup) { - return p_condition; - } - - if (p_condition && !execution_error_found) { - ERR_PRINT(p_message); - execution_error_found = true; - } - return p_condition; -} - -Ref<SkeletonModificationStack3D> SkeletonModification3D::get_modification_stack() { - return stack; -} - -void SkeletonModification3D::set_is_setup(bool p_is_setup) { - is_setup = p_is_setup; -} - -bool SkeletonModification3D::get_is_setup() const { - return is_setup; -} - -void SkeletonModification3D::set_execution_mode(int p_mode) { - execution_mode = p_mode; -} - -int SkeletonModification3D::get_execution_mode() const { - return execution_mode; -} - -void SkeletonModification3D::_bind_methods() { - GDVIRTUAL_BIND(_execute, "delta"); - GDVIRTUAL_BIND(_setup_modification, "modification_stack") - - ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModification3D::set_enabled); - ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModification3D::get_enabled); - ClassDB::bind_method(D_METHOD("get_modification_stack"), &SkeletonModification3D::get_modification_stack); - ClassDB::bind_method(D_METHOD("set_is_setup", "is_setup"), &SkeletonModification3D::set_is_setup); - ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModification3D::get_is_setup); - ClassDB::bind_method(D_METHOD("set_execution_mode", "execution_mode"), &SkeletonModification3D::set_execution_mode); - ClassDB::bind_method(D_METHOD("get_execution_mode"), &SkeletonModification3D::get_execution_mode); - ClassDB::bind_method(D_METHOD("clamp_angle", "angle", "min", "max", "invert"), &SkeletonModification3D::clamp_angle); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "execution_mode", PROPERTY_HINT_ENUM, "process,physics_process"), "set_execution_mode", "get_execution_mode"); -} - -SkeletonModification3D::SkeletonModification3D() { - stack = nullptr; - is_setup = false; -} diff --git a/scene/resources/skeleton_modification_3d.h b/scene/resources/skeleton_modification_3d.h deleted file mode 100644 index 367adbd977..0000000000 --- a/scene/resources/skeleton_modification_3d.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_H -#define SKELETON_MODIFICATION_3D_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_stack_3d.h" - -class SkeletonModificationStack3D; - -class SkeletonModification3D : public Resource { - GDCLASS(SkeletonModification3D, Resource); - friend class Skeleton3D; - friend class SkeletonModificationStack3D; - -protected: - static void _bind_methods(); - - SkeletonModificationStack3D *stack = nullptr; - int execution_mode = 0; // 0 = process - - bool enabled = true; - bool is_setup = false; - bool execution_error_found = false; - - bool _print_execution_error(bool p_condition, String p_message); - - GDVIRTUAL1(_execute, double) - GDVIRTUAL1(_setup_modification, Ref<SkeletonModificationStack3D>) - -public: - virtual void _execute(real_t p_delta); - virtual void _setup_modification(SkeletonModificationStack3D *p_stack); - - real_t clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert); - - void set_enabled(bool p_enabled); - bool get_enabled(); - - void set_execution_mode(int p_mode); - int get_execution_mode() const; - - Ref<SkeletonModificationStack3D> get_modification_stack(); - - void set_is_setup(bool p_setup); - bool get_is_setup() const; - - SkeletonModification3D(); -}; - -#endif // SKELETON_MODIFICATION_3D_H diff --git a/scene/resources/skeleton_modification_3d_ccdik.cpp b/scene/resources/skeleton_modification_3d_ccdik.cpp deleted file mode 100644 index b5c930f970..0000000000 --- a/scene/resources/skeleton_modification_3d_ccdik.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_ccdik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_ccdik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DCCDIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - int ccdik_data_size = ccdik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, ccdik_data_size, false); - - if (what == "bone_name") { - set_ccdik_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_ccdik_joint_bone_index(which, p_value); - } else if (what == "ccdik_axis") { - set_ccdik_joint_ccdik_axis(which, p_value); - } else if (what == "enable_joint_constraint") { - set_ccdik_joint_enable_constraint(which, p_value); - } else if (what == "joint_constraint_angle_min") { - set_ccdik_joint_constraint_angle_min(which, Math::deg_to_rad(real_t(p_value))); - } else if (what == "joint_constraint_angle_max") { - set_ccdik_joint_constraint_angle_max(which, Math::deg_to_rad(real_t(p_value))); - } else if (what == "joint_constraint_angles_invert") { - set_ccdik_joint_constraint_invert(which, p_value); - } - return true; - } - return true; -} - -bool SkeletonModification3DCCDIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int ccdik_data_size = ccdik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, ccdik_data_size, false); - - if (what == "bone_name") { - r_ret = get_ccdik_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_ccdik_joint_bone_index(which); - } else if (what == "ccdik_axis") { - r_ret = get_ccdik_joint_ccdik_axis(which); - } else if (what == "enable_joint_constraint") { - r_ret = get_ccdik_joint_enable_constraint(which); - } else if (what == "joint_constraint_angle_min") { - r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_min(which)); - } else if (what == "joint_constraint_angle_max") { - r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_max(which)); - } else if (what == "joint_constraint_angles_invert") { - r_ret = get_ccdik_joint_constraint_invert(which); - } - return true; - } - return true; -} - -void SkeletonModification3DCCDIK::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::INT, base_string + "ccdik_axis", - PROPERTY_HINT_ENUM, "X Axis,Y Axis,Z Axis", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "enable_joint_constraint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (ccdik_data_chain[i].enable_constraint) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_min", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_max", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "joint_constraint_angles_invert", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } -} - -void SkeletonModification3DCCDIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update"); - update_target_cache(); - return; - } - if (tip_node_cache.is_null()) { - _print_execution_error(true, "Tip cache is out of date. Attempting to update"); - update_tip_cache(); - return; - } - - // Reset the local bone overrides for CCDIK affected nodes - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - stack->skeleton->set_bone_local_pose_override(ccdik_data_chain[i].bone_idx, - stack->skeleton->get_bone_local_pose_override(ccdik_data_chain[i].bone_idx), - 0.0, false); - } - - Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - Node3D *node_tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - - if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - if (_print_execution_error(!node_tip || !node_tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) { - return; - } - - if (use_high_quality_solve) { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - for (uint32_t j = i; j < ccdik_data_chain.size(); j++) { - _execute_ccdik_joint(j, node_target, node_tip); - } - } - } else { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - _execute_ccdik_joint(i, node_target, node_tip); - } - } - - execution_error_found = false; -} - -void SkeletonModification3DCCDIK::_execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip) { - CCDIK_Joint_Data ccdik_data = ccdik_data_chain[p_joint_idx]; - - if (_print_execution_error(ccdik_data.bone_idx < 0 || ccdik_data.bone_idx > stack->skeleton->get_bone_count(), - "CCDIK joint: bone index for joint" + itos(p_joint_idx) + " not found. Cannot execute modification!")) { - return; - } - - Transform3D bone_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->get_bone_global_pose(ccdik_data.bone_idx)); - Transform3D tip_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_tip->get_global_transform())); - Transform3D target_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform())); - - if (tip_trans.origin.distance_to(target_trans.origin) <= 0.01) { - return; - } - - // Inspired (and very loosely based on) by the CCDIK algorithm made by Zalo on GitHub (https://github.com/zalo/MathUtilities) - // Convert the 3D position to a 2D position so we can use Atan2 (via the angle function) - // to know how much rotation we need on the given axis to place the tip at the target. - Vector2 tip_pos_2d; - Vector2 target_pos_2d; - if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) { - tip_pos_2d = Vector2(tip_trans.origin.y, tip_trans.origin.z); - target_pos_2d = Vector2(target_trans.origin.y, target_trans.origin.z); - bone_trans.basis.rotate_local(Vector3(1, 0, 0), target_pos_2d.angle() - tip_pos_2d.angle()); - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) { - tip_pos_2d = Vector2(tip_trans.origin.z, tip_trans.origin.x); - target_pos_2d = Vector2(target_trans.origin.z, target_trans.origin.x); - bone_trans.basis.rotate_local(Vector3(0, 1, 0), target_pos_2d.angle() - tip_pos_2d.angle()); - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) { - tip_pos_2d = Vector2(tip_trans.origin.x, tip_trans.origin.y); - target_pos_2d = Vector2(target_trans.origin.x, target_trans.origin.y); - bone_trans.basis.rotate_local(Vector3(0, 0, 1), target_pos_2d.angle() - tip_pos_2d.angle()); - } else { - // Should never happen, but... - ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!"); - } - - if (ccdik_data.enable_constraint) { - Vector3 rotation_axis; - real_t rotation_angle; - bone_trans.basis.get_axis_angle(rotation_axis, rotation_angle); - - // Note: When the axis has a negative direction, the angle is OVER 180 degrees and therefore we need to account for this - // when constraining. - if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) { - if (rotation_axis.x < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(1, 0, 0); - } - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) { - if (rotation_axis.y < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(0, 1, 0); - } - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) { - if (rotation_axis.z < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(0, 0, 1); - } - } else { - // Should never happen, but... - ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!"); - } - rotation_angle = clamp_angle(rotation_angle, ccdik_data.constraint_angle_min, ccdik_data.constraint_angle_max, ccdik_data.constraint_angles_invert); - - bone_trans.basis.set_axis_angle(rotation_axis, rotation_angle); - } - - stack->skeleton->set_bone_local_pose_override(ccdik_data.bone_idx, bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(ccdik_data.bone_idx); -} - -void SkeletonModification3DCCDIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_target_cache(); - update_tip_cache(); - } -} - -void SkeletonModification3DCCDIK::update_target_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DCCDIK::update_tip_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - - tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(tip_node)) { - Node *node = stack->skeleton->get_node(tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache: node is not in scene tree!"); - tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DCCDIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_target_cache(); -} - -NodePath SkeletonModification3DCCDIK::get_target_node() const { - return target_node; -} - -void SkeletonModification3DCCDIK::set_tip_node(const NodePath &p_tip_node) { - tip_node = p_tip_node; - update_tip_cache(); -} - -NodePath SkeletonModification3DCCDIK::get_tip_node() const { - return tip_node; -} - -void SkeletonModification3DCCDIK::set_use_high_quality_solve(bool p_high_quality) { - use_high_quality_solve = p_high_quality; -} - -bool SkeletonModification3DCCDIK::get_use_high_quality_solve() const { - return use_high_quality_solve; -} - -// CCDIK joint data functions -String SkeletonModification3DCCDIK::get_ccdik_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String()); - return ccdik_data_chain[p_joint_idx].bone_name; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].bone_name = p_bone_name; - - if (stack) { - if (stack->skeleton) { - ccdik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DCCDIK::get_ccdik_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return ccdik_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - ccdik_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - ccdik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return ccdik_data_chain[p_joint_idx].ccdik_axis; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_axis < 0, "CCDIK axis is out of range: The axis mode is too low!"); - ccdik_data_chain[p_joint_idx].ccdik_axis = p_axis; - notify_property_list_changed(); -} - -bool SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].enable_constraint; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].enable_constraint = p_enable; - notify_property_list_changed(); -} - -real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angle_min; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angle_min = p_angle_min; -} - -real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angle_max; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angle_max = p_angle_max; -} - -bool SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angles_invert; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angles_invert = p_invert; -} - -int SkeletonModification3DCCDIK::get_ccdik_data_chain_length() { - return ccdik_data_chain.size(); -} -void SkeletonModification3DCCDIK::set_ccdik_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - ccdik_data_chain.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DCCDIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DCCDIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DCCDIK::get_target_node); - - ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DCCDIK::set_tip_node); - ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DCCDIK::get_tip_node); - - ClassDB::bind_method(D_METHOD("set_use_high_quality_solve", "high_quality_solve"), &SkeletonModification3DCCDIK::set_use_high_quality_solve); - ClassDB::bind_method(D_METHOD("get_use_high_quality_solve"), &SkeletonModification3DCCDIK::get_use_high_quality_solve); - - // CCDIK joint data functions - ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_name", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_index", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_ccdik_axis", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_ccdik_axis", "joint_idx", "axis"), &SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_enable_joint_constraint", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_enable_joint_constraint", "joint_idx", "enable"), &SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_min", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_min", "joint_idx", "min_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_max", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_max", "joint_idx", "max_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_invert", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_invert", "joint_idx", "invert"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert); - - ClassDB::bind_method(D_METHOD("set_ccdik_data_chain_length", "length"), &SkeletonModification3DCCDIK::set_ccdik_data_chain_length); - ClassDB::bind_method(D_METHOD("get_ccdik_data_chain_length"), &SkeletonModification3DCCDIK::get_ccdik_data_chain_length); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "tip_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_tip_node", "get_tip_node"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "high_quality_solve", PROPERTY_HINT_NONE, ""), "set_use_high_quality_solve", "get_use_high_quality_solve"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "ccdik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_ccdik_data_chain_length", "get_ccdik_data_chain_length"); -} - -SkeletonModification3DCCDIK::SkeletonModification3DCCDIK() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DCCDIK::~SkeletonModification3DCCDIK() { -} diff --git a/scene/resources/skeleton_modification_3d_ccdik.h b/scene/resources/skeleton_modification_3d_ccdik.h deleted file mode 100644 index 30c29bb3aa..0000000000 --- a/scene/resources/skeleton_modification_3d_ccdik.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_ccdik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_CCDIK_H -#define SKELETON_MODIFICATION_3D_CCDIK_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DCCDIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DCCDIK, SkeletonModification3D); - -private: - enum CCDIK_Axes { - AXIS_X, - AXIS_Y, - AXIS_Z - }; - - struct CCDIK_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - int ccdik_axis = 0; - - bool enable_constraint = false; - real_t constraint_angle_min = 0; - real_t constraint_angle_max = (2.0 * Math_PI); - bool constraint_angles_invert = false; - }; - - LocalVector<CCDIK_Joint_Data> ccdik_data_chain; - NodePath target_node; - ObjectID target_node_cache; - - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_high_quality_solve = true; - - void update_target_cache(); - void update_tip_cache(); - - void _execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_tip_node(const NodePath &p_tip_node); - NodePath get_tip_node() const; - - void set_use_high_quality_solve(bool p_solve); - bool get_use_high_quality_solve() const; - - String get_ccdik_joint_bone_name(int p_joint_idx) const; - void set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name); - int get_ccdik_joint_bone_index(int p_joint_idx) const; - void set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx); - int get_ccdik_joint_ccdik_axis(int p_joint_idx) const; - void set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis); - bool get_ccdik_joint_enable_constraint(int p_joint_idx) const; - void set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable); - real_t get_ccdik_joint_constraint_angle_min(int p_joint_idx) const; - void set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min); - real_t get_ccdik_joint_constraint_angle_max(int p_joint_idx) const; - void set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max); - bool get_ccdik_joint_constraint_invert(int p_joint_idx) const; - void set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert); - - int get_ccdik_data_chain_length(); - void set_ccdik_data_chain_length(int p_new_length); - - SkeletonModification3DCCDIK(); - ~SkeletonModification3DCCDIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_CCDIK_H diff --git a/scene/resources/skeleton_modification_3d_fabrik.cpp b/scene/resources/skeleton_modification_3d_fabrik.cpp deleted file mode 100644 index 9fb7ade155..0000000000 --- a/scene/resources/skeleton_modification_3d_fabrik.cpp +++ /dev/null @@ -1,628 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_fabrik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_fabrik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DFABRIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - int fabrik_data_size = fabrik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, fabrik_data_size, false); - - if (what == "bone_name") { - set_fabrik_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_fabrik_joint_bone_index(which, p_value); - } else if (what == "length") { - set_fabrik_joint_length(which, p_value); - } else if (what == "magnet_position") { - set_fabrik_joint_magnet(which, p_value); - } else if (what == "auto_calculate_length") { - set_fabrik_joint_auto_calculate_length(which, p_value); - } else if (what == "use_tip_node") { - set_fabrik_joint_use_tip_node(which, p_value); - } else if (what == "tip_node") { - set_fabrik_joint_tip_node(which, p_value); - } else if (what == "use_target_basis") { - set_fabrik_joint_use_target_basis(which, p_value); - } else if (what == "roll") { - set_fabrik_joint_roll(which, Math::deg_to_rad(real_t(p_value))); - } - return true; - } - return true; -} - -bool SkeletonModification3DFABRIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int fabrik_data_size = fabrik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, fabrik_data_size, false); - - if (what == "bone_name") { - r_ret = get_fabrik_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_fabrik_joint_bone_index(which); - } else if (what == "length") { - r_ret = get_fabrik_joint_length(which); - } else if (what == "magnet_position") { - r_ret = get_fabrik_joint_magnet(which); - } else if (what == "auto_calculate_length") { - r_ret = get_fabrik_joint_auto_calculate_length(which); - } else if (what == "use_tip_node") { - r_ret = get_fabrik_joint_use_tip_node(which); - } else if (what == "tip_node") { - r_ret = get_fabrik_joint_tip_node(which); - } else if (what == "use_target_basis") { - r_ret = get_fabrik_joint_use_target_basis(which); - } else if (what == "roll") { - r_ret = Math::rad_to_deg(get_fabrik_joint_roll(which)); - } - return true; - } - return true; -} - -void SkeletonModification3DFABRIK::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "auto_calculate_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - if (!fabrik_data_chain[i].auto_calculate_length) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } else { - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (fabrik_data_chain[i].use_tip_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - } - - // Cannot apply magnet to the origin of the chain, as it will not do anything. - if (i > 0) { - p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "magnet_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - // Only give the override basis option on the last bone in the chain, so only include it for the last bone. - if (i == fabrik_data_chain.size() - 1) { - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_target_basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } -} - -void SkeletonModification3DFABRIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_target_cache(); - return; - } - - if (_print_execution_error(fabrik_data_chain.size() <= 1, "FABRIK requires at least two joints to operate. Cannot execute modification!")) { - return; - } - - Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - - // Make sure the transform cache is the correct size - if (fabrik_transforms.size() != fabrik_data_chain.size()) { - fabrik_transforms.resize(fabrik_data_chain.size()); - } - - // Verify that all joints have a valid bone ID, and that all bone lengths are zero or more - // Also, while we are here, apply magnet positions. - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - if (_print_execution_error(fabrik_data_chain[i].bone_idx < 0, "FABRIK Joint " + itos(i) + " has an invalid bone ID. Cannot execute!")) { - return; - } - - if (fabrik_data_chain[i].length < 0 && fabrik_data_chain[i].auto_calculate_length) { - fabrik_joint_auto_calculate_length(i); - } - if (_print_execution_error(fabrik_data_chain[i].length < 0, "FABRIK Joint " + itos(i) + " has an invalid joint length. Cannot execute!")) { - return; - } - fabrik_transforms[i] = stack->skeleton->get_bone_global_pose(fabrik_data_chain[i].bone_idx); - - // Apply magnet positions: - if (stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx) >= 0) { - int parent_bone_idx = stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx); - Transform3D conversion_transform = (stack->skeleton->get_bone_global_pose(parent_bone_idx)); - fabrik_transforms[i].origin += conversion_transform.basis.xform_inv(fabrik_data_chain[i].magnet_position); - } else { - fabrik_transforms[i].origin += fabrik_data_chain[i].magnet_position; - } - } - Transform3D origin_global_pose_trans = stack->skeleton->get_bone_global_pose_no_override(fabrik_data_chain[0].bone_idx); - - target_global_pose = stack->skeleton->world_transform_to_global_pose(node_target->get_global_transform()); - origin_global_pose = origin_global_pose_trans; - - final_joint_idx = fabrik_data_chain.size() - 1; - real_t target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin); - chain_iterations = 0; - - while (target_distance > chain_tolerance) { - chain_backwards(); - chain_forwards(); - - // update the target distance - target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin); - - // update chain iterations - chain_iterations += 1; - if (chain_iterations >= chain_max_iterations) { - break; - } - } - chain_apply(); - - execution_error_found = false; -} - -void SkeletonModification3DFABRIK::chain_backwards() { - int final_bone_idx = fabrik_data_chain[final_joint_idx].bone_idx; - Transform3D final_joint_trans = fabrik_transforms[final_joint_idx]; - - // Get the direction the final bone is facing in. - stack->skeleton->update_bone_rest_forward_vector(final_bone_idx); - Transform3D final_bone_direction_trans = final_joint_trans.looking_at(target_global_pose.origin, Vector3(0, 1, 0)); - final_bone_direction_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(final_bone_idx, final_bone_direction_trans.basis); - Vector3 direction = final_bone_direction_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized(); - - // If set to override, then use the target's Basis rather than the bone's - if (fabrik_data_chain[final_joint_idx].use_target_basis) { - direction = target_global_pose.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized(); - } - - // set the position of the final joint to the target position - final_joint_trans.origin = target_global_pose.origin - (direction * fabrik_data_chain[final_joint_idx].length); - fabrik_transforms[final_joint_idx] = final_joint_trans; - - // for all other joints, move them towards the target - int i = final_joint_idx; - while (i >= 1) { - Transform3D next_bone_trans = fabrik_transforms[i]; - i -= 1; - Transform3D current_trans = fabrik_transforms[i]; - - real_t length = fabrik_data_chain[i].length / (current_trans.origin.distance_to(next_bone_trans.origin)); - current_trans.origin = next_bone_trans.origin.lerp(current_trans.origin, length); - - // Save the result - fabrik_transforms[i] = current_trans; - } -} - -void SkeletonModification3DFABRIK::chain_forwards() { - // Set root at the initial position. - Transform3D root_transform = fabrik_transforms[0]; - - root_transform.origin = origin_global_pose.origin; - fabrik_transforms[0] = origin_global_pose; - - for (uint32_t i = 0; i < fabrik_data_chain.size() - 1; i++) { - Transform3D current_trans = fabrik_transforms[i]; - Transform3D next_bone_trans = fabrik_transforms[i + 1]; - - real_t length = fabrik_data_chain[i].length / (next_bone_trans.origin.distance_to(current_trans.origin)); - next_bone_trans.origin = current_trans.origin.lerp(next_bone_trans.origin, length); - - // Save the result - fabrik_transforms[i + 1] = next_bone_trans; - } -} - -void SkeletonModification3DFABRIK::chain_apply() { - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - int current_bone_idx = fabrik_data_chain[i].bone_idx; - Transform3D current_trans = fabrik_transforms[i]; - - // If this is the last bone in the chain... - if (i == fabrik_data_chain.size() - 1) { - if (fabrik_data_chain[i].use_target_basis == false) { // Point to target... - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(current_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx); - // Rotate the bone towards the target: - current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(target_global_pose.origin)); - current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll); - } else { // Use the target's Basis... - current_trans.basis = target_global_pose.basis.orthonormalized().scaled(current_trans.basis.get_scale()); - } - } else { // every other bone in the chain... - Transform3D next_trans = fabrik_transforms[i + 1]; - - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(current_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx); - // Rotate the bone towards the next bone in the chain: - current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(next_trans.origin)); - current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll); - } - stack->skeleton->set_bone_local_pose_override(current_bone_idx, stack->skeleton->global_pose_to_local_pose(current_bone_idx, current_trans), stack->strength, true); - } - - // Update all the bones so the next modification has up-to-date data. - stack->skeleton->force_update_all_bone_transforms(); -} - -void SkeletonModification3DFABRIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_target_cache(); - - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - update_joint_tip_cache(i); - } - } -} - -void SkeletonModification3DFABRIK::update_target_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DFABRIK::update_joint_tip_cache(int p_joint_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_MSG(p_joint_idx, bone_chain_size, "FABRIK joint not found"); - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - fabrik_data_chain[p_joint_idx].tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && fabrik_data_chain[p_joint_idx].tip_node.is_empty() == false) { - if (stack->skeleton->has_node(fabrik_data_chain[p_joint_idx].tip_node)) { - Node *node = stack->skeleton->get_node(fabrik_data_chain[p_joint_idx].tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is not in scene tree!"); - fabrik_data_chain[p_joint_idx].tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DFABRIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_target_cache(); -} - -NodePath SkeletonModification3DFABRIK::get_target_node() const { - return target_node; -} - -int SkeletonModification3DFABRIK::get_fabrik_data_chain_length() { - return fabrik_data_chain.size(); -} - -void SkeletonModification3DFABRIK::set_fabrik_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - fabrik_data_chain.resize(p_length); - fabrik_transforms.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -real_t SkeletonModification3DFABRIK::get_chain_tolerance() { - return chain_tolerance; -} - -void SkeletonModification3DFABRIK::set_chain_tolerance(real_t p_tolerance) { - ERR_FAIL_COND_MSG(p_tolerance <= 0, "FABRIK chain tolerance must be more than zero!"); - chain_tolerance = p_tolerance; -} - -int SkeletonModification3DFABRIK::get_chain_max_iterations() { - return chain_max_iterations; -} -void SkeletonModification3DFABRIK::set_chain_max_iterations(int p_iterations) { - ERR_FAIL_COND_MSG(p_iterations <= 0, "FABRIK chain iterations must be at least one. Set enabled to false to disable the FABRIK chain."); - chain_max_iterations = p_iterations; -} - -// FABRIK joint data functions -String SkeletonModification3DFABRIK::get_fabrik_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String()); - return fabrik_data_chain[p_joint_idx].bone_name; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].bone_name = p_bone_name; - - if (stack) { - if (stack->skeleton) { - fabrik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DFABRIK::get_fabrik_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return fabrik_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - fabrik_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - fabrik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -real_t SkeletonModification3DFABRIK::get_fabrik_joint_length(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return fabrik_data_chain[p_joint_idx].length; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_length < 0, "FABRIK joint length cannot be less than zero!"); - - if (!is_setup) { - fabrik_data_chain[p_joint_idx].length = p_bone_length; - return; - } - - if (fabrik_data_chain[p_joint_idx].auto_calculate_length) { - WARN_PRINT("FABRIK Length not set: auto calculate length is enabled for this joint!"); - fabrik_joint_auto_calculate_length(p_joint_idx); - } else { - fabrik_data_chain[p_joint_idx].length = p_bone_length; - } - - execution_error_found = false; -} - -Vector3 SkeletonModification3DFABRIK::get_fabrik_joint_magnet(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3()); - return fabrik_data_chain[p_joint_idx].magnet_position; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].magnet_position = p_magnet; -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].auto_calculate_length; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].auto_calculate_length = p_auto_calculate; - fabrik_joint_auto_calculate_length(p_joint_idx); - notify_property_list_changed(); -} - -void SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length(int p_joint_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - if (!fabrik_data_chain[p_joint_idx].auto_calculate_length) { - return; - } - - if (!stack || !stack->skeleton || !is_setup) { - _print_execution_error(true, "Cannot auto calculate joint length: modification is not properly setup!"); - return; - } - ERR_FAIL_INDEX_MSG(fabrik_data_chain[p_joint_idx].bone_idx, stack->skeleton->get_bone_count(), - "Bone for joint " + itos(p_joint_idx) + " is not set or points to an unknown bone!"); - - if (fabrik_data_chain[p_joint_idx].use_tip_node) { // Use the tip node to update joint length. - - update_joint_tip_cache(p_joint_idx); - - Node3D *tip_node = Object::cast_to<Node3D>(ObjectDB::get_instance(fabrik_data_chain[p_joint_idx].tip_node_cache)); - ERR_FAIL_COND_MSG(!tip_node, "Tip node for joint " + itos(p_joint_idx) + "is not a Node3D-based node. Cannot calculate length..."); - ERR_FAIL_COND_MSG(!tip_node->is_inside_tree(), "Tip node for joint " + itos(p_joint_idx) + "is not in the scene tree. Cannot calculate length..."); - - Transform3D node_trans = tip_node->get_global_transform(); - node_trans = stack->skeleton->world_transform_to_global_pose(node_trans); - //node_trans = stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, node_trans); - //fabrik_data_chain[p_joint_idx].length = node_trans.origin.length(); - - fabrik_data_chain[p_joint_idx].length = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx).origin.distance_to(node_trans.origin); - - } else { // Use child bone(s) to update joint length, if possible - Vector<int> bone_children = stack->skeleton->get_bone_children(fabrik_data_chain[p_joint_idx].bone_idx); - if (bone_children.size() <= 0) { - ERR_FAIL_MSG("Cannot calculate length for joint " + itos(p_joint_idx) + "joint uses leaf bone. \nPlease manually set the bone length or use a tip node!"); - return; - } - - Transform3D bone_trans = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx); - - real_t final_length = 0; - for (int i = 0; i < bone_children.size(); i++) { - Transform3D child_transform = stack->skeleton->get_bone_global_pose(bone_children[i]); - final_length += bone_trans.origin.distance_to(child_transform.origin); - //final_length += stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, child_transform).origin.length(); - } - fabrik_data_chain[p_joint_idx].length = final_length / bone_children.size(); - } - execution_error_found = false; - notify_property_list_changed(); -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].use_tip_node; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].use_tip_node = p_use_tip_node; - notify_property_list_changed(); -} - -NodePath SkeletonModification3DFABRIK::get_fabrik_joint_tip_node(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, NodePath()); - return fabrik_data_chain[p_joint_idx].tip_node; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].tip_node = p_tip_node; - update_joint_tip_cache(p_joint_idx); -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].use_target_basis; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_target_basis) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].use_target_basis = p_use_target_basis; -} - -real_t SkeletonModification3DFABRIK::get_fabrik_joint_roll(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0); - return fabrik_data_chain[p_joint_idx].roll; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_roll(int p_joint_idx, real_t p_roll) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].roll = p_roll; -} - -void SkeletonModification3DFABRIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DFABRIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DFABRIK::get_target_node); - ClassDB::bind_method(D_METHOD("set_fabrik_data_chain_length", "length"), &SkeletonModification3DFABRIK::set_fabrik_data_chain_length); - ClassDB::bind_method(D_METHOD("get_fabrik_data_chain_length"), &SkeletonModification3DFABRIK::get_fabrik_data_chain_length); - ClassDB::bind_method(D_METHOD("set_chain_tolerance", "tolerance"), &SkeletonModification3DFABRIK::set_chain_tolerance); - ClassDB::bind_method(D_METHOD("get_chain_tolerance"), &SkeletonModification3DFABRIK::get_chain_tolerance); - ClassDB::bind_method(D_METHOD("set_chain_max_iterations", "max_iterations"), &SkeletonModification3DFABRIK::set_chain_max_iterations); - ClassDB::bind_method(D_METHOD("get_chain_max_iterations"), &SkeletonModification3DFABRIK::get_chain_max_iterations); - - // FABRIK joint data functions - ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_name", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_index", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_length); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_length", "joint_idx", "length"), &SkeletonModification3DFABRIK::set_fabrik_joint_length); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_magnet", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_magnet); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_magnet", "joint_idx", "magnet_position"), &SkeletonModification3DFABRIK::set_fabrik_joint_magnet); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_auto_calculate_length", "joint_idx", "auto_calculate_length"), &SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_tip_node", "joint_idx", "use_tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_tip_node); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_tip_node", "joint_idx", "tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_tip_node); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_target_basis", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_target_basis", "joint_idx", "use_target_basis"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "fabrik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_fabrik_data_chain_length", "get_fabrik_data_chain_length"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "chain_tolerance", PROPERTY_HINT_RANGE, "0,100,0.001"), "set_chain_tolerance", "get_chain_tolerance"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "chain_max_iterations", PROPERTY_HINT_RANGE, "1,50,1"), "set_chain_max_iterations", "get_chain_max_iterations"); -} - -SkeletonModification3DFABRIK::SkeletonModification3DFABRIK() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DFABRIK::~SkeletonModification3DFABRIK() { -} diff --git a/scene/resources/skeleton_modification_3d_fabrik.h b/scene/resources/skeleton_modification_3d_fabrik.h deleted file mode 100644 index c834658093..0000000000 --- a/scene/resources/skeleton_modification_3d_fabrik.h +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_fabrik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_FABRIK_H -#define SKELETON_MODIFICATION_3D_FABRIK_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DFABRIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DFABRIK, SkeletonModification3D); - -private: - struct FABRIK_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - real_t length = -1; - Vector3 magnet_position = Vector3(0, 0, 0); - - bool auto_calculate_length = true; - bool use_tip_node = false; - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_target_basis = false; - real_t roll = 0; - }; - - LocalVector<FABRIK_Joint_Data> fabrik_data_chain; - LocalVector<Transform3D> fabrik_transforms; - - NodePath target_node; - ObjectID target_node_cache; - - real_t chain_tolerance = 0.01; - int chain_max_iterations = 10; - int chain_iterations = 0; - - void update_target_cache(); - void update_joint_tip_cache(int p_joint_idx); - - int final_joint_idx = 0; - Transform3D target_global_pose; - Transform3D origin_global_pose; - - void chain_backwards(); - void chain_forwards(); - void chain_apply(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - int get_fabrik_data_chain_length(); - void set_fabrik_data_chain_length(int p_new_length); - - real_t get_chain_tolerance(); - void set_chain_tolerance(real_t p_tolerance); - - int get_chain_max_iterations(); - void set_chain_max_iterations(int p_iterations); - - String get_fabrik_joint_bone_name(int p_joint_idx) const; - void set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name); - int get_fabrik_joint_bone_index(int p_joint_idx) const; - void set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx); - real_t get_fabrik_joint_length(int p_joint_idx) const; - void set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length); - Vector3 get_fabrik_joint_magnet(int p_joint_idx) const; - void set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet); - bool get_fabrik_joint_auto_calculate_length(int p_joint_idx) const; - void set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate); - void fabrik_joint_auto_calculate_length(int p_joint_idx); - bool get_fabrik_joint_use_tip_node(int p_joint_idx) const; - void set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node); - NodePath get_fabrik_joint_tip_node(int p_joint_idx) const; - void set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node); - bool get_fabrik_joint_use_target_basis(int p_joint_idx) const; - void set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_basis); - real_t get_fabrik_joint_roll(int p_joint_idx) const; - void set_fabrik_joint_roll(int p_joint_idx, real_t p_roll); - - SkeletonModification3DFABRIK(); - ~SkeletonModification3DFABRIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_FABRIK_H diff --git a/scene/resources/skeleton_modification_3d_jiggle.cpp b/scene/resources/skeleton_modification_3d_jiggle.cpp deleted file mode 100644 index 2cfc7fb10f..0000000000 --- a/scene/resources/skeleton_modification_3d_jiggle.cpp +++ /dev/null @@ -1,582 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_jiggle.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_jiggle.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DJiggle::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int jiggle_size = jiggle_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, jiggle_size, false); - - if (what == "bone_name") { - set_jiggle_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_jiggle_joint_bone_index(which, p_value); - } else if (what == "override_defaults") { - set_jiggle_joint_override(which, p_value); - } else if (what == "stiffness") { - set_jiggle_joint_stiffness(which, p_value); - } else if (what == "mass") { - set_jiggle_joint_mass(which, p_value); - } else if (what == "damping") { - set_jiggle_joint_damping(which, p_value); - } else if (what == "use_gravity") { - set_jiggle_joint_use_gravity(which, p_value); - } else if (what == "gravity") { - set_jiggle_joint_gravity(which, p_value); - } else if (what == "roll") { - set_jiggle_joint_roll(which, Math::deg_to_rad(real_t(p_value))); - } - return true; - } else { - if (path == "use_colliders") { - set_use_colliders(p_value); - } else if (path == "collision_mask") { - set_collision_mask(p_value); - } - return true; - } - return true; -} - -bool SkeletonModification3DJiggle::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int jiggle_size = jiggle_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, jiggle_size, false); - - if (what == "bone_name") { - r_ret = get_jiggle_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_jiggle_joint_bone_index(which); - } else if (what == "override_defaults") { - r_ret = get_jiggle_joint_override(which); - } else if (what == "stiffness") { - r_ret = get_jiggle_joint_stiffness(which); - } else if (what == "mass") { - r_ret = get_jiggle_joint_mass(which); - } else if (what == "damping") { - r_ret = get_jiggle_joint_damping(which); - } else if (what == "use_gravity") { - r_ret = get_jiggle_joint_use_gravity(which); - } else if (what == "gravity") { - r_ret = get_jiggle_joint_gravity(which); - } else if (what == "roll") { - r_ret = Math::rad_to_deg(get_jiggle_joint_roll(which)); - } - return true; - } else { - if (path == "use_colliders") { - r_ret = get_use_colliders(); - } else if (path == "collision_mask") { - r_ret = get_collision_mask(); - } - return true; - } - return true; -} - -void SkeletonModification3DJiggle::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "use_colliders", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_colliders) { - p_list->push_back(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS, "", PROPERTY_USAGE_DEFAULT)); - } - - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "override_defaults", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - if (jiggle_data_chain[i].override_defaults) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "stiffness", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "mass", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (jiggle_data_chain[i].use_gravity) { - p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } - } -} - -void SkeletonModification3DJiggle::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache(); - return; - } - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - _print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!"); - - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - _execute_jiggle_joint(i, target, p_delta); - } - - execution_error_found = false; -} - -void SkeletonModification3DJiggle::_execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta) { - // Adopted from: https://wiki.unity3d.com/index.php/JiggleBone - // With modifications by TwistedTwigleg. - - if (jiggle_data_chain[p_joint_idx].bone_idx <= -2) { - jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(jiggle_data_chain[p_joint_idx].bone_name); - } - if (_print_execution_error( - jiggle_data_chain[p_joint_idx].bone_idx < 0 || jiggle_data_chain[p_joint_idx].bone_idx > stack->skeleton->get_bone_count(), - "Jiggle joint " + itos(p_joint_idx) + " bone index is invalid. Cannot execute modification!")) { - return; - } - - Transform3D bone_local_pos = stack->skeleton->get_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx); - if (bone_local_pos == Transform3D()) { - bone_local_pos = stack->skeleton->get_bone_pose(jiggle_data_chain[p_joint_idx].bone_idx); - } - - Transform3D new_bone_trans = stack->skeleton->local_pose_to_global_pose(jiggle_data_chain[p_joint_idx].bone_idx, bone_local_pos); - Vector3 target_position = stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform()).origin; - - jiggle_data_chain[p_joint_idx].force = (target_position - jiggle_data_chain[p_joint_idx].dynamic_position) * jiggle_data_chain[p_joint_idx].stiffness * p_delta; - - if (jiggle_data_chain[p_joint_idx].use_gravity) { - Vector3 gravity_to_apply = new_bone_trans.basis.inverse().xform(jiggle_data_chain[p_joint_idx].gravity); - jiggle_data_chain[p_joint_idx].force += gravity_to_apply * p_delta; - } - - jiggle_data_chain[p_joint_idx].acceleration = jiggle_data_chain[p_joint_idx].force / jiggle_data_chain[p_joint_idx].mass; - jiggle_data_chain[p_joint_idx].velocity += jiggle_data_chain[p_joint_idx].acceleration * (1 - jiggle_data_chain[p_joint_idx].damping); - - jiggle_data_chain[p_joint_idx].dynamic_position += jiggle_data_chain[p_joint_idx].velocity + jiggle_data_chain[p_joint_idx].force; - jiggle_data_chain[p_joint_idx].dynamic_position += new_bone_trans.origin - jiggle_data_chain[p_joint_idx].last_position; - jiggle_data_chain[p_joint_idx].last_position = new_bone_trans.origin; - - // Collision detection/response - if (use_colliders) { - if (execution_mode == SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_physics_process) { - Ref<World3D> world_3d = stack->skeleton->get_world_3d(); - ERR_FAIL_COND(world_3d.is_null()); - PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space()); - PhysicsDirectSpaceState3D::RayResult ray_result; - - // Convert to world transforms, which is what the physics server needs - Transform3D new_bone_trans_world = stack->skeleton->global_pose_to_world_transform(new_bone_trans); - Transform3D dynamic_position_world = stack->skeleton->global_pose_to_world_transform(Transform3D(Basis(), jiggle_data_chain[p_joint_idx].dynamic_position)); - - PhysicsDirectSpaceState3D::RayParameters ray_params; - ray_params.from = new_bone_trans_world.origin; - ray_params.to = dynamic_position_world.get_origin(); - ray_params.collision_mask = collision_mask; - - bool ray_hit = space_state->intersect_ray(ray_params, ray_result); - - if (ray_hit) { - jiggle_data_chain[p_joint_idx].dynamic_position = jiggle_data_chain[p_joint_idx].last_noncollision_position; - jiggle_data_chain[p_joint_idx].acceleration = Vector3(0, 0, 0); - jiggle_data_chain[p_joint_idx].velocity = Vector3(0, 0, 0); - } else { - jiggle_data_chain[p_joint_idx].last_noncollision_position = jiggle_data_chain[p_joint_idx].dynamic_position; - } - - } else { - WARN_PRINT_ONCE("Jiggle modifier: You cannot detect colliders without the stack mode being set to _physics_process!"); - } - } - - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx); - - // Rotate the bone using the dynamic position! - new_bone_trans.basis.rotate_to_align(forward_vector, new_bone_trans.origin.direction_to(jiggle_data_chain[p_joint_idx].dynamic_position)); - - // Roll - new_bone_trans.basis.rotate_local(forward_vector, jiggle_data_chain[p_joint_idx].roll); - - new_bone_trans = stack->skeleton->global_pose_to_local_pose(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans); - stack->skeleton->set_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(jiggle_data_chain[p_joint_idx].bone_idx); -} - -void SkeletonModification3DJiggle::_update_jiggle_joint_data() { - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - if (!jiggle_data_chain[i].override_defaults) { - set_jiggle_joint_stiffness(i, stiffness); - set_jiggle_joint_mass(i, mass); - set_jiggle_joint_damping(i, damping); - set_jiggle_joint_use_gravity(i, use_gravity); - set_jiggle_joint_gravity(i, gravity); - } - } -} - -void SkeletonModification3DJiggle::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack) { - is_setup = true; - execution_error_found = false; - - if (stack->skeleton) { - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - int bone_idx = jiggle_data_chain[i].bone_idx; - if (bone_idx > 0 && bone_idx < stack->skeleton->get_bone_count()) { - jiggle_data_chain[i].dynamic_position = stack->skeleton->local_pose_to_global_pose(bone_idx, stack->skeleton->get_bone_local_pose_override(bone_idx)).origin; - } - } - } - - update_cache(); - } -} - -void SkeletonModification3DJiggle::update_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DJiggle::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache(); -} - -NodePath SkeletonModification3DJiggle::get_target_node() const { - return target_node; -} - -void SkeletonModification3DJiggle::set_stiffness(real_t p_stiffness) { - ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!"); - stiffness = p_stiffness; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_stiffness() const { - return stiffness; -} - -void SkeletonModification3DJiggle::set_mass(real_t p_mass) { - ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!"); - mass = p_mass; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_mass() const { - return mass; -} - -void SkeletonModification3DJiggle::set_damping(real_t p_damping) { - ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!"); - ERR_FAIL_COND_MSG(p_damping > 1, "Damping cannot be more than one!"); - damping = p_damping; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_damping() const { - return damping; -} - -void SkeletonModification3DJiggle::set_use_gravity(bool p_use_gravity) { - use_gravity = p_use_gravity; - _update_jiggle_joint_data(); -} - -bool SkeletonModification3DJiggle::get_use_gravity() const { - return use_gravity; -} - -void SkeletonModification3DJiggle::set_gravity(Vector3 p_gravity) { - gravity = p_gravity; - _update_jiggle_joint_data(); -} - -Vector3 SkeletonModification3DJiggle::get_gravity() const { - return gravity; -} - -void SkeletonModification3DJiggle::set_use_colliders(bool p_use_collider) { - use_colliders = p_use_collider; - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_use_colliders() const { - return use_colliders; -} - -void SkeletonModification3DJiggle::set_collision_mask(int p_mask) { - collision_mask = p_mask; -} - -int SkeletonModification3DJiggle::get_collision_mask() const { - return collision_mask; -} - -// Jiggle joint data functions -int SkeletonModification3DJiggle::get_jiggle_data_chain_length() { - return jiggle_data_chain.size(); -} - -void SkeletonModification3DJiggle::set_jiggle_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - jiggle_data_chain.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DJiggle::set_jiggle_joint_bone_name(int p_joint_idx, String p_name) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - - jiggle_data_chain[p_joint_idx].bone_name = p_name; - if (stack && stack->skeleton) { - jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DJiggle::get_jiggle_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, ""); - return jiggle_data_chain[p_joint_idx].bone_name; -} - -int SkeletonModification3DJiggle::get_jiggle_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - jiggle_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - jiggle_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DJiggle::set_jiggle_joint_override(int p_joint_idx, bool p_override) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].override_defaults = p_override; - _update_jiggle_joint_data(); - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_jiggle_joint_override(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return jiggle_data_chain[p_joint_idx].override_defaults; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].stiffness = p_stiffness; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_stiffness(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].stiffness; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_mass(int p_joint_idx, real_t p_mass) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].mass = p_mass; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_mass(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].mass; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_damping(int p_joint_idx, real_t p_damping) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].damping = p_damping; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_damping(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].damping; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].use_gravity = p_use_gravity; - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_jiggle_joint_use_gravity(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return jiggle_data_chain[p_joint_idx].use_gravity; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].gravity = p_gravity; -} - -Vector3 SkeletonModification3DJiggle::get_jiggle_joint_gravity(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3(0, 0, 0)); - return jiggle_data_chain[p_joint_idx].gravity; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_roll(int p_joint_idx, real_t p_roll) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].roll = p_roll; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_roll(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0); - return jiggle_data_chain[p_joint_idx].roll; -} - -void SkeletonModification3DJiggle::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DJiggle::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DJiggle::get_target_node); - - ClassDB::bind_method(D_METHOD("set_jiggle_data_chain_length", "length"), &SkeletonModification3DJiggle::set_jiggle_data_chain_length); - ClassDB::bind_method(D_METHOD("get_jiggle_data_chain_length"), &SkeletonModification3DJiggle::get_jiggle_data_chain_length); - - ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &SkeletonModification3DJiggle::set_stiffness); - ClassDB::bind_method(D_METHOD("get_stiffness"), &SkeletonModification3DJiggle::get_stiffness); - ClassDB::bind_method(D_METHOD("set_mass", "mass"), &SkeletonModification3DJiggle::set_mass); - ClassDB::bind_method(D_METHOD("get_mass"), &SkeletonModification3DJiggle::get_mass); - ClassDB::bind_method(D_METHOD("set_damping", "damping"), &SkeletonModification3DJiggle::set_damping); - ClassDB::bind_method(D_METHOD("get_damping"), &SkeletonModification3DJiggle::get_damping); - ClassDB::bind_method(D_METHOD("set_use_gravity", "use_gravity"), &SkeletonModification3DJiggle::set_use_gravity); - ClassDB::bind_method(D_METHOD("get_use_gravity"), &SkeletonModification3DJiggle::get_use_gravity); - ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &SkeletonModification3DJiggle::set_gravity); - ClassDB::bind_method(D_METHOD("get_gravity"), &SkeletonModification3DJiggle::get_gravity); - - ClassDB::bind_method(D_METHOD("set_use_colliders", "use_colliders"), &SkeletonModification3DJiggle::set_use_colliders); - ClassDB::bind_method(D_METHOD("get_use_colliders"), &SkeletonModification3DJiggle::get_use_colliders); - ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &SkeletonModification3DJiggle::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"), &SkeletonModification3DJiggle::get_collision_mask); - - // Jiggle joint data functions - ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_name", "joint_idx", "name"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_name", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_index", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_override", "joint_idx", "override"), &SkeletonModification3DJiggle::set_jiggle_joint_override); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_override", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_override); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_stiffness", "joint_idx", "stiffness"), &SkeletonModification3DJiggle::set_jiggle_joint_stiffness); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_stiffness", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_stiffness); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_mass", "joint_idx", "mass"), &SkeletonModification3DJiggle::set_jiggle_joint_mass); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_mass", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_mass); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_damping", "joint_idx", "damping"), &SkeletonModification3DJiggle::set_jiggle_joint_damping); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_damping", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_damping); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_use_gravity", "joint_idx", "use_gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_use_gravity); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_use_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_use_gravity); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_gravity", "joint_idx", "gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_gravity); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_gravity); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_roll", "joint_idx", "roll"), &SkeletonModification3DJiggle::set_jiggle_joint_roll); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_roll", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_roll); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "jiggle_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_jiggle_data_chain_length", "get_jiggle_data_chain_length"); - ADD_GROUP("Default Joint Settings", ""); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "stiffness"), "set_stiffness", "get_stiffness"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass"), "set_mass", "get_mass"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01"), "set_damping", "get_damping"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_gravity"), "set_use_gravity", "get_use_gravity"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity"), "set_gravity", "get_gravity"); - ADD_GROUP("", ""); -} - -SkeletonModification3DJiggle::SkeletonModification3DJiggle() { - stack = nullptr; - is_setup = false; - jiggle_data_chain = Vector<Jiggle_Joint_Data>(); - stiffness = 3; - mass = 0.75; - damping = 0.75; - use_gravity = false; - gravity = Vector3(0, -6.0, 0); - enabled = true; -} - -SkeletonModification3DJiggle::~SkeletonModification3DJiggle() { -} diff --git a/scene/resources/skeleton_modification_3d_jiggle.h b/scene/resources/skeleton_modification_3d_jiggle.h deleted file mode 100644 index cca620a72d..0000000000 --- a/scene/resources/skeleton_modification_3d_jiggle.h +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_jiggle.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_JIGGLE_H -#define SKELETON_MODIFICATION_3D_JIGGLE_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DJiggle : public SkeletonModification3D { - GDCLASS(SkeletonModification3DJiggle, SkeletonModification3D); - -private: - struct Jiggle_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - - bool override_defaults = false; - real_t stiffness = 3; - real_t mass = 0.75; - real_t damping = 0.75; - bool use_gravity = false; - Vector3 gravity = Vector3(0, -6.0, 0); - real_t roll = 0; - - Vector3 cached_rotation = Vector3(0, 0, 0); - Vector3 force = Vector3(0, 0, 0); - Vector3 acceleration = Vector3(0, 0, 0); - Vector3 velocity = Vector3(0, 0, 0); - Vector3 last_position = Vector3(0, 0, 0); - Vector3 dynamic_position = Vector3(0, 0, 0); - - Vector3 last_noncollision_position = Vector3(0, 0, 0); - }; - - NodePath target_node; - ObjectID target_node_cache; - LocalVector<Jiggle_Joint_Data> jiggle_data_chain; - - real_t stiffness = 3; - real_t mass = 0.75; - real_t damping = 0.75; - bool use_gravity = false; - Vector3 gravity = Vector3(0, -6.0, 0); - - bool use_colliders = false; - uint32_t collision_mask = 1; - - void update_cache(); - void _execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta); - void _update_jiggle_joint_data(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_stiffness(real_t p_stiffness); - real_t get_stiffness() const; - void set_mass(real_t p_mass); - real_t get_mass() const; - void set_damping(real_t p_damping); - real_t get_damping() const; - - void set_use_gravity(bool p_use_gravity); - bool get_use_gravity() const; - void set_gravity(Vector3 p_gravity); - Vector3 get_gravity() const; - - void set_use_colliders(bool p_use_colliders); - bool get_use_colliders() const; - void set_collision_mask(int p_mask); - int get_collision_mask() const; - - int get_jiggle_data_chain_length(); - void set_jiggle_data_chain_length(int p_new_length); - - void set_jiggle_joint_bone_name(int p_joint_idx, String p_name); - String get_jiggle_joint_bone_name(int p_joint_idx) const; - void set_jiggle_joint_bone_index(int p_joint_idx, int p_idx); - int get_jiggle_joint_bone_index(int p_joint_idx) const; - - void set_jiggle_joint_override(int p_joint_idx, bool p_override); - bool get_jiggle_joint_override(int p_joint_idx) const; - void set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness); - real_t get_jiggle_joint_stiffness(int p_joint_idx) const; - void set_jiggle_joint_mass(int p_joint_idx, real_t p_mass); - real_t get_jiggle_joint_mass(int p_joint_idx) const; - void set_jiggle_joint_damping(int p_joint_idx, real_t p_damping); - real_t get_jiggle_joint_damping(int p_joint_idx) const; - void set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity); - bool get_jiggle_joint_use_gravity(int p_joint_idx) const; - void set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity); - Vector3 get_jiggle_joint_gravity(int p_joint_idx) const; - void set_jiggle_joint_roll(int p_joint_idx, real_t p_roll); - real_t get_jiggle_joint_roll(int p_joint_idx) const; - - SkeletonModification3DJiggle(); - ~SkeletonModification3DJiggle(); -}; - -#endif // SKELETON_MODIFICATION_3D_JIGGLE_H diff --git a/scene/resources/skeleton_modification_3d_lookat.cpp b/scene/resources/skeleton_modification_3d_lookat.cpp deleted file mode 100644 index 57eedeb64e..0000000000 --- a/scene/resources/skeleton_modification_3d_lookat.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_lookat.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_lookat.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DLookAt::_set(const StringName &p_path, const Variant &p_value) { - if (p_path == "lock_rotation_to_plane") { - set_lock_rotation_to_plane(p_value); - } else if (p_path == "lock_rotation_plane") { - set_lock_rotation_plane(p_value); - } else if (p_path == "additional_rotation") { - Vector3 tmp = p_value; - tmp.x = Math::deg_to_rad(tmp.x); - tmp.y = Math::deg_to_rad(tmp.y); - tmp.z = Math::deg_to_rad(tmp.z); - set_additional_rotation(tmp); - } - - return true; -} - -bool SkeletonModification3DLookAt::_get(const StringName &p_path, Variant &r_ret) const { - if (p_path == "lock_rotation_to_plane") { - r_ret = get_lock_rotation_to_plane(); - } else if (p_path == "lock_rotation_plane") { - r_ret = get_lock_rotation_plane(); - } else if (p_path == "additional_rotation") { - Vector3 tmp = get_additional_rotation(); - tmp.x = Math::rad_to_deg(tmp.x); - tmp.y = Math::rad_to_deg(tmp.y); - tmp.z = Math::rad_to_deg(tmp.z); - r_ret = tmp; - } - - return true; -} - -void SkeletonModification3DLookAt::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "lock_rotation_to_plane", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (lock_rotation_to_plane) { - p_list->push_back(PropertyInfo(Variant::INT, "lock_rotation_plane", PROPERTY_HINT_ENUM, "X plane,Y plane,Z plane", PROPERTY_USAGE_DEFAULT)); - } - p_list->push_back(PropertyInfo(Variant::VECTOR3, "additional_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); -} - -void SkeletonModification3DLookAt::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache(); - return; - } - - if (bone_idx <= -2) { - bone_idx = stack->skeleton->find_bone(bone_name); - } - - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - if (_print_execution_error(bone_idx <= -1, "Bone index is invalid. Cannot execute modification!")) { - return; - } - Transform3D new_bone_trans = stack->skeleton->get_bone_local_pose_override(bone_idx); - if (new_bone_trans == Transform3D()) { - new_bone_trans = stack->skeleton->get_bone_pose(bone_idx); - } - Vector3 target_pos = stack->skeleton->global_pose_to_local_pose(bone_idx, stack->skeleton->world_transform_to_global_pose(target->get_global_transform())).origin; - - // Lock the rotation to a plane relative to the bone by changing the target position - if (lock_rotation_to_plane) { - if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_X) { - target_pos.x = new_bone_trans.origin.x; - } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Y) { - target_pos.y = new_bone_trans.origin.y; - } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Z) { - target_pos.z = new_bone_trans.origin.z; - } - } - - // Look at the target! - new_bone_trans = new_bone_trans.looking_at(target_pos, Vector3(0, 1, 0)); - // Convert from Z-forward to whatever direction the bone faces. - stack->skeleton->update_bone_rest_forward_vector(bone_idx); - new_bone_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(bone_idx, new_bone_trans.basis); - - // Apply additional rotation - new_bone_trans.basis.rotate_local(Vector3(1, 0, 0), additional_rotation.x); - new_bone_trans.basis.rotate_local(Vector3(0, 1, 0), additional_rotation.y); - new_bone_trans.basis.rotate_local(Vector3(0, 0, 1), additional_rotation.z); - - stack->skeleton->set_bone_local_pose_override(bone_idx, new_bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(bone_idx); - - // If we completed it successfully, then we can set execution_error_found to false - execution_error_found = false; -} - -void SkeletonModification3DLookAt::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_cache(); - } -} - -void SkeletonModification3DLookAt::set_bone_name(String p_name) { - bone_name = p_name; - if (stack) { - if (stack->skeleton) { - bone_idx = stack->skeleton->find_bone(bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DLookAt::get_bone_name() const { - return bone_name; -} - -int SkeletonModification3DLookAt::get_bone_index() const { - return bone_idx; -} - -void SkeletonModification3DLookAt::set_bone_index(int p_bone_idx) { - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DLookAt::update_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: Node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: Node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DLookAt::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache(); -} - -NodePath SkeletonModification3DLookAt::get_target_node() const { - return target_node; -} - -Vector3 SkeletonModification3DLookAt::get_additional_rotation() const { - return additional_rotation; -} - -void SkeletonModification3DLookAt::set_additional_rotation(Vector3 p_offset) { - additional_rotation = p_offset; -} - -bool SkeletonModification3DLookAt::get_lock_rotation_to_plane() const { - return lock_rotation_plane; -} - -void SkeletonModification3DLookAt::set_lock_rotation_to_plane(bool p_lock_rotation) { - lock_rotation_to_plane = p_lock_rotation; - notify_property_list_changed(); -} - -int SkeletonModification3DLookAt::get_lock_rotation_plane() const { - return lock_rotation_plane; -} - -void SkeletonModification3DLookAt::set_lock_rotation_plane(int p_plane) { - lock_rotation_plane = p_plane; -} - -void SkeletonModification3DLookAt::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_bone_name", "name"), &SkeletonModification3DLookAt::set_bone_name); - ClassDB::bind_method(D_METHOD("get_bone_name"), &SkeletonModification3DLookAt::get_bone_name); - - ClassDB::bind_method(D_METHOD("set_bone_index", "bone_idx"), &SkeletonModification3DLookAt::set_bone_index); - ClassDB::bind_method(D_METHOD("get_bone_index"), &SkeletonModification3DLookAt::get_bone_index); - - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DLookAt::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DLookAt::get_target_node); - - ClassDB::bind_method(D_METHOD("set_additional_rotation", "additional_rotation"), &SkeletonModification3DLookAt::set_additional_rotation); - ClassDB::bind_method(D_METHOD("get_additional_rotation"), &SkeletonModification3DLookAt::get_additional_rotation); - - ClassDB::bind_method(D_METHOD("set_lock_rotation_to_plane", "lock_to_plane"), &SkeletonModification3DLookAt::set_lock_rotation_to_plane); - ClassDB::bind_method(D_METHOD("get_lock_rotation_to_plane"), &SkeletonModification3DLookAt::get_lock_rotation_to_plane); - ClassDB::bind_method(D_METHOD("set_lock_rotation_plane", "plane"), &SkeletonModification3DLookAt::set_lock_rotation_plane); - ClassDB::bind_method(D_METHOD("get_lock_rotation_plane"), &SkeletonModification3DLookAt::get_lock_rotation_plane); - - ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bone_name"), "set_bone_name", "get_bone_name"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_index"), "set_bone_index", "get_bone_index"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); -} - -SkeletonModification3DLookAt::SkeletonModification3DLookAt() { - stack = nullptr; - is_setup = false; - bone_name = ""; - bone_idx = -2; - additional_rotation = Vector3(); - lock_rotation_to_plane = false; - enabled = true; -} - -SkeletonModification3DLookAt::~SkeletonModification3DLookAt() { -} diff --git a/scene/resources/skeleton_modification_3d_lookat.h b/scene/resources/skeleton_modification_3d_lookat.h deleted file mode 100644 index 9a25ac530d..0000000000 --- a/scene/resources/skeleton_modification_3d_lookat.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_lookat.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_LOOKAT_H -#define SKELETON_MODIFICATION_3D_LOOKAT_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DLookAt : public SkeletonModification3D { - GDCLASS(SkeletonModification3DLookAt, SkeletonModification3D); - -private: - String bone_name = ""; - int bone_idx = -1; - NodePath target_node; - ObjectID target_node_cache; - - Vector3 additional_rotation = Vector3(1, 0, 0); - bool lock_rotation_to_plane = false; - int lock_rotation_plane = ROTATION_PLANE_X; - - void update_cache(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - enum ROTATION_PLANE { - ROTATION_PLANE_X, - ROTATION_PLANE_Y, - ROTATION_PLANE_Z - }; - - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_bone_name(String p_name); - String get_bone_name() const; - - void set_bone_index(int p_idx); - int get_bone_index() const; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_additional_rotation(Vector3 p_offset); - Vector3 get_additional_rotation() const; - - void set_lock_rotation_to_plane(bool p_lock_to_plane); - bool get_lock_rotation_to_plane() const; - void set_lock_rotation_plane(int p_plane); - int get_lock_rotation_plane() const; - - SkeletonModification3DLookAt(); - ~SkeletonModification3DLookAt(); -}; - -#endif // SKELETON_MODIFICATION_3D_LOOKAT_H diff --git a/scene/resources/skeleton_modification_3d_stackholder.cpp b/scene/resources/skeleton_modification_3d_stackholder.cpp deleted file mode 100644 index 1598badb30..0000000000 --- a/scene/resources/skeleton_modification_3d_stackholder.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_stackholder.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_stackholder.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DStackHolder::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path == "held_modification_stack") { - set_held_modification_stack(p_value); - } - return true; -} - -bool SkeletonModification3DStackHolder::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path == "held_modification_stack") { - r_ret = get_held_modification_stack(); - } - return true; -} - -void SkeletonModification3DStackHolder::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack3D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); -} - -void SkeletonModification3DStackHolder::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - - if (held_modification_stack.is_valid()) { - held_modification_stack->execute(p_delta, execution_mode); - } -} - -void SkeletonModification3DStackHolder::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - - if (held_modification_stack.is_valid()) { - held_modification_stack->set_skeleton(stack->get_skeleton()); - held_modification_stack->setup(); - } - } -} - -void SkeletonModification3DStackHolder::set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack) { - held_modification_stack = p_held_stack; - - if (is_setup && held_modification_stack.is_valid()) { - held_modification_stack->set_skeleton(stack->get_skeleton()); - held_modification_stack->setup(); - } -} - -Ref<SkeletonModificationStack3D> SkeletonModification3DStackHolder::get_held_modification_stack() const { - return held_modification_stack; -} - -void SkeletonModification3DStackHolder::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_held_modification_stack", "held_modification_stack"), &SkeletonModification3DStackHolder::set_held_modification_stack); - ClassDB::bind_method(D_METHOD("get_held_modification_stack"), &SkeletonModification3DStackHolder::get_held_modification_stack); -} - -SkeletonModification3DStackHolder::SkeletonModification3DStackHolder() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DStackHolder::~SkeletonModification3DStackHolder() { -} diff --git a/scene/resources/skeleton_modification_3d_stackholder.h b/scene/resources/skeleton_modification_3d_stackholder.h deleted file mode 100644 index da39044f97..0000000000 --- a/scene/resources/skeleton_modification_3d_stackholder.h +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_stackholder.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_STACKHOLDER_H -#define SKELETON_MODIFICATION_3D_STACKHOLDER_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DStackHolder : public SkeletonModification3D { - GDCLASS(SkeletonModification3DStackHolder, SkeletonModification3D); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - Ref<SkeletonModificationStack3D> held_modification_stack; - - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack); - Ref<SkeletonModificationStack3D> get_held_modification_stack() const; - - SkeletonModification3DStackHolder(); - ~SkeletonModification3DStackHolder(); -}; - -#endif // SKELETON_MODIFICATION_3D_STACKHOLDER_H diff --git a/scene/resources/skeleton_modification_3d_twoboneik.cpp b/scene/resources/skeleton_modification_3d_twoboneik.cpp deleted file mode 100644 index 7d5b4d2b55..0000000000 --- a/scene/resources/skeleton_modification_3d_twoboneik.cpp +++ /dev/null @@ -1,617 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_twoboneik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "scene/resources/skeleton_modification_3d_twoboneik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DTwoBoneIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path == "use_tip_node") { - set_use_tip_node(p_value); - } else if (path == "tip_node") { - set_tip_node(p_value); - } else if (path == "auto_calculate_joint_length") { - set_auto_calculate_joint_length(p_value); - } else if (path == "use_pole_node") { - set_use_pole_node(p_value); - } else if (path == "pole_node") { - set_pole_node(p_value); - } else if (path == "joint_one_length") { - set_joint_one_length(p_value); - } else if (path == "joint_two_length") { - set_joint_two_length(p_value); - } else if (path == "joint_one/bone_name") { - set_joint_one_bone_name(p_value); - } else if (path == "joint_one/bone_idx") { - set_joint_one_bone_idx(p_value); - } else if (path == "joint_one/roll") { - set_joint_one_roll(Math::deg_to_rad(real_t(p_value))); - } else if (path == "joint_two/bone_name") { - set_joint_two_bone_name(p_value); - } else if (path == "joint_two/bone_idx") { - set_joint_two_bone_idx(p_value); - } else if (path == "joint_two/roll") { - set_joint_two_roll(Math::deg_to_rad(real_t(p_value))); - } - - return true; -} - -bool SkeletonModification3DTwoBoneIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path == "use_tip_node") { - r_ret = get_use_tip_node(); - } else if (path == "tip_node") { - r_ret = get_tip_node(); - } else if (path == "auto_calculate_joint_length") { - r_ret = get_auto_calculate_joint_length(); - } else if (path == "use_pole_node") { - r_ret = get_use_pole_node(); - } else if (path == "pole_node") { - r_ret = get_pole_node(); - } else if (path == "joint_one_length") { - r_ret = get_joint_one_length(); - } else if (path == "joint_two_length") { - r_ret = get_joint_two_length(); - } else if (path == "joint_one/bone_name") { - r_ret = get_joint_one_bone_name(); - } else if (path == "joint_one/bone_idx") { - r_ret = get_joint_one_bone_idx(); - } else if (path == "joint_one/roll") { - r_ret = Math::rad_to_deg(get_joint_one_roll()); - } else if (path == "joint_two/bone_name") { - r_ret = get_joint_two_bone_name(); - } else if (path == "joint_two/bone_idx") { - r_ret = get_joint_two_bone_idx(); - } else if (path == "joint_two/roll") { - r_ret = Math::rad_to_deg(get_joint_two_roll()); - } - - return true; -} - -void SkeletonModification3DTwoBoneIK::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_tip_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::BOOL, "auto_calculate_joint_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (!auto_calculate_joint_length) { - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::BOOL, "use_pole_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_pole_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, "pole_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_one/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, "joint_one/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_two/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, "joint_two/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT)); -} - -void SkeletonModification3DTwoBoneIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - - if (!enabled) { - return; - } - - if (_print_execution_error(joint_one_bone_idx < 0 || joint_two_bone_idx < 0, - "One (or more) of the bones in the modification have invalid bone indexes. Cannot execute modification!")) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache_target(); - return; - } - - // Update joint lengths (if needed) - if (auto_calculate_joint_length && (joint_one_length < 0 || joint_two_length < 0)) { - calculate_joint_lengths(); - } - - // Adopted from the links below: - // http://theorangeduck.com/page/simple-two-joint - // https://www.alanzucconi.com/2018/05/02/ik-2d-2/ - // With modifications by TwistedTwigleg - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - Transform3D target_trans = stack->skeleton->world_transform_to_global_pose(target->get_global_transform()); - - Transform3D bone_one_trans; - Transform3D bone_two_trans; - - // Make the first joint look at the pole, and the second look at the target. That way, the - // TwoBoneIK solver has to really only handle extension/contraction, which should make it align with the pole. - if (use_pole_node) { - if (pole_node_cache.is_null()) { - _print_execution_error(true, "Pole cache is out of date. Attempting to update..."); - update_cache_pole(); - return; - } - - Node3D *pole = Object::cast_to<Node3D>(ObjectDB::get_instance(pole_node_cache)); - if (_print_execution_error(!pole || !pole->is_inside_tree(), "Pole node is not in the scene tree. Cannot execute modification!")) { - return; - } - Transform3D pole_trans = stack->skeleton->world_transform_to_global_pose(pole->get_global_transform()); - - Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx); - if (bone_one_local_pos == Transform3D()) { - bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx); - } - Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx); - if (bone_two_local_pos == Transform3D()) { - bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx); - } - - bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos); - bone_one_trans = bone_one_trans.looking_at(pole_trans.origin, Vector3(0, 1, 0)); - bone_one_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_one_bone_idx, bone_one_trans.basis); - stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx); - bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll); - stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans), stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx); - - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos); - bone_two_trans = bone_two_trans.looking_at(target_trans.origin, Vector3(0, 1, 0)); - bone_two_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_two_bone_idx, bone_two_trans.basis); - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans), stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } else { - Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx); - if (bone_one_local_pos == Transform3D()) { - bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx); - } - Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx); - if (bone_two_local_pos == Transform3D()) { - bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx); - } - - bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos); - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos); - } - - Transform3D bone_two_tip_trans; - if (use_tip_node) { - if (tip_node_cache.is_null()) { - _print_execution_error(true, "Tip cache is out of date. Attempting to update..."); - update_cache_tip(); - return; - } - Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - if (_print_execution_error(!tip || !tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) { - return; - } - bone_two_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform()); - } else { - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_tip_trans = bone_two_trans; - bone_two_tip_trans.origin += bone_two_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx)).normalized() * joint_two_length; - } - - real_t joint_one_to_target_length = bone_one_trans.origin.distance_to(target_trans.origin); - if (joint_one_length + joint_two_length < joint_one_to_target_length) { - // Set the target *just* out of reach to straighten the bones - joint_one_to_target_length = joint_one_length + joint_two_length + 0.01; - } else if (joint_one_to_target_length < joint_one_length) { - // Place the target in reach so the solver doesn't do crazy things - joint_one_to_target_length = joint_one_length; - } - - // Get the square lengths for all three sides of the triangle we'll use to calculate the angles - real_t sqr_one_length = joint_one_length * joint_one_length; - real_t sqr_two_length = joint_two_length * joint_two_length; - real_t sqr_three_length = joint_one_to_target_length * joint_one_to_target_length; - - // Calculate the angles for the first joint using the law of cosigns - real_t ac_ab_0 = Math::acos(CLAMP(bone_two_tip_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_one_trans.origin)), -1, 1)); - real_t ac_at_0 = Math::acos(CLAMP(bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).dot(bone_one_trans.origin.direction_to(target_trans.origin)), -1, 1)); - real_t ac_ab_1 = Math::acos(CLAMP((sqr_two_length - sqr_one_length - sqr_three_length) / (-2.0 * joint_one_length * joint_one_to_target_length), -1, 1)); - - // Calculate the angles of rotation. Angle 0 is the extension/contraction axis, while angle 1 is the rotation axis to align the triangle to the target - Vector3 axis_0 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(bone_two_trans.origin)); - Vector3 axis_1 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(target_trans.origin)); - - // Make a quaternion with the delta rotation needed to rotate the first joint into alignment and apply it to the transform. - Quaternion bone_one_quat = bone_one_trans.basis.get_rotation_quaternion(); - Quaternion rot_0 = Quaternion(bone_one_quat.inverse().xform(axis_0).normalized(), (ac_ab_1 - ac_ab_0)); - Quaternion rot_2 = Quaternion(bone_one_quat.inverse().xform(axis_1).normalized(), ac_at_0); - bone_one_trans.basis.set_quaternion(bone_one_quat * (rot_0 * rot_2)); - - stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx); - bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll); - - // Apply the rotation to the first joint - bone_one_trans = stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans); - bone_one_trans.origin = Vector3(0, 0, 0); - stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, bone_one_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx); - - if (use_pole_node) { - // Update bone_two_trans so its at the latest position, with the rotation of bone_one_trans taken into account, then look at the target. - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx)); - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_to_align(forward_vector, bone_two_trans.origin.direction_to(target_trans.origin)); - - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - - bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } else { - // Calculate the angles for the second joint using the law of cosigns, make a quaternion with the delta rotation needed to rotate the joint into - // alignment, and then apply it to the second joint. - real_t ba_bc_0 = Math::acos(CLAMP(bone_two_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_two_tip_trans.origin)), -1, 1)); - real_t ba_bc_1 = Math::acos(CLAMP((sqr_three_length - sqr_one_length - sqr_two_length) / (-2.0 * joint_one_length * joint_two_length), -1, 1)); - Quaternion bone_two_quat = bone_two_trans.basis.get_rotation_quaternion(); - Quaternion rot_1 = Quaternion(bone_two_quat.inverse().xform(axis_0).normalized(), (ba_bc_1 - ba_bc_0)); - bone_two_trans.basis.set_quaternion(bone_two_quat * rot_1); - - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - - bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans); - bone_two_trans.origin = Vector3(0, 0, 0); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } -} - -void SkeletonModification3DTwoBoneIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_cache_target(); - update_cache_tip(); - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_target() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: Target node is this modification's skeleton or cannot be found. Cannot execute modification"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: Target node is not in the scene tree. Cannot execute modification!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_tip() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - - tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(tip_node)) { - Node *node = stack->skeleton->get_node(tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache: Tip node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache: Tip node is not in the scene tree. Cannot execute modification!"); - tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_pole() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update pole cache: modification is not properly setup!"); - return; - } - - pole_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(pole_node)) { - Node *node = stack->skeleton->get_node(pole_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update pole cache: Pole node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update pole cache: Pole node is not in the scene tree. Cannot execute modification!"); - pole_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache_target(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_target_node() const { - return target_node; -} - -void SkeletonModification3DTwoBoneIK::set_use_tip_node(const bool p_use_tip_node) { - use_tip_node = p_use_tip_node; - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_use_tip_node() const { - return use_tip_node; -} - -void SkeletonModification3DTwoBoneIK::set_tip_node(const NodePath &p_tip_node) { - tip_node = p_tip_node; - update_cache_tip(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_tip_node() const { - return tip_node; -} - -void SkeletonModification3DTwoBoneIK::set_use_pole_node(const bool p_use_pole_node) { - use_pole_node = p_use_pole_node; - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_use_pole_node() const { - return use_pole_node; -} - -void SkeletonModification3DTwoBoneIK::set_pole_node(const NodePath &p_pole_node) { - pole_node = p_pole_node; - update_cache_pole(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_pole_node() const { - return pole_node; -} - -void SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length(bool p_calculate) { - auto_calculate_joint_length = p_calculate; - if (p_calculate) { - calculate_joint_lengths(); - } - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length() const { - return auto_calculate_joint_length; -} - -void SkeletonModification3DTwoBoneIK::calculate_joint_lengths() { - if (!is_setup) { - return; // fail silently, as we likely just loaded the scene. - } - ERR_FAIL_COND_MSG(!stack || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot calculate joint lengths!"); - ERR_FAIL_COND_MSG(joint_one_bone_idx <= -1 || joint_two_bone_idx <= -1, - "One of the bones in the TwoBoneIK modification are not set! Cannot calculate joint lengths!"); - - Transform3D bone_one_rest_trans = stack->skeleton->get_bone_global_pose(joint_one_bone_idx); - Transform3D bone_two_rest_trans = stack->skeleton->get_bone_global_pose(joint_two_bone_idx); - - joint_one_length = bone_one_rest_trans.origin.distance_to(bone_two_rest_trans.origin); - - if (use_tip_node) { - if (tip_node_cache.is_null()) { - update_cache_tip(); - WARN_PRINT("Tip cache is out of date. Updating..."); - } - - Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - if (tip) { - Transform3D bone_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform()); - joint_two_length = bone_two_rest_trans.origin.distance_to(bone_tip_trans.origin); - } - } else { - // Attempt to use children bones to get the length - Vector<int> bone_two_children = stack->skeleton->get_bone_children(joint_two_bone_idx); - if (bone_two_children.size() > 0) { - joint_two_length = 0; - for (int i = 0; i < bone_two_children.size(); i++) { - joint_two_length += bone_two_rest_trans.origin.distance_to( - stack->skeleton->get_bone_global_pose(bone_two_children[i]).origin); - } - joint_two_length = joint_two_length / bone_two_children.size(); - } else { - WARN_PRINT("TwoBoneIK modification: Cannot auto calculate length for joint 2! Auto setting the length to 1..."); - joint_two_length = 1.0; - } - } - execution_error_found = false; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_bone_name(String p_bone_name) { - joint_one_bone_name = p_bone_name; - if (stack && stack->skeleton) { - joint_one_bone_idx = stack->skeleton->find_bone(p_bone_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DTwoBoneIK::get_joint_one_bone_name() const { - return joint_one_bone_name; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx(int p_bone_idx) { - joint_one_bone_idx = p_bone_idx; - if (stack && stack->skeleton) { - joint_one_bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx() const { - return joint_one_bone_idx; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_length(real_t p_length) { - joint_one_length = p_length; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_one_length() const { - return joint_one_length; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_bone_name(String p_bone_name) { - joint_two_bone_name = p_bone_name; - if (stack && stack->skeleton) { - joint_two_bone_idx = stack->skeleton->find_bone(p_bone_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DTwoBoneIK::get_joint_two_bone_name() const { - return joint_two_bone_name; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx(int p_bone_idx) { - joint_two_bone_idx = p_bone_idx; - if (stack && stack->skeleton) { - joint_two_bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx() const { - return joint_two_bone_idx; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_length(real_t p_length) { - joint_two_length = p_length; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_two_length() const { - return joint_two_length; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_roll(real_t p_roll) { - joint_one_roll = p_roll; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_one_roll() const { - return joint_one_roll; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_roll(real_t p_roll) { - joint_two_roll = p_roll; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_two_roll() const { - return joint_two_roll; -} - -void SkeletonModification3DTwoBoneIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DTwoBoneIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DTwoBoneIK::get_target_node); - - ClassDB::bind_method(D_METHOD("set_use_pole_node", "use_pole_node"), &SkeletonModification3DTwoBoneIK::set_use_pole_node); - ClassDB::bind_method(D_METHOD("get_use_pole_node"), &SkeletonModification3DTwoBoneIK::get_use_pole_node); - ClassDB::bind_method(D_METHOD("set_pole_node", "pole_nodepath"), &SkeletonModification3DTwoBoneIK::set_pole_node); - ClassDB::bind_method(D_METHOD("get_pole_node"), &SkeletonModification3DTwoBoneIK::get_pole_node); - - ClassDB::bind_method(D_METHOD("set_use_tip_node", "use_tip_node"), &SkeletonModification3DTwoBoneIK::set_use_tip_node); - ClassDB::bind_method(D_METHOD("get_use_tip_node"), &SkeletonModification3DTwoBoneIK::get_use_tip_node); - ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DTwoBoneIK::set_tip_node); - ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DTwoBoneIK::get_tip_node); - - ClassDB::bind_method(D_METHOD("set_auto_calculate_joint_length", "auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length); - ClassDB::bind_method(D_METHOD("get_auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length); - - ClassDB::bind_method(D_METHOD("set_joint_one_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_name); - ClassDB::bind_method(D_METHOD("get_joint_one_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_name); - ClassDB::bind_method(D_METHOD("set_joint_one_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx); - ClassDB::bind_method(D_METHOD("get_joint_one_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx); - ClassDB::bind_method(D_METHOD("set_joint_one_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_one_length); - ClassDB::bind_method(D_METHOD("get_joint_one_length"), &SkeletonModification3DTwoBoneIK::get_joint_one_length); - - ClassDB::bind_method(D_METHOD("set_joint_two_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_name); - ClassDB::bind_method(D_METHOD("get_joint_two_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_name); - ClassDB::bind_method(D_METHOD("set_joint_two_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx); - ClassDB::bind_method(D_METHOD("get_joint_two_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx); - ClassDB::bind_method(D_METHOD("set_joint_two_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_two_length); - ClassDB::bind_method(D_METHOD("get_joint_two_length"), &SkeletonModification3DTwoBoneIK::get_joint_two_length); - - ClassDB::bind_method(D_METHOD("set_joint_one_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_one_roll); - ClassDB::bind_method(D_METHOD("get_joint_one_roll"), &SkeletonModification3DTwoBoneIK::get_joint_one_roll); - ClassDB::bind_method(D_METHOD("set_joint_two_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_two_roll); - ClassDB::bind_method(D_METHOD("get_joint_two_roll"), &SkeletonModification3DTwoBoneIK::get_joint_two_roll); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_GROUP("", ""); -} - -SkeletonModification3DTwoBoneIK::SkeletonModification3DTwoBoneIK() { - stack = nullptr; - is_setup = false; -} - -SkeletonModification3DTwoBoneIK::~SkeletonModification3DTwoBoneIK() { -} diff --git a/scene/resources/skeleton_modification_3d_twoboneik.h b/scene/resources/skeleton_modification_3d_twoboneik.h deleted file mode 100644 index 57481e0181..0000000000 --- a/scene/resources/skeleton_modification_3d_twoboneik.h +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_twoboneik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_3D_TWOBONEIK_H -#define SKELETON_MODIFICATION_3D_TWOBONEIK_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DTwoBoneIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DTwoBoneIK, SkeletonModification3D); - -private: - NodePath target_node; - ObjectID target_node_cache; - - bool use_tip_node = false; - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_pole_node = false; - NodePath pole_node; - ObjectID pole_node_cache; - - String joint_one_bone_name = ""; - int joint_one_bone_idx = -1; - String joint_two_bone_name = ""; - int joint_two_bone_idx = -1; - - bool auto_calculate_joint_length = false; - real_t joint_one_length = -1; - real_t joint_two_length = -1; - - real_t joint_one_roll = 0; - real_t joint_two_roll = 0; - - void update_cache_target(); - void update_cache_tip(); - void update_cache_pole(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_use_tip_node(const bool p_use_tip_node); - bool get_use_tip_node() const; - void set_tip_node(const NodePath &p_tip_node); - NodePath get_tip_node() const; - - void set_use_pole_node(const bool p_use_pole_node); - bool get_use_pole_node() const; - void set_pole_node(const NodePath &p_pole_node); - NodePath get_pole_node() const; - - void set_auto_calculate_joint_length(bool p_calculate); - bool get_auto_calculate_joint_length() const; - void calculate_joint_lengths(); - - void set_joint_one_bone_name(String p_bone_name); - String get_joint_one_bone_name() const; - void set_joint_one_bone_idx(int p_bone_idx); - int get_joint_one_bone_idx() const; - void set_joint_one_length(real_t p_length); - real_t get_joint_one_length() const; - - void set_joint_two_bone_name(String p_bone_name); - String get_joint_two_bone_name() const; - void set_joint_two_bone_idx(int p_bone_idx); - int get_joint_two_bone_idx() const; - void set_joint_two_length(real_t p_length); - real_t get_joint_two_length() const; - - void set_joint_one_roll(real_t p_roll); - real_t get_joint_one_roll() const; - void set_joint_two_roll(real_t p_roll); - real_t get_joint_two_roll() const; - - SkeletonModification3DTwoBoneIK(); - ~SkeletonModification3DTwoBoneIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_TWOBONEIK_H diff --git a/scene/resources/skeleton_modification_stack_3d.cpp b/scene/resources/skeleton_modification_stack_3d.cpp deleted file mode 100644 index 32708e198a..0000000000 --- a/scene/resources/skeleton_modification_stack_3d.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_stack_3d.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 "skeleton_modification_stack_3d.h" -#include "scene/3d/skeleton_3d.h" - -/////////////////////////////////////// -// ModificationStack3D -/////////////////////////////////////// - -void SkeletonModificationStack3D::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < modifications.size(); i++) { - p_list->push_back( - PropertyInfo(Variant::OBJECT, "modifications/" + itos(i), - PROPERTY_HINT_RESOURCE_TYPE, - "SkeletonModification3D", - PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); - } -} - -bool SkeletonModificationStack3D::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("modifications/")) { - int mod_idx = path.get_slicec('/', 1).to_int(); - set_modification(mod_idx, p_value); - return true; - } - return true; -} - -bool SkeletonModificationStack3D::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("modifications/")) { - int mod_idx = path.get_slicec('/', 1).to_int(); - r_ret = get_modification(mod_idx); - return true; - } - return true; -} - -void SkeletonModificationStack3D::setup() { - if (is_setup) { - return; - } - - if (skeleton != nullptr) { - is_setup = true; - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - modifications[i]->_setup_modification(this); - } - } else { - WARN_PRINT("Cannot setup SkeletonModificationStack3D: no skeleton set!"); - } -} - -void SkeletonModificationStack3D::execute(real_t p_delta, int p_execution_mode) { - ERR_FAIL_COND_MSG(!is_setup || skeleton == nullptr || is_queued_for_deletion(), - "Modification stack is not properly setup and therefore cannot execute!"); - - if (!skeleton->is_inside_tree()) { - ERR_PRINT_ONCE("Skeleton is not inside SceneTree! Cannot execute modification!"); - return; - } - - if (!enabled) { - return; - } - - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - - if (modifications[i]->get_execution_mode() == p_execution_mode) { - modifications[i]->_execute(p_delta); - } - } -} - -void SkeletonModificationStack3D::enable_all_modifications(bool p_enabled) { - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - modifications[i]->set_enabled(p_enabled); - } -} - -Ref<SkeletonModification3D> SkeletonModificationStack3D::get_modification(int p_mod_idx) const { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX_V(p_mod_idx, modifications_size, nullptr); - return modifications[p_mod_idx]; -} - -void SkeletonModificationStack3D::add_modification(Ref<SkeletonModification3D> p_mod) { - ERR_FAIL_NULL(p_mod); - p_mod->_setup_modification(this); - modifications.push_back(p_mod); -} - -void SkeletonModificationStack3D::delete_modification(int p_mod_idx) { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX(p_mod_idx, modifications_size); - modifications.remove_at(p_mod_idx); -} - -void SkeletonModificationStack3D::set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod) { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX(p_mod_idx, modifications_size); - - if (p_mod == nullptr) { - modifications.remove_at(p_mod_idx); - } else { - p_mod->_setup_modification(this); - modifications[p_mod_idx] = p_mod; - } -} - -void SkeletonModificationStack3D::set_modification_count(int p_count) { - ERR_FAIL_COND_MSG(p_count < 0, "Modification count cannot be less than zero."); - modifications.resize(p_count); - notify_property_list_changed(); -} - -int SkeletonModificationStack3D::get_modification_count() const { - return modifications.size(); -} - -void SkeletonModificationStack3D::set_skeleton(Skeleton3D *p_skeleton) { - skeleton = p_skeleton; -} - -Skeleton3D *SkeletonModificationStack3D::get_skeleton() const { - return skeleton; -} - -bool SkeletonModificationStack3D::get_is_setup() const { - return is_setup; -} - -void SkeletonModificationStack3D::set_enabled(bool p_enabled) { - enabled = p_enabled; - - if (!enabled && is_setup && skeleton != nullptr) { - skeleton->clear_bones_local_pose_override(); - } -} - -bool SkeletonModificationStack3D::get_enabled() const { - return enabled; -} - -void SkeletonModificationStack3D::set_strength(real_t p_strength) { - ERR_FAIL_COND_MSG(p_strength < 0, "Strength cannot be less than zero!"); - ERR_FAIL_COND_MSG(p_strength > 1, "Strength cannot be more than one!"); - strength = p_strength; -} - -real_t SkeletonModificationStack3D::get_strength() const { - return strength; -} - -void SkeletonModificationStack3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("setup"), &SkeletonModificationStack3D::setup); - ClassDB::bind_method(D_METHOD("execute", "delta", "execution_mode"), &SkeletonModificationStack3D::execute); - - ClassDB::bind_method(D_METHOD("enable_all_modifications", "enabled"), &SkeletonModificationStack3D::enable_all_modifications); - ClassDB::bind_method(D_METHOD("get_modification", "mod_idx"), &SkeletonModificationStack3D::get_modification); - ClassDB::bind_method(D_METHOD("add_modification", "modification"), &SkeletonModificationStack3D::add_modification); - ClassDB::bind_method(D_METHOD("delete_modification", "mod_idx"), &SkeletonModificationStack3D::delete_modification); - ClassDB::bind_method(D_METHOD("set_modification", "mod_idx", "modification"), &SkeletonModificationStack3D::set_modification); - - ClassDB::bind_method(D_METHOD("set_modification_count", "count"), &SkeletonModificationStack3D::set_modification_count); - ClassDB::bind_method(D_METHOD("get_modification_count"), &SkeletonModificationStack3D::get_modification_count); - - ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModificationStack3D::get_is_setup); - - ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModificationStack3D::set_enabled); - ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModificationStack3D::get_enabled); - - ClassDB::bind_method(D_METHOD("set_strength", "strength"), &SkeletonModificationStack3D::set_strength); - ClassDB::bind_method(D_METHOD("get_strength"), &SkeletonModificationStack3D::get_strength); - - ClassDB::bind_method(D_METHOD("get_skeleton"), &SkeletonModificationStack3D::get_skeleton); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "strength", PROPERTY_HINT_RANGE, "0, 1, 0.001"), "set_strength", "get_strength"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "modification_count", PROPERTY_HINT_RANGE, "0, 100, 1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ARRAY, "Modifications,modifications/"), "set_modification_count", "get_modification_count"); -} - -SkeletonModificationStack3D::SkeletonModificationStack3D() { -} diff --git a/scene/resources/skeleton_modification_stack_3d.h b/scene/resources/skeleton_modification_stack_3d.h deleted file mode 100644 index fd490c49e9..0000000000 --- a/scene/resources/skeleton_modification_stack_3d.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_stack_3d.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* 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 SKELETON_MODIFICATION_STACK_3D_H -#define SKELETON_MODIFICATION_STACK_3D_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" - -class Skeleton3D; -class SkeletonModification3D; - -class SkeletonModificationStack3D : public Resource { - GDCLASS(SkeletonModificationStack3D, Resource); - friend class Skeleton3D; - friend class SkeletonModification3D; - -protected: - static void _bind_methods(); - virtual void _get_property_list(List<PropertyInfo> *p_list) const; - virtual bool _set(const StringName &p_path, const Variant &p_value); - virtual bool _get(const StringName &p_path, Variant &r_ret) const; - -public: - Skeleton3D *skeleton = nullptr; - bool is_setup = false; - bool enabled = false; - real_t strength = 1.0; - - enum EXECUTION_MODE { - execution_mode_process, - execution_mode_physics_process, - }; - - LocalVector<Ref<SkeletonModification3D>> modifications = LocalVector<Ref<SkeletonModification3D>>(); - int modifications_count = 0; - - virtual void setup(); - virtual void execute(real_t p_delta, int p_execution_mode); - - void enable_all_modifications(bool p_enable); - Ref<SkeletonModification3D> get_modification(int p_mod_idx) const; - void add_modification(Ref<SkeletonModification3D> p_mod); - void delete_modification(int p_mod_idx); - void set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod); - - void set_modification_count(int p_count); - int get_modification_count() const; - - void set_skeleton(Skeleton3D *p_skeleton); - Skeleton3D *get_skeleton() const; - - bool get_is_setup() const; - - void set_enabled(bool p_enabled); - bool get_enabled() const; - - void set_strength(real_t p_strength); - real_t get_strength() const; - - SkeletonModificationStack3D(); -}; - -#endif // SKELETON_MODIFICATION_STACK_3D_H diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp index 0008250f8f..4c99563a91 100644 --- a/scene/resources/visual_shader.cpp +++ b/scene/resources/visual_shader.cpp @@ -2508,14 +2508,6 @@ void VisualShader::_update_shader() const { global_compute_code += " return __rand_from_seed(seed) * (to - from) + from;\n"; global_compute_code += "}\n\n"; - global_compute_code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n"; - global_compute_code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n"; - global_compute_code += "}\n\n"; - - global_compute_code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n"; - global_compute_code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n"; - global_compute_code += "}\n\n"; - global_compute_code += "uint __hash(uint x) {\n"; global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n"; global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n"; diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp index 4ac663f7f2..9cf42b681c 100644 --- a/scene/resources/visual_shader_particle_nodes.cpp +++ b/scene/resources/visual_shader_particle_nodes.cpp @@ -911,11 +911,12 @@ void VisualShaderNodeParticleRandomness::_bind_methods() { ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeParticleRandomness::set_op_type); ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeParticleRandomness::get_op_type); - ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3"), "set_op_type", "get_op_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type"); BIND_ENUM_CONSTANT(OP_TYPE_SCALAR); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D); + BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D); BIND_ENUM_CONSTANT(OP_TYPE_MAX); } @@ -939,6 +940,8 @@ VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: return PORT_TYPE_VECTOR_3D; + case OP_TYPE_VECTOR_4D: + return PORT_TYPE_VECTOR_4D; default: break; } @@ -950,48 +953,69 @@ String VisualShaderNodeParticleRandomness::get_output_port_name(int p_port) cons } int VisualShaderNodeParticleRandomness::get_input_port_count() const { - return 2; + return 3; } VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness::get_input_port_type(int p_port) const { - switch (op_type) { - case OP_TYPE_VECTOR_2D: - return PORT_TYPE_VECTOR_2D; - case OP_TYPE_VECTOR_3D: - return PORT_TYPE_VECTOR_3D; - default: + switch (p_port) { + case 0: + return PORT_TYPE_SCALAR_UINT; + case 1: + case 2: + switch (op_type) { + case OP_TYPE_VECTOR_2D: + return PORT_TYPE_VECTOR_2D; + case OP_TYPE_VECTOR_3D: + return PORT_TYPE_VECTOR_3D; + case OP_TYPE_VECTOR_4D: + return PORT_TYPE_VECTOR_4D; + default: + break; + } break; } return PORT_TYPE_SCALAR; } String VisualShaderNodeParticleRandomness::get_input_port_name(int p_port) const { - if (p_port == 0) { - return "min"; - } else if (p_port == 1) { - return "max"; + switch (p_port) { + case 0: + return "seed"; + case 1: + return "min"; + case 2: + return "max"; } return String(); } -String VisualShaderNodeParticleRandomness::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { +bool VisualShaderNodeParticleRandomness::is_input_port_default(int p_port, Shader::Mode p_mode) const { + return p_port == 0; // seed +} + +String VisualShaderNodeParticleRandomness::generate_global_per_node(Shader::Mode p_mode, int p_id) const { String code; - switch (op_type) { - case OP_TYPE_SCALAR: { - code += vformat(" %s = __randf_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - case OP_TYPE_VECTOR_2D: { - code += vformat(" %s = __randv2_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - case OP_TYPE_VECTOR_3D: { - code += vformat(" %s = __randv3_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - default: - break; - } + + code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n"; + code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n"; + code += "}\n\n"; + + code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n"; + code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n"; + code += "}\n\n"; + + code += "vec4 __randv4_range(inout uint seed, vec4 from, vec4 to) {\n"; + code += " return vec4(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z), __randf_range(seed, from.w, to.w));\n"; + code += "}\n\n"; + return code; } +String VisualShaderNodeParticleRandomness::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + static const char *func[(int)OP_TYPE_MAX] = { "__randf_range", "__randv2_range", "__randv3_range", "__randv4_range" }; + return vformat(" %s = %s(%s, %s, %s);\n", p_output_vars[0], func[op_type], p_input_vars[0].is_empty() ? "__seed" : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1], p_input_vars[2].is_empty() ? (String)get_input_port_default_value(2) : p_input_vars[2]); +} + void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) { ERR_FAIL_INDEX(int(p_op_type), int(OP_TYPE_MAX)); if (op_type == p_op_type) { @@ -999,16 +1023,20 @@ void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) { } switch (p_op_type) { case OP_TYPE_SCALAR: { - set_input_port_default_value(0, 0.0, get_input_port_default_value(0)); set_input_port_default_value(1, 0.0, get_input_port_default_value(1)); + set_input_port_default_value(2, 0.0, get_input_port_default_value(2)); } break; case OP_TYPE_VECTOR_2D: { - set_input_port_default_value(0, Vector2(), get_input_port_default_value(0)); set_input_port_default_value(1, Vector2(), get_input_port_default_value(1)); + set_input_port_default_value(2, Vector2(), get_input_port_default_value(2)); } break; case OP_TYPE_VECTOR_3D: { - set_input_port_default_value(0, Vector3(), get_input_port_default_value(0)); set_input_port_default_value(1, Vector3(), get_input_port_default_value(1)); + set_input_port_default_value(2, Vector3(), get_input_port_default_value(2)); + } break; + case OP_TYPE_VECTOR_4D: { + set_input_port_default_value(1, Quaternion(), get_input_port_default_value(1)); + set_input_port_default_value(2, Quaternion(), get_input_port_default_value(2)); } break; default: break; @@ -1026,8 +1054,8 @@ bool VisualShaderNodeParticleRandomness::has_output_port_preview(int p_port) con } VisualShaderNodeParticleRandomness::VisualShaderNodeParticleRandomness() { - set_input_port_default_value(0, -1.0); - set_input_port_default_value(1, 1.0); + set_input_port_default_value(1, -1.0); + set_input_port_default_value(2, 1.0); } // VisualShaderNodeParticleAccelerator diff --git a/scene/resources/visual_shader_particle_nodes.h b/scene/resources/visual_shader_particle_nodes.h index c0ab974693..08fb059534 100644 --- a/scene/resources/visual_shader_particle_nodes.h +++ b/scene/resources/visual_shader_particle_nodes.h @@ -216,6 +216,7 @@ public: OP_TYPE_SCALAR, OP_TYPE_VECTOR_2D, OP_TYPE_VECTOR_3D, + OP_TYPE_VECTOR_4D, OP_TYPE_MAX, }; @@ -232,12 +233,14 @@ public: virtual int get_input_port_count() const override; virtual PortType get_input_port_type(int p_port) const override; virtual String get_input_port_name(int p_port) const override; + virtual bool is_input_port_default(int p_port, Shader::Mode p_mode) const override; virtual int get_output_port_count() const override; virtual PortType get_output_port_type(int p_port) const override; virtual String get_output_port_name(int p_port) const override; virtual bool has_output_port_preview(int p_port) const override; + virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override; virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; void set_op_type(OpType p_type); diff --git a/servers/display_server.cpp b/servers/display_server.cpp index 6af4783fa5..82343e0402 100644 --- a/servers/display_server.cpp +++ b/servers/display_server.cpp @@ -38,6 +38,9 @@ DisplayServer *DisplayServer::singleton = nullptr; bool DisplayServer::hidpi_allowed = false; +bool DisplayServer::window_early_clear_override_enabled = false; +Color DisplayServer::window_early_clear_override_color = Color(0, 0, 0, 0); + DisplayServer::DisplayServerCreate DisplayServer::server_create_functions[DisplayServer::MAX_SERVERS] = { { "headless", &DisplayServerHeadless::create_func, &DisplayServerHeadless::get_rendering_drivers_func } }; @@ -315,6 +318,23 @@ void DisplayServer::tts_post_utterance_event(TTSUtteranceEvent p_event, int p_id } } +bool DisplayServer::_get_window_early_clear_override(Color &r_color) { + if (window_early_clear_override_enabled) { + r_color = window_early_clear_override_color; + return true; + } else if (RenderingServer::get_singleton()) { + r_color = RenderingServer::get_singleton()->get_default_clear_color(); + return true; + } else { + return false; + } +} + +void DisplayServer::set_early_window_clear_color_override(bool p_enabled, Color p_color) { + window_early_clear_override_enabled = p_enabled; + window_early_clear_override_color = p_color; +} + void DisplayServer::mouse_set_mode(MouseMode p_mode) { WARN_PRINT("Mouse is not supported by this display server."); } diff --git a/servers/display_server.h b/servers/display_server.h index 0e4c8aa172..f8ade60aca 100644 --- a/servers/display_server.h +++ b/servers/display_server.h @@ -217,6 +217,16 @@ public: virtual bool is_dark_mode() const { return false; }; virtual Color get_accent_color() const { return Color(0, 0, 0, 0); }; +private: + static bool window_early_clear_override_enabled; + static Color window_early_clear_override_color; + +protected: + static bool _get_window_early_clear_override(Color &r_color); + +public: + static void set_early_window_clear_color_override(bool p_enabled, Color p_color = Color(0, 0, 0, 0)); + enum MouseMode { MOUSE_MODE_VISIBLE, MOUSE_MODE_HIDDEN, diff --git a/servers/navigation_server_3d.cpp b/servers/navigation_server_3d.cpp index 97c0ae0d54..253b28a623 100644 --- a/servers/navigation_server_3d.cpp +++ b/servers/navigation_server_3d.cpp @@ -123,6 +123,18 @@ void NavigationServer3D::_bind_methods() { ADD_SIGNAL(MethodInfo("map_changed", PropertyInfo(Variant::RID, "map"))); ADD_SIGNAL(MethodInfo("navigation_debug_changed")); + + ClassDB::bind_method(D_METHOD("get_process_info", "process_info"), &NavigationServer3D::get_process_info); + + BIND_ENUM_CONSTANT(INFO_ACTIVE_MAPS); + BIND_ENUM_CONSTANT(INFO_REGION_COUNT); + BIND_ENUM_CONSTANT(INFO_AGENT_COUNT); + BIND_ENUM_CONSTANT(INFO_LINK_COUNT); + BIND_ENUM_CONSTANT(INFO_POLYGON_COUNT); + BIND_ENUM_CONSTANT(INFO_EDGE_COUNT); + BIND_ENUM_CONSTANT(INFO_EDGE_MERGE_COUNT); + BIND_ENUM_CONSTANT(INFO_EDGE_CONNECTION_COUNT); + BIND_ENUM_CONSTANT(INFO_EDGE_FREE_COUNT); } NavigationServer3D *NavigationServer3D::get_singleton() { diff --git a/servers/navigation_server_3d.h b/servers/navigation_server_3d.h index afd7216a43..6c4bd2e151 100644 --- a/servers/navigation_server_3d.h +++ b/servers/navigation_server_3d.h @@ -260,6 +260,20 @@ public: NavigationServer3D(); virtual ~NavigationServer3D(); + enum ProcessInfo { + INFO_ACTIVE_MAPS, + INFO_REGION_COUNT, + INFO_AGENT_COUNT, + INFO_LINK_COUNT, + INFO_POLYGON_COUNT, + INFO_EDGE_COUNT, + INFO_EDGE_MERGE_COUNT, + INFO_EDGE_CONNECTION_COUNT, + INFO_EDGE_FREE_COUNT, + }; + + virtual int get_process_info(ProcessInfo p_info) const = 0; + #ifdef DEBUG_ENABLED private: bool debug_enabled = false; @@ -357,4 +371,6 @@ public: static NavigationServer3D *new_default_server(); }; +VARIANT_ENUM_CAST(NavigationServer3D::ProcessInfo); + #endif // NAVIGATION_SERVER_3D_H diff --git a/servers/physics_3d/godot_collision_solver_3d_sat.cpp b/servers/physics_3d/godot_collision_solver_3d_sat.cpp index 36c47a07b9..d13f4ee801 100644 --- a/servers/physics_3d/godot_collision_solver_3d_sat.cpp +++ b/servers/physics_3d/godot_collision_solver_3d_sat.cpp @@ -758,24 +758,72 @@ public: typedef void (*CollisionFunc)(const GodotShape3D *, const Transform3D &, const GodotShape3D *, const Transform3D &, _CollectorCallback *p_callback, real_t, real_t); +// Perform analytic sphere-sphere collision and report results to collector template <bool withMargin> -static void _collision_sphere_sphere(const GodotShape3D *p_a, const Transform3D &p_transform_a, const GodotShape3D *p_b, const Transform3D &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { - const GodotSphereShape3D *sphere_A = static_cast<const GodotSphereShape3D *>(p_a); - const GodotSphereShape3D *sphere_B = static_cast<const GodotSphereShape3D *>(p_b); +static void analytic_sphere_collision(const Vector3 &p_origin_a, real_t p_radius_a, const Vector3 &p_origin_b, real_t p_radius_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { + // Expand the spheres by the margins if enabled + if (withMargin) { + p_radius_a += p_margin_a; + p_radius_b += p_margin_b; + } - SeparatorAxisTest<GodotSphereShape3D, GodotSphereShape3D, withMargin> separator(sphere_A, p_transform_a, sphere_B, p_transform_b, p_collector, p_margin_a, p_margin_b); + // Get the vector from sphere B to A + Vector3 b_to_a = p_origin_a - p_origin_b; - // previous axis + // Get the length from B to A + real_t b_to_a_len = b_to_a.length(); - if (!separator.test_previous_axis()) { + // Calculate the sphere overlap, and bail if not overlapping + real_t overlap = p_radius_a + p_radius_b - b_to_a_len; + if (overlap < 0) return; - } - if (!separator.test_axis((p_transform_a.origin - p_transform_b.origin).normalized())) { + // Report collision + p_collector->collided = true; + + // Bail if there is no callback to receive the A and B collision points. + if (!p_collector->callback) { return; } - separator.generate_contacts(); + // Normalize the B to A vector + if (b_to_a_len < CMP_EPSILON) { + b_to_a = Vector3(0, 1, 0); // Spheres coincident, use arbitrary direction + } else { + b_to_a /= b_to_a_len; + } + + // Report collision points. The operations below are intended to minimize + // floating-point precision errors. This is done by calculating the first + // collision point from the smaller sphere, and then jumping across to + // the larger spheres collision point using the overlap distance. This + // jump is usually small even if the large sphere is massive, and so the + // second point will not suffer from precision errors. + if (p_radius_a < p_radius_b) { + Vector3 point_a = p_origin_a - b_to_a * p_radius_a; + Vector3 point_b = point_a + b_to_a * overlap; + p_collector->call(point_a, point_b); // Consider adding b_to_a vector + } else { + Vector3 point_b = p_origin_b + b_to_a * p_radius_b; + Vector3 point_a = point_b - b_to_a * overlap; + p_collector->call(point_a, point_b); // Consider adding b_to_a vector + } +} + +template <bool withMargin> +static void _collision_sphere_sphere(const GodotShape3D *p_a, const Transform3D &p_transform_a, const GodotShape3D *p_b, const Transform3D &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { + const GodotSphereShape3D *sphere_A = static_cast<const GodotSphereShape3D *>(p_a); + const GodotSphereShape3D *sphere_B = static_cast<const GodotSphereShape3D *>(p_b); + + // Perform an analytic sphere collision between the two spheres + analytic_sphere_collision<withMargin>( + p_transform_a.origin, + sphere_A->get_radius(), + p_transform_b.origin, + sphere_B->get_radius(), + p_collector, + p_margin_a, + p_margin_b); } template <bool withMargin> @@ -783,50 +831,36 @@ static void _collision_sphere_box(const GodotShape3D *p_a, const Transform3D &p_ const GodotSphereShape3D *sphere_A = static_cast<const GodotSphereShape3D *>(p_a); const GodotBoxShape3D *box_B = static_cast<const GodotBoxShape3D *>(p_b); - SeparatorAxisTest<GodotSphereShape3D, GodotBoxShape3D, withMargin> separator(sphere_A, p_transform_a, box_B, p_transform_b, p_collector, p_margin_a, p_margin_b); + // Find the point on the box nearest to the center of the sphere. - if (!separator.test_previous_axis()) { - return; - } + Vector3 center = p_transform_b.xform_inv(p_transform_a.origin); + Vector3 extents = box_B->get_half_extents(); + Vector3 nearest(MIN(MAX(center.x, -extents.x), extents.x), + MIN(MAX(center.y, -extents.y), extents.y), + MIN(MAX(center.z, -extents.z), extents.z)); + nearest = p_transform_b.xform(nearest); - // test faces + // See if it is inside the sphere. - for (int i = 0; i < 3; i++) { - Vector3 axis = p_transform_b.basis.get_column(i).normalized(); - - if (!separator.test_axis(axis)) { - return; - } + Vector3 delta = nearest - p_transform_a.origin; + real_t length = delta.length(); + if (length > sphere_A->get_radius() + p_margin_a + p_margin_b) { + return; } - - // calculate closest point to sphere - - Vector3 cnormal = p_transform_b.xform_inv(p_transform_a.origin); - - Vector3 cpoint = p_transform_b.xform(Vector3( - - (cnormal.x < 0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x, - (cnormal.y < 0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y, - (cnormal.z < 0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z)); - - // use point to test axis - Vector3 point_axis = (p_transform_a.origin - cpoint).normalized(); - - if (!separator.test_axis(point_axis)) { + p_collector->collided = true; + if (!p_collector->callback) { return; } - - // test edges - - for (int i = 0; i < 3; i++) { - Vector3 axis = point_axis.cross(p_transform_b.basis.get_column(i)).cross(p_transform_b.basis.get_column(i)).normalized(); - - if (!separator.test_axis(axis)) { - return; - } + Vector3 axis; + if (length == 0) { + // The box passes through the sphere center. Select an axis based on the box's center. + axis = (p_transform_b.origin - nearest).normalized(); + } else { + axis = delta / length; } - - separator.generate_contacts(); + Vector3 point_a = p_transform_a.origin + (sphere_A->get_radius() + p_margin_a) * axis; + Vector3 point_b = (withMargin ? nearest + p_margin_b * axis : nearest); + p_collector->call(point_a, point_b); } template <bool withMargin> @@ -834,41 +868,66 @@ static void _collision_sphere_capsule(const GodotShape3D *p_a, const Transform3D const GodotSphereShape3D *sphere_A = static_cast<const GodotSphereShape3D *>(p_a); const GodotCapsuleShape3D *capsule_B = static_cast<const GodotCapsuleShape3D *>(p_b); - SeparatorAxisTest<GodotSphereShape3D, GodotCapsuleShape3D, withMargin> separator(sphere_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - if (!separator.test_previous_axis()) { - return; - } - - //capsule sphere 1, sphere - - Vector3 capsule_axis = p_transform_b.basis.get_column(1) * (capsule_B->get_height() * 0.5 - capsule_B->get_radius()); - - Vector3 capsule_ball_1 = p_transform_b.origin + capsule_axis; + real_t capsule_B_radius = capsule_B->get_radius(); + + // Construct the capsule segment (ball-center to ball-center) + Vector3 capsule_segment[2]; + Vector3 capsule_axis = p_transform_b.basis.get_column(1) * (capsule_B->get_height() * 0.5 - capsule_B_radius); + capsule_segment[0] = p_transform_b.origin + capsule_axis; + capsule_segment[1] = p_transform_b.origin - capsule_axis; + + // Get the capsules closest segment-point to the sphere + Vector3 capsule_closest = Geometry3D::get_closest_point_to_segment(p_transform_a.origin, capsule_segment); + + // Perform an analytic sphere collision between the sphere and the sphere-collider in the capsule + analytic_sphere_collision<withMargin>( + p_transform_a.origin, + sphere_A->get_radius(), + capsule_closest, + capsule_B_radius, + p_collector, + p_margin_a, + p_margin_b); +} - if (!separator.test_axis((capsule_ball_1 - p_transform_a.origin).normalized())) { +template <bool withMargin> +static void analytic_sphere_cylinder_collision(real_t p_radius_a, real_t p_radius_b, real_t p_height_b, const Transform3D &p_transform_a, const Transform3D &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) { + // Find the point on the cylinder nearest to the center of the sphere. + + Vector3 center = p_transform_b.xform_inv(p_transform_a.origin); + Vector3 nearest = center; + real_t radius = p_radius_b; + real_t r = Math::sqrt(center.x * center.x + center.z * center.z); + if (r > radius) { + real_t scale = radius / r; + nearest.x *= scale; + nearest.z *= scale; + } + real_t half_height = p_height_b / 2; + nearest.y = MIN(MAX(center.y, -half_height), half_height); + nearest = p_transform_b.xform(nearest); + + // See if it is inside the sphere. + + Vector3 delta = nearest - p_transform_a.origin; + real_t length = delta.length(); + if (length > p_radius_a + p_margin_a + p_margin_b) { return; } - - //capsule sphere 2, sphere - - Vector3 capsule_ball_2 = p_transform_b.origin - capsule_axis; - - if (!separator.test_axis((capsule_ball_2 - p_transform_a.origin).normalized())) { + p_collector->collided = true; + if (!p_collector->callback) { return; } - - //capsule edge, sphere - - Vector3 b2a = p_transform_a.origin - p_transform_b.origin; - - Vector3 axis = b2a.cross(capsule_axis).cross(capsule_axis).normalized(); - - if (!separator.test_axis(axis)) { - return; + Vector3 axis; + if (length == 0) { + // The cylinder passes through the sphere center. Select an axis based on the cylinder's center. + axis = (p_transform_b.origin - nearest).normalized(); + } else { + axis = delta / length; } - - separator.generate_contacts(); + Vector3 point_a = p_transform_a.origin + (p_radius_a + p_margin_a) * axis; + Vector3 point_b = (withMargin ? nearest + p_margin_b * axis : nearest); + p_collector->call(point_a, point_b); } template <bool withMargin> @@ -876,58 +935,7 @@ static void _collision_sphere_cylinder(const GodotShape3D *p_a, const Transform3 const GodotSphereShape3D *sphere_A = static_cast<const GodotSphereShape3D *>(p_a); const GodotCylinderShape3D *cylinder_B = static_cast<const GodotCylinderShape3D *>(p_b); - SeparatorAxisTest<GodotSphereShape3D, GodotCylinderShape3D, withMargin> separator(sphere_A, p_transform_a, cylinder_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - if (!separator.test_previous_axis()) { - return; - } - - // Cylinder B end caps. - Vector3 cylinder_B_axis = p_transform_b.basis.get_column(1).normalized(); - if (!separator.test_axis(cylinder_B_axis)) { - return; - } - - Vector3 cylinder_diff = p_transform_b.origin - p_transform_a.origin; - - // Cylinder B lateral surface. - if (!separator.test_axis(cylinder_B_axis.cross(cylinder_diff).cross(cylinder_B_axis).normalized())) { - return; - } - - // Closest point to cylinder caps. - const Vector3 &sphere_center = p_transform_a.origin; - Vector3 cyl_axis = p_transform_b.basis.get_column(1); - Vector3 cap_axis = p_transform_b.basis.get_column(0); - real_t height_scale = cyl_axis.length(); - real_t cap_dist = cylinder_B->get_height() * 0.5 * height_scale; - cyl_axis /= height_scale; - real_t radius_scale = cap_axis.length(); - real_t cap_radius = cylinder_B->get_radius() * radius_scale; - - for (int i = 0; i < 2; i++) { - Vector3 cap_dir = ((i == 0) ? cyl_axis : -cyl_axis); - Vector3 cap_pos = p_transform_b.origin + cap_dir * cap_dist; - - Vector3 closest_point; - - Vector3 diff = sphere_center - cap_pos; - Vector3 proj = diff - cap_dir.dot(diff) * cap_dir; - - real_t proj_len = proj.length(); - if (Math::is_zero_approx(proj_len)) { - // Point is equidistant to all circle points. - continue; - } - - closest_point = cap_pos + (cap_radius / proj_len) * proj; - - if (!separator.test_axis((closest_point - sphere_center).normalized())) { - return; - } - } - - separator.generate_contacts(); + analytic_sphere_cylinder_collision<withMargin>(sphere_A->get_radius(), cylinder_B->get_radius(), cylinder_B->get_height(), p_transform_a, p_transform_b, p_collector, p_margin_a, p_margin_b); } template <bool withMargin> @@ -1615,63 +1623,31 @@ static void _collision_capsule_capsule(const GodotShape3D *p_a, const Transform3 const GodotCapsuleShape3D *capsule_A = static_cast<const GodotCapsuleShape3D *>(p_a); const GodotCapsuleShape3D *capsule_B = static_cast<const GodotCapsuleShape3D *>(p_b); - SeparatorAxisTest<GodotCapsuleShape3D, GodotCapsuleShape3D, withMargin> separator(capsule_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - if (!separator.test_previous_axis()) { - return; - } - - // some values - - Vector3 capsule_A_axis = p_transform_a.basis.get_column(1) * (capsule_A->get_height() * 0.5 - capsule_A->get_radius()); - Vector3 capsule_B_axis = p_transform_b.basis.get_column(1) * (capsule_B->get_height() * 0.5 - capsule_B->get_radius()); - - Vector3 capsule_A_ball_1 = p_transform_a.origin + capsule_A_axis; - Vector3 capsule_A_ball_2 = p_transform_a.origin - capsule_A_axis; - Vector3 capsule_B_ball_1 = p_transform_b.origin + capsule_B_axis; - Vector3 capsule_B_ball_2 = p_transform_b.origin - capsule_B_axis; - - //balls-balls - - if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).normalized())) { - return; - } - if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).normalized())) { - return; - } - - if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_1).normalized())) { - return; - } - if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_2).normalized())) { - return; - } - - // edges-balls - - if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).cross(capsule_A_axis).cross(capsule_A_axis).normalized())) { - return; - } - - if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).cross(capsule_A_axis).cross(capsule_A_axis).normalized())) { - return; - } - - if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_1).cross(capsule_B_axis).cross(capsule_B_axis).normalized())) { - return; - } - - if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_2).cross(capsule_B_axis).cross(capsule_B_axis).normalized())) { - return; - } - - // edges - - if (!separator.test_axis(capsule_A_axis.cross(capsule_B_axis).normalized())) { - return; - } - - separator.generate_contacts(); + real_t capsule_A_radius = capsule_A->get_radius(); + real_t capsule_B_radius = capsule_B->get_radius(); + + // Get the closest points between the capsule segments + Vector3 capsule_A_closest; + Vector3 capsule_B_closest; + Vector3 capsule_A_axis = p_transform_a.basis.get_column(1) * (capsule_A->get_height() * 0.5 - capsule_A_radius); + Vector3 capsule_B_axis = p_transform_b.basis.get_column(1) * (capsule_B->get_height() * 0.5 - capsule_B_radius); + Geometry3D::get_closest_points_between_segments( + p_transform_a.origin + capsule_A_axis, + p_transform_a.origin - capsule_A_axis, + p_transform_b.origin + capsule_B_axis, + p_transform_b.origin - capsule_B_axis, + capsule_A_closest, + capsule_B_closest); + + // Perform the analytic collision between the two closest capsule spheres + analytic_sphere_collision<withMargin>( + capsule_A_closest, + capsule_A_radius, + capsule_B_closest, + capsule_B_radius, + p_collector, + p_margin_a, + p_margin_b); } template <bool withMargin> @@ -1679,61 +1655,24 @@ static void _collision_capsule_cylinder(const GodotShape3D *p_a, const Transform const GodotCapsuleShape3D *capsule_A = static_cast<const GodotCapsuleShape3D *>(p_a); const GodotCylinderShape3D *cylinder_B = static_cast<const GodotCylinderShape3D *>(p_b); - SeparatorAxisTest<GodotCapsuleShape3D, GodotCylinderShape3D, withMargin> separator(capsule_A, p_transform_a, cylinder_B, p_transform_b, p_collector, p_margin_a, p_margin_b); - - if (!separator.test_previous_axis()) { - return; - } - - // Cylinder B end caps. - Vector3 cylinder_B_axis = p_transform_b.basis.get_column(1).normalized(); - if (!separator.test_axis(cylinder_B_axis)) { - return; - } - - // Cylinder edge against capsule balls. - - Vector3 capsule_A_axis = p_transform_a.basis.get_column(1); - - Vector3 capsule_A_ball_1 = p_transform_a.origin + capsule_A_axis * (capsule_A->get_height() * 0.5 - capsule_A->get_radius()); - Vector3 capsule_A_ball_2 = p_transform_a.origin - capsule_A_axis * (capsule_A->get_height() * 0.5 - capsule_A->get_radius()); - - if (!separator.test_axis((p_transform_b.origin - capsule_A_ball_1).cross(cylinder_B_axis).cross(cylinder_B_axis).normalized())) { - return; - } - - if (!separator.test_axis((p_transform_b.origin - capsule_A_ball_2).cross(cylinder_B_axis).cross(cylinder_B_axis).normalized())) { - return; - } - - // Cylinder edge against capsule edge. + // Find the closest points between the axes of the two objects. - Vector3 center_diff = p_transform_b.origin - p_transform_a.origin; - - if (!separator.test_axis(capsule_A_axis.cross(center_diff).cross(capsule_A_axis).normalized())) { - return; - } - - if (!separator.test_axis(cylinder_B_axis.cross(center_diff).cross(cylinder_B_axis).normalized())) { - return; - } - - real_t proj = capsule_A_axis.cross(cylinder_B_axis).cross(cylinder_B_axis).dot(capsule_A_axis); - if (Math::is_zero_approx(proj)) { - // Parallel capsule and cylinder axes, handle with specific axes only. - // Note: GJKEPA with no margin can lead to degenerate cases in this situation. - separator.generate_contacts(); - return; - } - - GodotCollisionSolver3D::CallbackResult callback = SeparatorAxisTest<GodotCapsuleShape3D, GodotCylinderShape3D, withMargin>::test_contact_points; - - // Fallback to generic algorithm to find the best separating axis. - if (!fallback_collision_solver(p_a, p_transform_a, p_b, p_transform_b, callback, &separator, false, p_margin_a, p_margin_b)) { - return; - } - - separator.generate_contacts(); + Vector3 capsule_A_closest; + Vector3 cylinder_B_closest; + Vector3 capsule_A_axis = p_transform_a.basis.get_column(1) * (capsule_A->get_height() * 0.5 - capsule_A->get_radius()); + Vector3 cylinder_B_axis = p_transform_b.basis.get_column(1) * (cylinder_B->get_height() * 0.5); + Geometry3D::get_closest_points_between_segments( + p_transform_a.origin + capsule_A_axis, + p_transform_a.origin - capsule_A_axis, + p_transform_b.origin + cylinder_B_axis, + p_transform_b.origin - cylinder_B_axis, + capsule_A_closest, + cylinder_B_closest); + + // Perform the collision test between the cylinder and the nearest sphere on the capsule axis. + + Transform3D sphere_transform(p_transform_a.basis, capsule_A_closest); + analytic_sphere_cylinder_collision<withMargin>(capsule_A->get_radius(), cylinder_B->get_radius(), cylinder_B->get_height(), sphere_transform, p_transform_b, p_collector, p_margin_a, p_margin_b); } template <bool withMargin> diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp index bd34d83ea3..93c741fd34 100644 --- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp @@ -1707,7 +1707,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co RD::get_singleton()->draw_command_end_label(); - if (rb.is_valid()) { + if (rb.is_valid() && !p_render_data->reflection_probe.is_valid()) { if (using_voxelgi) { depth_pass_mode = PASS_MODE_DEPTH_NORMAL_ROUGHNESS_VOXEL_GI; } else if (p_render_data->environment.is_valid()) { diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp index 66ae1e8d1a..d631a89dd2 100644 --- a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp +++ b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp @@ -2685,6 +2685,14 @@ void MaterialStorage::material_free(RID p_rid) { Material *material = material_owner.get_or_null(p_rid); ERR_FAIL_COND(!material); + // Need to clear texture arrays to prevent spin locking of their RID's. + // This happens when the app is being closed. + for (KeyValue<StringName, Variant> &E : material->params) { + if (E.value.get_type() == Variant::ARRAY) { + Array(E.value).clear(); + } + } + material_set_shader(p_rid, RID()); //clean up shader material->dependency.deleted_notify(p_rid); diff --git a/servers/rendering/rendering_device_binds.cpp b/servers/rendering/rendering_device_binds.cpp index 5967835d03..3678b70254 100644 --- a/servers/rendering/rendering_device_binds.cpp +++ b/servers/rendering/rendering_device_binds.cpp @@ -31,6 +31,8 @@ #include "rendering_device_binds.h" Error RDShaderFile::parse_versions_from_text(const String &p_text, const String p_defines, OpenIncludeFunction p_include_func, void *p_include_func_userdata) { + ERR_FAIL_NULL_V(RenderingDevice::get_singleton(), ERR_UNAVAILABLE); + Vector<String> lines = p_text.split("\n"); bool reading_versions = false; diff --git a/servers/rendering/rendering_server_default.cpp b/servers/rendering/rendering_server_default.cpp index 4c4b3d13f9..6017eff55e 100644 --- a/servers/rendering/rendering_server_default.cpp +++ b/servers/rendering/rendering_server_default.cpp @@ -291,6 +291,10 @@ void RenderingServerDefault::set_boot_image(const Ref<Image> &p_image, const Col RSG::rasterizer->set_boot_image(p_image, p_color, p_scale, p_use_filter); } +Color RenderingServerDefault::get_default_clear_color() { + return RSG::texture_storage->get_default_clear_color(); +} + void RenderingServerDefault::set_default_clear_color(const Color &p_color) { RSG::viewport->set_default_clear_color(p_color); } diff --git a/servers/rendering/rendering_server_default.h b/servers/rendering/rendering_server_default.h index f2fadd5e1f..d053c60b85 100644 --- a/servers/rendering/rendering_server_default.h +++ b/servers/rendering/rendering_server_default.h @@ -986,6 +986,7 @@ public: virtual double get_frame_setup_time_cpu() const override; virtual void set_boot_image(const Ref<Image> &p_image, const Color &p_color, bool p_scale, bool p_use_filter = true) override; + virtual Color get_default_clear_color() override; virtual void set_default_clear_color(const Color &p_color) override; virtual bool has_feature(Features p_feature) const override; diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp index 658d683398..14d8d035e2 100644 --- a/servers/rendering_server.cpp +++ b/servers/rendering_server.cpp @@ -2763,6 +2763,7 @@ void RenderingServer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_white_texture"), &RenderingServer::get_white_texture); ClassDB::bind_method(D_METHOD("set_boot_image", "image", "color", "scale", "use_filter"), &RenderingServer::set_boot_image, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("get_default_clear_color"), &RenderingServer::get_default_clear_color); ClassDB::bind_method(D_METHOD("set_default_clear_color", "color"), &RenderingServer::set_default_clear_color); ClassDB::bind_method(D_METHOD("has_feature", "feature"), &RenderingServer::has_feature); diff --git a/servers/rendering_server.h b/servers/rendering_server.h index 81aec55ce6..5785f5c273 100644 --- a/servers/rendering_server.h +++ b/servers/rendering_server.h @@ -1561,6 +1561,7 @@ public: virtual void mesh_add_surface_from_planes(RID p_mesh, const Vector<Plane> &p_planes); virtual void set_boot_image(const Ref<Image> &p_image, const Color &p_color, bool p_scale, bool p_use_filter = true) = 0; + virtual Color get_default_clear_color() = 0; virtual void set_default_clear_color(const Color &p_color) = 0; enum Features { diff --git a/tests/scene/test_node.h b/tests/scene/test_node.h index 20c42d9fc2..0ddf027970 100644 --- a/tests/scene/test_node.h +++ b/tests/scene/test_node.h @@ -37,7 +37,7 @@ namespace TestNode { -TEST_CASE("[SceneTree][Node] Simple Add/Remove/Move/Find") { +TEST_CASE("[SceneTree][Node] Testing node operations with a very simple scene tree") { Node *node = memnew(Node); // Check initial scene tree setup. @@ -135,10 +135,30 @@ TEST_CASE("[SceneTree][Node] Simple Add/Remove/Move/Find") { CHECK(node->is_inside_tree()); } + SUBCASE("Node should be possible to reparent") { + node->reparent(SceneTree::get_singleton()->get_root()); + + Node *child = SceneTree::get_singleton()->get_root()->get_child(0); + CHECK_EQ(child, node); + CHECK(node->is_inside_tree()); + } + + SUBCASE("Node should be possible to duplicate") { + node->set_name("MyName"); + + Node *duplicate = node->duplicate(); + + CHECK_FALSE(node == duplicate); + CHECK_FALSE(duplicate->is_inside_tree()); + CHECK_EQ(duplicate->get_name(), node->get_name()); + + memdelete(duplicate); + } + memdelete(node); } -TEST_CASE("[SceneTree][Node] Nested Add/Remove/Move/Find") { +TEST_CASE("[SceneTree][Node] Testing node operations with a more complex simple scene tree") { Node *node1 = memnew(Node); Node *node2 = memnew(Node); Node *node1_1 = memnew(Node); @@ -209,7 +229,7 @@ TEST_CASE("[SceneTree][Node] Nested Add/Remove/Move/Find") { CHECK_EQ(child2, node1); } - SUBCASE("Nodes should be in the expected order when reparented") { + SUBCASE("Nodes should be in the expected order when reparented (remove/add)") { CHECK_EQ(node2->get_child_count(), 0); node1->remove_child(node1_1); @@ -227,6 +247,22 @@ TEST_CASE("[SceneTree][Node] Nested Add/Remove/Move/Find") { CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 4); } + SUBCASE("Nodes should be in the expected order when reparented") { + CHECK_EQ(node2->get_child_count(), 0); + + node1_1->reparent(node2); + + CHECK_EQ(node1->get_child_count(), 0); + CHECK_EQ(node2->get_child_count(), 1); + CHECK_EQ(node1_1->get_parent(), node2); + + Node *child = node2->get_child(0); + CHECK_EQ(child, node1_1); + + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child_count(), 2); + CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 4); + } + SUBCASE("Nodes should be possible to find") { Node *child = SceneTree::get_singleton()->get_root()->find_child("NestedNode", true, false); CHECK_EQ(child, nullptr); @@ -315,6 +351,70 @@ TEST_CASE("[SceneTree][Node] Nested Add/Remove/Move/Find") { CHECK_EQ(E->get(), node1_1); } + SUBCASE("Nodes added as siblings of another node should be right next to it") { + node1->remove_child(node1_1); + + node1->add_sibling(node1_1); + + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child_count(), 3); + CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 4); + + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(0), node1); + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(1), node1_1); + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child(2), node2); + } + + SUBCASE("Replaced nodes should be be removed and the replacing node added") { + SceneTree::get_singleton()->get_root()->remove_child(node2); + + node1->replace_by(node2); + + CHECK_EQ(SceneTree::get_singleton()->get_root()->get_child_count(), 1); + CHECK_EQ(SceneTree::get_singleton()->get_node_count(), 3); + + CHECK_FALSE(node1->is_inside_tree()); + CHECK(node2->is_inside_tree()); + + CHECK_EQ(node1->get_parent(), nullptr); + CHECK_EQ(node2->get_parent(), SceneTree::get_singleton()->get_root()); + CHECK_EQ(node2->get_child_count(), 1); + CHECK_EQ(node2->get_child(0), node1_1); + } + + SUBCASE("Replacing nodes should keep the groups of the replaced nodes") { + SceneTree::get_singleton()->get_root()->remove_child(node2); + + node1->add_to_group("nodes"); + node1->replace_by(node2, true); + + List<Node *> nodes; + SceneTree::get_singleton()->get_nodes_in_group("nodes", &nodes); + CHECK_EQ(nodes.size(), 1); + + List<Node *>::Element *E = nodes.front(); + CHECK_EQ(E->get(), node2); + } + + SUBCASE("Duplicating a node should also duplicate the children") { + node1->set_name("MyName1"); + node1_1->set_name("MyName1_1"); + Node *duplicate1 = node1->duplicate(); + + CHECK_EQ(duplicate1->get_child_count(), node1->get_child_count()); + Node *duplicate1_1 = duplicate1->get_child(0); + + CHECK_EQ(duplicate1_1->get_child_count(), node1_1->get_child_count()); + + CHECK_EQ(duplicate1->get_name(), node1->get_name()); + CHECK_EQ(duplicate1_1->get_name(), node1_1->get_name()); + + CHECK_FALSE(duplicate1->is_inside_tree()); + CHECK_FALSE(duplicate1_1->is_inside_tree()); + + memdelete(duplicate1_1); + memdelete(duplicate1); + } + memdelete(node1_1); memdelete(node1); memdelete(node2); |