diff options
326 files changed, 6040 insertions, 3850 deletions
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt index e84302620e..8ad6997463 100644 --- a/COPYRIGHT.txt +++ b/COPYRIGHT.txt @@ -143,7 +143,7 @@ License: Expat Files: ./thirdparty/doctest/ Comment: doctest -Copyright: 2016-2020, Viktor Kirilov +Copyright: 2016-2021, Viktor Kirilov License: Expat Files: ./thirdparty/embree/ @@ -177,11 +177,6 @@ Copyright: 2018, Source Foundry Authors 2003, Bitstream Inc. License: Expat and Bitstream Vera Fonts Copyright -Files: ./thirdparty/fonts/Tamsyn*.png -Comment: Tamsyn font -Copyright: 2015, Scott Fial -License: Tamsyn - Files: ./thirdparty/freetype/ Comment: The FreeType Project Copyright: 1996-2020, David Turner, Robert Wilhelm, and Werner Lemberg. @@ -1865,18 +1860,6 @@ License: OFL-1.1 DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE. -License: Tamsyn - Tamsyn font is free. You are hereby granted permission to use, copy, modify, - and distribute it as you see fit. - . - Tamsyn font is provided "as is" without any express or implied warranty. - . - The author makes no representations about the suitability of this font for - a particular purpose. - . - In no event will the author be held liable for damages arising from the use - of this font. - License: Unicode COPYRIGHT AND PERMISSION NOTICE (ICU 58 and later) . diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp index 85e83ff7f2..57833fe42f 100644 --- a/core/config/project_settings.cpp +++ b/core/config/project_settings.cpp @@ -48,11 +48,22 @@ ProjectSettings *ProjectSettings::get_singleton() { return singleton; } +String ProjectSettings::get_project_data_dir_name() const { + return ".godot"; +} + +String ProjectSettings::get_project_data_path() const { + String project_data_dir_name = get_project_data_dir_name(); + return "res://" + project_data_dir_name; +} + String ProjectSettings::get_resource_path() const { return resource_path; } -const String ProjectSettings::IMPORTED_FILES_PATH("res://.godot/imported"); +String ProjectSettings::get_imported_files_path() const { + return get_project_data_path().plus_file("imported"); +} String ProjectSettings::localize_path(const String &p_path) const { if (resource_path.is_empty() || p_path.begins_with("res://") || p_path.begins_with("user://") || diff --git a/core/config/project_settings.h b/core/config/project_settings.h index 7e93f26f0d..b642051402 100644 --- a/core/config/project_settings.h +++ b/core/config/project_settings.h @@ -42,7 +42,6 @@ class ProjectSettings : public Object { public: typedef Map<String, Variant> CustomMap; - static const String IMPORTED_FILES_PATH; enum { //properties that are not for built in values begin from this value, so builtin ones are displayed first @@ -141,7 +140,10 @@ public: bool property_can_revert(const String &p_name); Variant property_get_revert(const String &p_name); + String get_project_data_dir_name() const; + String get_project_data_path() const; String get_resource_path() const; + String get_imported_files_path() const; static ProjectSettings *get_singleton(); diff --git a/core/core_bind.cpp b/core/core_bind.cpp index 0b9816932c..f630adc39e 100644 --- a/core/core_bind.cpp +++ b/core/core_bind.cpp @@ -1768,6 +1768,12 @@ void Thread::_start_func(void *ud) { Ref<Thread> *tud = (Ref<Thread> *)ud; Ref<Thread> t = *tud; memdelete(tud); + + Object *target_instance = t->target_callable.get_object(); + if (!target_instance) { + ERR_FAIL_MSG(vformat("Could not call function '%s' on previously freed instance to start thread %s.", t->target_callable.get_method(), t->get_id())); + } + Callable::CallError ce; const Variant *arg[1] = { &t->userdata }; int argc = 0; @@ -1786,15 +1792,17 @@ void Thread::_start_func(void *ud) { // We must check if we are in case b). int target_param_count = 0; int target_default_arg_count = 0; - Ref<Script> script = t->target_callable.get_object()->get_script(); + Ref<Script> script = target_instance->get_script(); if (script.is_valid()) { MethodInfo mi = script->get_method_info(t->target_callable.get_method()); target_param_count = mi.arguments.size(); target_default_arg_count = mi.default_arguments.size(); } else { - MethodBind *method = ClassDB::get_method(t->target_callable.get_object()->get_class_name(), t->target_callable.get_method()); - target_param_count = method->get_argument_count(); - target_default_arg_count = method->get_default_argument_count(); + MethodBind *method = ClassDB::get_method(target_instance->get_class_name(), t->target_callable.get_method()); + if (method) { + target_param_count = method->get_argument_count(); + target_default_arg_count = method->get_default_argument_count(); + } } if (target_param_count >= 1 && target_default_arg_count < target_param_count) { argc = 1; diff --git a/core/error/error_macros.h b/core/error/error_macros.h index f909a67d55..1bed8d366b 100644 --- a/core/error/error_macros.h +++ b/core/error/error_macros.h @@ -89,13 +89,6 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li #define GENERATE_TRAP() __builtin_trap() #endif -// Used to strip debug messages in release mode -#ifdef DEBUG_ENABLED -#define DEBUG_STR(m_msg) m_msg -#else -#define DEBUG_STR(m_msg) "" -#endif - /** * Error macros. * WARNING: These macros work in the opposite way to assert(). @@ -135,11 +128,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an integer index `m_index` is less than `m_size` and greater than or equal to 0. * If not, prints `m_msg` and the current function returns. */ -#define ERR_FAIL_INDEX_MSG(m_index, m_size, m_msg) \ - if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg)); \ - return; \ - } else \ +#define ERR_FAIL_INDEX_MSG(m_index, m_size, m_msg) \ + if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg); \ + return; \ + } else \ ((void)0) /** @@ -160,11 +153,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an integer index `m_index` is less than `m_size` and greater than or equal to 0. * If not, prints `m_msg` and the current function returns `m_retval`. */ -#define ERR_FAIL_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ - if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg)); \ - return m_retval; \ - } else \ +#define ERR_FAIL_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ + if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg); \ + return m_retval; \ + } else \ ((void)0) /** @@ -189,11 +182,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an integer index `m_index` is less than `m_size` and greater than or equal to 0. * If not, prints `m_msg` and the application crashes. */ -#define CRASH_BAD_INDEX_MSG(m_index, m_size, m_msg) \ - if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg), true); \ - GENERATE_TRAP(); \ - } else \ +#define CRASH_BAD_INDEX_MSG(m_index, m_size, m_msg) \ + if (unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg, true); \ + GENERATE_TRAP(); \ + } else \ ((void)0) // Unsigned integer index out of bounds error macros. @@ -216,11 +209,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an unsigned integer index `m_index` is less than `m_size`. * If not, prints `m_msg` and the current function returns. */ -#define ERR_FAIL_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ - if (unlikely((m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg)); \ - return; \ - } else \ +#define ERR_FAIL_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ + if (unlikely((m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg); \ + return; \ + } else \ ((void)0) /** @@ -241,11 +234,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an unsigned integer index `m_index` is less than `m_size`. * If not, prints `m_msg` and the current function returns `m_retval`. */ -#define ERR_FAIL_UNSIGNED_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ - if (unlikely((m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg)); \ - return m_retval; \ - } else \ +#define ERR_FAIL_UNSIGNED_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ + if (unlikely((m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg); \ + return m_retval; \ + } else \ ((void)0) /** @@ -270,11 +263,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures an unsigned integer index `m_index` is less than `m_size`. * If not, prints `m_msg` and the application crashes. */ -#define CRASH_BAD_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ - if (unlikely((m_index) >= (m_size))) { \ - _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), DEBUG_STR(m_msg), true); \ - GENERATE_TRAP(); \ - } else \ +#define CRASH_BAD_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ + if (unlikely((m_index) >= (m_size))) { \ + _err_print_index_error(FUNCTION_STR, __FILE__, __LINE__, m_index, m_size, _STR(m_index), _STR(m_size), m_msg, true); \ + GENERATE_TRAP(); \ + } else \ ((void)0) // Null reference error macros. @@ -297,11 +290,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures a pointer `m_param` is not null. * If it is null, prints `m_msg` and the current function returns. */ -#define ERR_FAIL_NULL_MSG(m_param, m_msg) \ - if (unlikely(m_param == nullptr)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter \"" _STR(m_param) "\" is null.", DEBUG_STR(m_msg)); \ - return; \ - } else \ +#define ERR_FAIL_NULL_MSG(m_param, m_msg) \ + if (unlikely(m_param == nullptr)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter \"" _STR(m_param) "\" is null.", m_msg); \ + return; \ + } else \ ((void)0) /** @@ -322,11 +315,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures a pointer `m_param` is not null. * If it is null, prints `m_msg` and the current function returns `m_retval`. */ -#define ERR_FAIL_NULL_V_MSG(m_param, m_retval, m_msg) \ - if (unlikely(m_param == nullptr)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter \"" _STR(m_param) "\" is null.", DEBUG_STR(m_msg)); \ - return m_retval; \ - } else \ +#define ERR_FAIL_NULL_V_MSG(m_param, m_retval, m_msg) \ + if (unlikely(m_param == nullptr)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter \"" _STR(m_param) "\" is null.", m_msg); \ + return m_retval; \ + } else \ ((void)0) /** @@ -352,11 +345,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * If checking for null use ERR_FAIL_NULL_MSG instead. * If checking index bounds use ERR_FAIL_INDEX_MSG instead. */ -#define ERR_FAIL_COND_MSG(m_cond, m_msg) \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true.", DEBUG_STR(m_msg)); \ - return; \ - } else \ +#define ERR_FAIL_COND_MSG(m_cond, m_msg) \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true.", m_msg); \ + return; \ + } else \ ((void)0) /** @@ -382,11 +375,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * If checking for null use ERR_FAIL_NULL_V_MSG instead. * If checking index bounds use ERR_FAIL_INDEX_V_MSG instead. */ -#define ERR_FAIL_COND_V_MSG(m_cond, m_retval, m_msg) \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Returning: " _STR(m_retval), DEBUG_STR(m_msg)); \ - return m_retval; \ - } else \ +#define ERR_FAIL_COND_V_MSG(m_cond, m_retval, m_msg) \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Returning: " _STR(m_retval), m_msg); \ + return m_retval; \ + } else \ ((void)0) /** @@ -407,11 +400,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures `m_cond` is false. * If `m_cond` is true, prints `m_msg` and the current loop continues. */ -#define ERR_CONTINUE_MSG(m_cond, m_msg) \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Continuing.", DEBUG_STR(m_msg)); \ - continue; \ - } else \ +#define ERR_CONTINUE_MSG(m_cond, m_msg) \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Continuing.", m_msg); \ + continue; \ + } else \ ((void)0) /** @@ -432,11 +425,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures `m_cond` is false. * If `m_cond` is true, prints `m_msg` and the current loop breaks. */ -#define ERR_BREAK_MSG(m_cond, m_msg) \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Breaking.", DEBUG_STR(m_msg)); \ - break; \ - } else \ +#define ERR_BREAK_MSG(m_cond, m_msg) \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition \"" _STR(m_cond) "\" is true. Breaking.", m_msg); \ + break; \ + } else \ ((void)0) /** @@ -461,11 +454,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * Ensures `m_cond` is false. * If `m_cond` is true, prints `m_msg` and the application crashes. */ -#define CRASH_COND_MSG(m_cond, m_msg) \ - if (unlikely(m_cond)) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "FATAL: Condition \"" _STR(m_cond) "\" is true.", DEBUG_STR(m_msg)); \ - GENERATE_TRAP(); \ - } else \ +#define CRASH_COND_MSG(m_cond, m_msg) \ + if (unlikely(m_cond)) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "FATAL: Condition \"" _STR(m_cond) "\" is true.", m_msg); \ + GENERATE_TRAP(); \ + } else \ ((void)0) // Generic error macros. @@ -490,11 +483,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * * Prints `m_msg`, and the current function returns. */ -#define ERR_FAIL_MSG(m_msg) \ - if (true) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/function failed.", DEBUG_STR(m_msg)); \ - return; \ - } else \ +#define ERR_FAIL_MSG(m_msg) \ + if (true) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/function failed.", m_msg); \ + return; \ + } else \ ((void)0) /** @@ -517,11 +510,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * * Prints `m_msg`, and the current function returns `m_retval`. */ -#define ERR_FAIL_V_MSG(m_retval, m_msg) \ - if (true) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/function failed. Returning: " _STR(m_retval), DEBUG_STR(m_msg)); \ - return m_retval; \ - } else \ +#define ERR_FAIL_V_MSG(m_retval, m_msg) \ + if (true) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/function failed. Returning: " _STR(m_retval), m_msg); \ + return m_retval; \ + } else \ ((void)0) /** @@ -590,14 +583,14 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li /** * Warns that the current function is deprecated and prints `m_msg`. */ -#define WARN_DEPRECATED_MSG(m_msg) \ - if (true) { \ - static SafeFlag warning_shown; \ - if (!warning_shown.is_set()) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "This method has been deprecated and will be removed in the future.", DEBUG_STR(m_msg), ERR_HANDLER_WARNING); \ - warning_shown.set(); \ - } \ - } else \ +#define WARN_DEPRECATED_MSG(m_msg) \ + if (true) { \ + static SafeFlag warning_shown; \ + if (!warning_shown.is_set()) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "This method has been deprecated and will be removed in the future.", m_msg, ERR_HANDLER_WARNING); \ + warning_shown.set(); \ + } \ + } else \ ((void)0) /** @@ -618,11 +611,11 @@ void _err_print_index_error(const char *p_function, const char *p_file, int p_li * * Prints `m_msg`, and then the application crashes. */ -#define CRASH_NOW_MSG(m_msg) \ - if (true) { \ - _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "FATAL: Method/function failed.", DEBUG_STR(m_msg)); \ - GENERATE_TRAP(); \ - } else \ +#define CRASH_NOW_MSG(m_msg) \ + if (true) { \ + _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "FATAL: Method/function failed.", m_msg); \ + GENERATE_TRAP(); \ + } else \ ((void)0) #endif // ERROR_MACROS_H diff --git a/core/extension/native_extension.cpp b/core/extension/native_extension.cpp index 635e53fa9c..a6b0a708c3 100644 --- a/core/extension/native_extension.cpp +++ b/core/extension/native_extension.cpp @@ -35,7 +35,9 @@ #include "core/object/method_bind.h" #include "core/os/os.h" -const char *NativeExtension::EXTENSION_LIST_CONFIG_FILE = "res://.godot/extension_list.cfg"; +String NativeExtension::get_extension_list_config_file() { + return ProjectSettings::get_singleton()->get_project_data_path().plus_file("extension_list.cfg"); +} class NativeExtensionMethodBind : public MethodBind { GDNativeExtensionClassMethodCall call_func; diff --git a/core/extension/native_extension.h b/core/extension/native_extension.h index 52e869ad4d..f7f235d8fc 100644 --- a/core/extension/native_extension.h +++ b/core/extension/native_extension.h @@ -62,7 +62,7 @@ protected: static void _bind_methods(); public: - static const char *EXTENSION_LIST_CONFIG_FILE; + static String get_extension_list_config_file(); Error open_library(const String &p_path, const String &p_entry_symbol); void close_library(); diff --git a/core/extension/native_extension_manager.cpp b/core/extension/native_extension_manager.cpp index 4eac5249c9..c8755250d5 100644 --- a/core/extension/native_extension_manager.cpp +++ b/core/extension/native_extension_manager.cpp @@ -112,7 +112,7 @@ void NativeExtensionManager::deinitialize_extensions(NativeExtension::Initializa } void NativeExtensionManager::load_extensions() { - FileAccessRef f = FileAccess::open(NativeExtension::EXTENSION_LIST_CONFIG_FILE, FileAccess::READ); + FileAccessRef f = FileAccess::open(NativeExtension::get_extension_list_config_file(), FileAccess::READ); while (f && !f->eof_reached()) { String s = f->get_line().strip_edges(); if (s != String()) { diff --git a/core/input/input.cpp b/core/input/input.cpp index 05b02408a1..f9a361c761 100644 --- a/core/input/input.cpp +++ b/core/input/input.cpp @@ -35,10 +35,6 @@ #include "core/input/input_map.h" #include "core/os/os.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" -#endif - static const char *_joy_buttons[JOY_BUTTON_SDL_MAX] = { "a", "b", @@ -162,9 +158,6 @@ void Input::_bind_methods() { } void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { -#ifdef TOOLS_ENABLED - const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\""; - String pf = p_function; if (p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released" || @@ -179,10 +172,9 @@ void Input::get_argument_options(const StringName &p_function, int p_idx, List<S } String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length()); - r_options->push_back(name.quote(quote_style)); + r_options->push_back(name.quote()); } } -#endif } void Input::SpeedTrack::update(const Vector2 &p_delta_p) { diff --git a/core/io/resource_importer.cpp b/core/io/resource_importer.cpp index 1e166015b0..cd44c537a8 100644 --- a/core/io/resource_importer.cpp +++ b/core/io/resource_importer.cpp @@ -418,7 +418,7 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const St } String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const { - return ProjectSettings::IMPORTED_FILES_PATH.plus_file(p_for_file.get_file() + "-" + p_for_file.md5_text()); + return ProjectSettings::get_singleton()->get_imported_files_path().plus_file(p_for_file.get_file() + "-" + p_for_file.md5_text()); } bool ResourceFormatImporter::are_import_settings_valid(const String &p_path) const { diff --git a/core/io/resource_uid.cpp b/core/io/resource_uid.cpp index 290a71043c..b7d01712ff 100644 --- a/core/io/resource_uid.cpp +++ b/core/io/resource_uid.cpp @@ -29,6 +29,8 @@ /*************************************************************************/ #include "resource_uid.h" + +#include "core/config/project_settings.h" #include "core/crypto/crypto.h" #include "core/io/dir_access.h" #include "core/io/file_access.h" @@ -36,7 +38,9 @@ static constexpr uint32_t char_count = ('z' - 'a'); static constexpr uint32_t base = char_count + ('9' - '0'); -const char *ResourceUID::CACHE_FILE = "res://.godot/uid_cache.bin"; +String ResourceUID::get_cache_file() { + return ProjectSettings::get_singleton()->get_project_data_path().plus_file("uid_cache.bin"); +} String ResourceUID::id_to_text(ID p_id) const { if (p_id < 0) { @@ -135,12 +139,13 @@ void ResourceUID::remove_id(ID p_id) { } Error ResourceUID::save_to_cache() { - if (!FileAccess::exists(CACHE_FILE)) { + String cache_file = get_cache_file(); + if (!FileAccess::exists(cache_file)) { DirAccessRef d = DirAccess::create(DirAccess::ACCESS_RESOURCES); - d->make_dir_recursive(String(CACHE_FILE).get_base_dir()); //ensure base dir exists + d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists } - FileAccessRef f = FileAccess::open(CACHE_FILE, FileAccess::WRITE); + FileAccessRef f = FileAccess::open(cache_file, FileAccess::WRITE); if (!f) { return ERR_CANT_OPEN; } @@ -164,7 +169,7 @@ Error ResourceUID::save_to_cache() { } Error ResourceUID::load_from_cache() { - FileAccessRef f = FileAccess::open(CACHE_FILE, FileAccess::READ); + FileAccessRef f = FileAccess::open(get_cache_file(), FileAccess::READ); if (!f) { return ERR_CANT_OPEN; } @@ -206,7 +211,7 @@ Error ResourceUID::update_cache() { for (OrderedHashMap<ID, Cache>::Element E = unique_ids.front(); E; E = E.next()) { if (!E.get().saved_to_cache) { if (f == nullptr) { - f = FileAccess::open(CACHE_FILE, FileAccess::READ_WRITE); //append + f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); //append if (!f) { return ERR_CANT_OPEN; } diff --git a/core/io/resource_uid.h b/core/io/resource_uid.h index b12138425a..2f1bfdf243 100644 --- a/core/io/resource_uid.h +++ b/core/io/resource_uid.h @@ -44,7 +44,7 @@ public: INVALID_ID = -1 }; - static const char *CACHE_FILE; + static String get_cache_file(); private: mutable Ref<Crypto> crypto; diff --git a/core/object/class_db.cpp b/core/object/class_db.cpp index 8ba46e49eb..d5509c50f1 100644 --- a/core/object/class_db.cpp +++ b/core/object/class_db.cpp @@ -529,7 +529,7 @@ Object *ClassDB::instantiate(const StringName &p_class) { } ERR_FAIL_COND_V_MSG(!ti, nullptr, "Cannot get class '" + String(p_class) + "'."); ERR_FAIL_COND_V_MSG(ti->disabled, nullptr, "Class '" + String(p_class) + "' is disabled."); - ERR_FAIL_COND_V(!ti->creation_func, nullptr); + ERR_FAIL_COND_V_MSG(!ti->creation_func, nullptr, "Class '" + String(p_class) + "' or its base class cannot be instantiated."); } #ifdef TOOLS_ENABLED if (ti->api == API_EDITOR && !Engine::get_singleton()->is_editor_hint()) { diff --git a/core/os/os.cpp b/core/os/os.cpp index 69366f688c..12f85858c3 100644 --- a/core/os/os.cpp +++ b/core/os/os.cpp @@ -36,7 +36,6 @@ #include "core/io/file_access.h" #include "core/os/midi_driver.h" #include "core/version_generated.gen.h" -#include "servers/audio_server.h" #include <stdarg.h> diff --git a/core/string/translation.cpp b/core/string/translation.cpp index 5e3b8297aa..cf61467d08 100644 --- a/core/string/translation.cpp +++ b/core/string/translation.cpp @@ -35,7 +35,6 @@ #include "core/os/os.h" #ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" #include "main/main.h" #endif @@ -810,9 +809,12 @@ static const char *locale_names[] = { // - https://msdn.microsoft.com/en-us/library/windows/desktop/ms693062(v=vs.85).aspx static const char *locale_renames[][2] = { - { "in", "id" }, // Indonesian - { "iw", "he" }, // Hebrew - { "no", "nb" }, // Norwegian BokmÃ¥l + { "in", "id" }, // Indonesian + { "iw", "he" }, // Hebrew + { "no", "nb" }, // Norwegian BokmÃ¥l + { "C", "en" }, // "C" is the simple/default/untranslated Computer locale. + // ASCII-only, English, no currency symbols. Godot treats this as "en". + // See https://unix.stackexchange.com/a/87763/164141 "The C locale is"... { nullptr, nullptr } }; diff --git a/core/string/ustring.h b/core/string/ustring.h index 24da6b82af..1d80ccf58d 100644 --- a/core/string/ustring.h +++ b/core/string/ustring.h @@ -51,11 +51,15 @@ class CharProxy { CowData<T> &_cowdata; static const T _null = 0; - _FORCE_INLINE_ CharProxy(const int &p_index, CowData<T> &cowdata) : + _FORCE_INLINE_ CharProxy(const int &p_index, CowData<T> &p_cowdata) : _index(p_index), - _cowdata(cowdata) {} + _cowdata(p_cowdata) {} public: + _FORCE_INLINE_ CharProxy(const CharProxy<T> &p_other) : + _index(p_other._index), + _cowdata(p_other._cowdata) {} + _FORCE_INLINE_ operator T() const { if (unlikely(_index == _cowdata.size())) { return _null; @@ -68,12 +72,12 @@ public: return _cowdata.ptr() + _index; } - _FORCE_INLINE_ void operator=(const T &other) const { - _cowdata.set(_index, other); + _FORCE_INLINE_ void operator=(const T &p_other) const { + _cowdata.set(_index, p_other); } - _FORCE_INLINE_ void operator=(const CharProxy<T> &other) const { - _cowdata.set(_index, other.operator T()); + _FORCE_INLINE_ void operator=(const CharProxy<T> &p_other) const { + _cowdata.set(_index, p_other.operator T()); } }; diff --git a/core/variant/variant_parser.cpp b/core/variant/variant_parser.cpp index a214a238a6..221a8c4f98 100644 --- a/core/variant/variant_parser.cpp +++ b/core/variant/variant_parser.cpp @@ -90,6 +90,17 @@ const char *VariantParser::tk_name[TK_MAX] = { "ERROR" }; +static double stor_fix(const String &p_str) { + if (p_str == "inf") { + return INFINITY; + } else if (p_str == "inf_neg") { + return -INFINITY; + } else if (p_str == "nan") { + return NAN; + } + return -1; +} + Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, String &r_err_str) { bool string_name = false; @@ -469,8 +480,19 @@ Error VariantParser::_parse_construct(Stream *p_stream, Vector<T> &r_construct, if (first && token.type == TK_PARENTHESIS_CLOSE) { break; } else if (token.type != TK_NUMBER) { - r_err_str = "Expected float in constructor"; - return ERR_PARSE_ERROR; + bool valid = false; + if (token.type == TK_IDENTIFIER) { + double real = stor_fix(token.value); + if (real != -1) { + token.type = TK_NUMBER; + token.value = real; + valid = true; + } + } + if (!valid) { + r_err_str = "Expected float in constructor"; + return ERR_PARSE_ERROR; + } } r_construct.push_back(token.value); @@ -507,6 +529,8 @@ Error VariantParser::parse_value(Token &token, Variant &value, Stream *p_stream, value = Variant(); } else if (id == "inf") { value = INFINITY; + } else if (id == "inf_neg") { + value = -INFINITY; } else if (id == "nan") { value = NAN; } else if (id == "Vector2") { @@ -1401,11 +1425,19 @@ Error VariantParser::parse(Stream *p_stream, Variant &r_ret, String &r_err_str, ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////// -static String rtosfix(double p_value) { +static String rtos_fix(double p_value) { if (p_value == 0.0) { return "0"; //avoid negative zero (-0) being written, which may annoy git, svn, etc. for changes when they don't exist. + } else if (isnan(p_value)) { + return "nan"; + } else if (isinf(p_value)) { + if (p_value > 0) { + return "inf"; + } else { + return "inf_neg"; + } } else { return rtoss(p_value); } @@ -1423,8 +1455,8 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str p_store_string_func(p_store_string_ud, itos(p_variant.operator int64_t())); } break; case Variant::FLOAT: { - String s = rtosfix(p_variant.operator double()); - if (s != "inf" && s != "nan") { + String s = rtos_fix(p_variant.operator double()); + if (s != "inf" && s != "inf_neg" && s != "nan") { if (s.find(".") == -1 && s.find("e") == -1) { s += ".0"; } @@ -1439,7 +1471,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str } break; case Variant::VECTOR2: { Vector2 v = p_variant; - p_store_string_func(p_store_string_ud, "Vector2(" + rtosfix(v.x) + ", " + rtosfix(v.y) + ")"); + p_store_string_func(p_store_string_ud, "Vector2(" + rtos_fix(v.x) + ", " + rtos_fix(v.y) + ")"); } break; case Variant::VECTOR2I: { Vector2i v = p_variant; @@ -1447,7 +1479,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str } break; case Variant::RECT2: { Rect2 aabb = p_variant; - p_store_string_func(p_store_string_ud, "Rect2(" + rtosfix(aabb.position.x) + ", " + rtosfix(aabb.position.y) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + ")"); + p_store_string_func(p_store_string_ud, "Rect2(" + rtos_fix(aabb.position.x) + ", " + rtos_fix(aabb.position.y) + ", " + rtos_fix(aabb.size.x) + ", " + rtos_fix(aabb.size.y) + ")"); } break; case Variant::RECT2I: { @@ -1457,7 +1489,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str } break; case Variant::VECTOR3: { Vector3 v = p_variant; - p_store_string_func(p_store_string_ud, "Vector3(" + rtosfix(v.x) + ", " + rtosfix(v.y) + ", " + rtosfix(v.z) + ")"); + p_store_string_func(p_store_string_ud, "Vector3(" + rtos_fix(v.x) + ", " + rtos_fix(v.y) + ", " + rtos_fix(v.z) + ")"); } break; case Variant::VECTOR3I: { Vector3i v = p_variant; @@ -1465,17 +1497,17 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str } break; case Variant::PLANE: { Plane p = p_variant; - p_store_string_func(p_store_string_ud, "Plane(" + rtosfix(p.normal.x) + ", " + rtosfix(p.normal.y) + ", " + rtosfix(p.normal.z) + ", " + rtosfix(p.d) + ")"); + p_store_string_func(p_store_string_ud, "Plane(" + rtos_fix(p.normal.x) + ", " + rtos_fix(p.normal.y) + ", " + rtos_fix(p.normal.z) + ", " + rtos_fix(p.d) + ")"); } break; case Variant::AABB: { AABB aabb = p_variant; - p_store_string_func(p_store_string_ud, "AABB(" + rtosfix(aabb.position.x) + ", " + rtosfix(aabb.position.y) + ", " + rtosfix(aabb.position.z) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + ", " + rtosfix(aabb.size.z) + ")"); + p_store_string_func(p_store_string_ud, "AABB(" + rtos_fix(aabb.position.x) + ", " + rtos_fix(aabb.position.y) + ", " + rtos_fix(aabb.position.z) + ", " + rtos_fix(aabb.size.x) + ", " + rtos_fix(aabb.size.y) + ", " + rtos_fix(aabb.size.z) + ")"); } break; case Variant::QUATERNION: { Quaternion quaternion = p_variant; - p_store_string_func(p_store_string_ud, "Quaternion(" + rtosfix(quaternion.x) + ", " + rtosfix(quaternion.y) + ", " + rtosfix(quaternion.z) + ", " + rtosfix(quaternion.w) + ")"); + p_store_string_func(p_store_string_ud, "Quaternion(" + rtos_fix(quaternion.x) + ", " + rtos_fix(quaternion.y) + ", " + rtos_fix(quaternion.z) + ", " + rtos_fix(quaternion.w) + ")"); } break; case Variant::TRANSFORM2D: { @@ -1486,7 +1518,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i != 0 || j != 0) { s += ", "; } - s += rtosfix(m3.elements[i][j]); + s += rtos_fix(m3.elements[i][j]); } } @@ -1501,7 +1533,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i != 0 || j != 0) { s += ", "; } - s += rtosfix(m3.elements[i][j]); + s += rtos_fix(m3.elements[i][j]); } } @@ -1517,11 +1549,11 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i != 0 || j != 0) { s += ", "; } - s += rtosfix(m3.elements[i][j]); + s += rtos_fix(m3.elements[i][j]); } } - s = s + ", " + rtosfix(t.origin.x) + ", " + rtosfix(t.origin.y) + ", " + rtosfix(t.origin.z); + s = s + ", " + rtos_fix(t.origin.x) + ", " + rtos_fix(t.origin.y) + ", " + rtos_fix(t.origin.z); p_store_string_func(p_store_string_ud, s + ")"); } break; @@ -1529,7 +1561,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str // misc types case Variant::COLOR: { Color c = p_variant; - p_store_string_func(p_store_string_ud, "Color(" + rtosfix(c.r) + ", " + rtosfix(c.g) + ", " + rtosfix(c.b) + ", " + rtosfix(c.a) + ")"); + p_store_string_func(p_store_string_ud, "Color(" + rtos_fix(c.r) + ", " + rtos_fix(c.g) + ", " + rtos_fix(c.b) + ", " + rtos_fix(c.a) + ")"); } break; case Variant::STRING_NAME: { @@ -1707,7 +1739,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i > 0) { p_store_string_func(p_store_string_ud, ", "); } - p_store_string_func(p_store_string_ud, rtosfix(ptr[i])); + p_store_string_func(p_store_string_ud, rtos_fix(ptr[i])); } p_store_string_func(p_store_string_ud, ")"); @@ -1723,7 +1755,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i > 0) { p_store_string_func(p_store_string_ud, ", "); } - p_store_string_func(p_store_string_ud, rtosfix(ptr[i])); + p_store_string_func(p_store_string_ud, rtos_fix(ptr[i])); } p_store_string_func(p_store_string_ud, ")"); @@ -1759,7 +1791,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i > 0) { p_store_string_func(p_store_string_ud, ", "); } - p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y)); + p_store_string_func(p_store_string_ud, rtos_fix(ptr[i].x) + ", " + rtos_fix(ptr[i].y)); } p_store_string_func(p_store_string_ud, ")"); @@ -1775,7 +1807,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str if (i > 0) { p_store_string_func(p_store_string_ud, ", "); } - p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y) + ", " + rtosfix(ptr[i].z)); + p_store_string_func(p_store_string_ud, rtos_fix(ptr[i].x) + ", " + rtos_fix(ptr[i].y) + ", " + rtos_fix(ptr[i].z)); } p_store_string_func(p_store_string_ud, ")"); @@ -1792,7 +1824,7 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str p_store_string_func(p_store_string_ud, ", "); } - p_store_string_func(p_store_string_ud, rtosfix(ptr[i].r) + ", " + rtosfix(ptr[i].g) + ", " + rtosfix(ptr[i].b) + ", " + rtosfix(ptr[i].a)); + p_store_string_func(p_store_string_ud, rtos_fix(ptr[i].r) + ", " + rtos_fix(ptr[i].g) + ", " + rtos_fix(ptr[i].b) + ", " + rtos_fix(ptr[i].a)); } p_store_string_func(p_store_string_ud, ")"); diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index 5d45947a19..4b710d5f12 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -838,7 +838,7 @@ [codeblock] sqrt(9) # Returns 3 [/codeblock] - [b]Note:[/b]Negative values of [code]x[/code] return NaN. If you need negative inputs, use [code]System.Numerics.Complex[/code] in C#. + [b]Note:[/b] Negative values of [code]x[/code] return NaN. If you need negative inputs, use [code]System.Numerics.Complex[/code] in C#. </description> </method> <method name="step_decimals"> @@ -2340,7 +2340,7 @@ hint_string = "%s/%s:Resource" % [TYPE_OBJECT, TYPE_OBJECT] # Array of resources. hint_string = "%s:%s/%s:Resource" % [TYPE_ARRAY, TYPE_OBJECT, TYPE_OBJECT] # Two-dimensional array of resources. [/codeblock] - [b]Note:[/b] the final colon is required to specify for properly detecting built-in types. + [b]Note:[/b] The final colon is required to specify for properly detecting built-in types. </constant> <constant name="PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE" value="26" enum="PropertyHint"> </constant> diff --git a/doc/classes/AABB.xml b/doc/classes/AABB.xml index 5d18f69409..1be6d5a440 100644 --- a/doc/classes/AABB.xml +++ b/doc/classes/AABB.xml @@ -9,7 +9,7 @@ [b]Note:[/b] Unlike [Rect2], [AABB] does not have a variant that uses integer coordinates. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="Advanced vector math">https://docs.godotengine.org/en/latest/tutorials/math/vectors_advanced.html</link> </tutorials> diff --git a/doc/classes/AESContext.xml b/doc/classes/AESContext.xml index 847d1226a2..8c390155ee 100644 --- a/doc/classes/AESContext.xml +++ b/doc/classes/AESContext.xml @@ -89,7 +89,7 @@ <return type="PackedByteArray" /> <description> Get the current IV state for this context (IV gets updated when calling [method update]). You normally don't need this function. - Note: This function only makes sense when the context is started with [constant MODE_CBC_ENCRYPT] or [constant MODE_CBC_DECRYPT]. + [b]Note:[/b] This function only makes sense when the context is started with [constant MODE_CBC_ENCRYPT] or [constant MODE_CBC_DECRYPT]. </description> </method> <method name="start"> @@ -106,7 +106,7 @@ <argument index="0" name="src" type="PackedByteArray" /> <description> Run the desired operation for this AES context. Will return a [PackedByteArray] containing the result of encrypting (or decrypting) the given [code]src[/code]. See [method start] for mode of operation. - Note: The size of [code]src[/code] must be a multiple of 16. Apply some padding if needed. + [b]Note:[/b] The size of [code]src[/code] must be a multiple of 16. Apply some padding if needed. </description> </method> </methods> diff --git a/doc/classes/Animation.xml b/doc/classes/Animation.xml index 38e02745d4..d2ecbdde26 100644 --- a/doc/classes/Animation.xml +++ b/doc/classes/Animation.xml @@ -28,7 +28,7 @@ Animations are just data containers, and must be added to nodes such as an [AnimationPlayer] to be played back. Animation tracks have different types, each with its own set of dedicated methods. Check [enum TrackType] to see available types. </description> <tutorials> - <link title="Animation tutorial index">https://docs.godotengine.org/en/latest/tutorials/animation/index.html</link> + <link title="Animation documentation index">https://docs.godotengine.org/en/latest/tutorials/animation/index.html</link> </tutorials> <methods> <method name="add_track"> diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml index 1ef9d81d02..2fd923df85 100644 --- a/doc/classes/AnimationPlayer.xml +++ b/doc/classes/AnimationPlayer.xml @@ -10,7 +10,7 @@ </description> <tutorials> <link title="2D Sprite animation">https://docs.godotengine.org/en/latest/tutorials/2d/2d_sprite_animation.html</link> - <link title="Animation tutorial index">https://docs.godotengine.org/en/latest/tutorials/animation/index.html</link> + <link title="Animation documentation index">https://docs.godotengine.org/en/latest/tutorials/animation/index.html</link> <link title="Third Person Shooter Demo">https://godotengine.org/asset-library/asset/678</link> </tutorials> <methods> @@ -188,7 +188,7 @@ </member> <member name="current_animation" type="String" setter="set_current_animation" getter="get_current_animation" default=""""> The name of the currently playing animation. If no animation is playing, the property's value is an empty string. Changing this value does not restart the animation. See [method play] for more information on playing animations. - [b]Note[/b]: while this property appears in the inspector, it's not meant to be edited, and it's not saved in the scene. This property is mainly used to get the currently playing animation, and internally for animation playback tracks. For more information, see [Animation]. + [b]Note:[/b] while this property appears in the inspector, it's not meant to be edited, and it's not saved in the scene. This property is mainly used to get the currently playing animation, and internally for animation playback tracks. For more information, see [Animation]. </member> <member name="current_animation_length" type="float" setter="" getter="get_current_animation_length"> The length (in seconds) of the currently being played animation. diff --git a/doc/classes/AnimationTree.xml b/doc/classes/AnimationTree.xml index 843dd5a6d1..3d112e258e 100644 --- a/doc/classes/AnimationTree.xml +++ b/doc/classes/AnimationTree.xml @@ -4,7 +4,8 @@ A node to be used for advanced animation transitions in an [AnimationPlayer]. </brief_description> <description> - Note: When linked with an [AnimationPlayer], several properties and methods of the corresponding [AnimationPlayer] will not function as expected. Playback and transitions should be handled using only the [AnimationTree] and its constituent [AnimationNode](s). The [AnimationPlayer] node should be used solely for adding, deleting, and editing animations. + A node to be used for advanced animation transitions in an [AnimationPlayer]. + [b]Note:[/b] When linked with an [AnimationPlayer], several properties and methods of the corresponding [AnimationPlayer] will not function as expected. Playback and transitions should be handled using only the [AnimationTree] and its constituent [AnimationNode](s). The [AnimationPlayer] node should be used solely for adding, deleting, and editing animations. </description> <tutorials> <link title="Using AnimationTree">https://docs.godotengine.org/en/latest/tutorials/animation/animation_tree.html</link> diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index 44e27643bb..8898a59036 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -530,7 +530,7 @@ <argument index="0" name="func" type="Callable" /> <description> Sorts the array using a custom method. The custom method receives two arguments (a pair of elements from the array) and must return either [code]true[/code] or [code]false[/code]. For two elements [code]a[/code] and [code]b[/code], if the given method returns [code]true[/code], element [code]b[/code] will be after element [code]a[/code] in the array. - [b]Note:[/b] you cannot randomize the return value as the heapsort algorithm expects a deterministic result. Doing so will result in unexpected behavior. + [b]Note:[/b] You cannot randomize the return value as the heapsort algorithm expects a deterministic result. Doing so will result in unexpected behavior. [codeblocks] [gdscript] class MyCustomSorter: diff --git a/doc/classes/ArrayMesh.xml b/doc/classes/ArrayMesh.xml index 49ce2588c5..7b77462322 100644 --- a/doc/classes/ArrayMesh.xml +++ b/doc/classes/ArrayMesh.xml @@ -47,7 +47,7 @@ [b]Note:[/b] Godot uses clockwise [url=https://learnopengl.com/Advanced-OpenGL/Face-culling]winding order[/url] for front faces of triangle primitive modes. </description> <tutorials> - <link title="Procedural geometry using the ArrayMesh">https://docs.godotengine.org/en/latest/tutorials/content/procedural_geometry/arraymesh.html</link> + <link title="Procedural geometry using the ArrayMesh">https://docs.godotengine.org/en/latest/tutorials/3d/procedural_geometry/arraymesh.html</link> </tutorials> <methods> <method name="add_blend_shape"> diff --git a/doc/classes/BaseMaterial3D.xml b/doc/classes/BaseMaterial3D.xml index 84ed0de42d..818ab50030 100644 --- a/doc/classes/BaseMaterial3D.xml +++ b/doc/classes/BaseMaterial3D.xml @@ -7,7 +7,7 @@ This provides a default material with a wide variety of rendering features and properties without the need to write shader code. See the tutorial below for details. </description> <tutorials> - <link title="Spatial material">https://docs.godotengine.org/en/latest/tutorials/3d/spatial_material.html</link> + <link title="Standard Material 3D">https://docs.godotengine.org/en/latest/tutorials/3d/standard_material_3d.html</link> </tutorials> <methods> <method name="get_feature" qualifiers="const"> @@ -232,7 +232,7 @@ </member> <member name="metallic_specular" type="float" setter="set_specular" getter="get_specular" default="0.5"> Sets the size of the specular lobe. The specular lobe is the bright spot that is reflected from light sources. - [b]Note:[/b] unlike [member metallic], this is not energy-conserving, so it should be left at [code]0.5[/code] in most cases. See also [member roughness]. + [b]Note:[/b] Unlike [member metallic], this is not energy-conserving, so it should be left at [code]0.5[/code] in most cases. See also [member roughness]. </member> <member name="metallic_texture" type="Texture2D" setter="set_texture" getter="get_texture"> Texture used to specify metallic for an object. This is multiplied by [member metallic]. @@ -352,7 +352,7 @@ </member> <member name="use_point_size" type="bool" setter="set_flag" getter="get_flag" default="false"> If [code]true[/code], render point size can be changed. - [b]Note:[/b] this is only effective for objects whose geometry is point-based rather than triangle-based. See also [member point_size]. + [b]Note:[/b] This is only effective for objects whose geometry is point-based rather than triangle-based. See also [member point_size]. </member> <member name="uv1_offset" type="Vector3" setter="set_uv1_offset" getter="get_uv1_offset" default="Vector3(0, 0, 0)"> How much to offset the [code]UV[/code] coordinates. This amount will be added to [code]UV[/code] in the vertex function. This can be used to offset a texture. diff --git a/doc/classes/Basis.xml b/doc/classes/Basis.xml index 63df5c40b2..7f0d4cbbe3 100644 --- a/doc/classes/Basis.xml +++ b/doc/classes/Basis.xml @@ -10,7 +10,7 @@ For more information, read the "Matrices and transforms" documentation article. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Matrices and transforms">https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html</link> <link title="Using 3D transforms">https://docs.godotengine.org/en/latest/tutorials/3d/using_transforms.html</link> <link title="Matrix Transform Demo">https://godotengine.org/asset-library/asset/584</link> diff --git a/doc/classes/Camera3D.xml b/doc/classes/Camera3D.xml index cd17a31e23..06e2f83f05 100644 --- a/doc/classes/Camera3D.xml +++ b/doc/classes/Camera3D.xml @@ -26,7 +26,7 @@ <method name="get_camera_transform" qualifiers="const"> <return type="Transform3D" /> <description> - Returns the transform of the camera plus the vertical ([member v_offset]) and horizontal ([member h_offset]) offsets; and any other adjustments made to the position and orientation of the camera by subclassed cameras such as [ClippedCamera3D] and [XRCamera3D]. + Returns the transform of the camera plus the vertical ([member v_offset]) and horizontal ([member h_offset]) offsets; and any other adjustments made to the position and orientation of the camera by subclassed cameras such as [XRCamera3D]. </description> </method> <method name="get_cull_mask_value" qualifiers="const"> @@ -42,6 +42,12 @@ Returns the camera's frustum planes in world space units as an array of [Plane]s in the following order: near, far, left, top, right, bottom. Not to be confused with [member frustum_offset]. </description> </method> + <method name="get_pyramid_shape_rid"> + <return type="RID" /> + <description> + Returns the RID of a pyramid shape encompassing the camera's view frustum, ignoring the camera's near plane. The tip of the pyramid represents the position of the camera. + </description> + </method> <method name="is_position_behind" qualifiers="const"> <return type="bool" /> <argument index="0" name="world_point" type="Vector3" /> diff --git a/doc/classes/CharFXTransform.xml b/doc/classes/CharFXTransform.xml index b00031edf6..2d8e7817c1 100644 --- a/doc/classes/CharFXTransform.xml +++ b/doc/classes/CharFXTransform.xml @@ -7,7 +7,7 @@ By setting various properties on this object, you can control how individual characters will be displayed in a [RichTextEffect]. </description> <tutorials> - <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/gui/bbcode_in_richtextlabel.html</link> + <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/ui/bbcode_in_richtextlabel.html</link> <link title="RichTextEffect test project (third-party)">https://github.com/Eoin-ONeill-Yokai/Godot-Rich-Text-Effect-Test-Project</link> </tutorials> <members> diff --git a/doc/classes/ClassDB.xml b/doc/classes/ClassDB.xml index 5f39fc48e0..b4f98c6c5f 100644 --- a/doc/classes/ClassDB.xml +++ b/doc/classes/ClassDB.xml @@ -78,7 +78,7 @@ <argument index="1" name="no_inheritance" type="bool" default="false" /> <description> Returns an array with all the methods of [code]class[/code] or its ancestry if [code]no_inheritance[/code] is [code]false[/code]. Every element of the array is a [Dictionary] with the following keys: [code]args[/code], [code]default_args[/code], [code]flags[/code], [code]id[/code], [code]name[/code], [code]return: (class_name, hint, hint_string, name, type, usage)[/code]. - [b]Note:[/code] In exported release builds the debug info is not available, so the returned dictionaries will contain only method names. + [b]Note:[/b] In exported release builds the debug info is not available, so the returned dictionaries will contain only method names. </description> </method> <method name="class_get_property" qualifiers="const"> diff --git a/doc/classes/ClippedCamera3D.xml b/doc/classes/ClippedCamera3D.xml deleted file mode 100644 index 1a0d3499cd..0000000000 --- a/doc/classes/ClippedCamera3D.xml +++ /dev/null @@ -1,93 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="ClippedCamera3D" inherits="Camera3D" version="4.0"> - <brief_description> - A [Camera3D] that includes collision. - </brief_description> - <description> - This node extends [Camera3D] to add collisions with [Area3D] and/or [PhysicsBody3D] nodes. The camera cannot move through colliding objects. - </description> - <tutorials> - </tutorials> - <methods> - <method name="add_exception"> - <return type="void" /> - <argument index="0" name="node" type="Object" /> - <description> - Adds a collision exception so the camera does not collide with the specified node. - </description> - </method> - <method name="add_exception_rid"> - <return type="void" /> - <argument index="0" name="rid" type="RID" /> - <description> - Adds a collision exception so the camera does not collide with the specified [RID]. - </description> - </method> - <method name="clear_exceptions"> - <return type="void" /> - <description> - Removes all collision exceptions. - </description> - </method> - <method name="get_clip_offset" qualifiers="const"> - <return type="float" /> - <description> - Returns the distance the camera has been offset due to a collision. - </description> - </method> - <method name="get_collision_mask_value" qualifiers="const"> - <return type="bool" /> - <argument index="0" name="layer_number" type="int" /> - <description> - Returns whether or not the specified layer of the [member collision_mask] is enabled, given a [code]layer_number[/code] between 1 and 32. - </description> - </method> - <method name="remove_exception"> - <return type="void" /> - <argument index="0" name="node" type="Object" /> - <description> - Removes a collision exception with the specified node. - </description> - </method> - <method name="remove_exception_rid"> - <return type="void" /> - <argument index="0" name="rid" type="RID" /> - <description> - Removes a collision exception with the specified [RID]. - </description> - </method> - <method name="set_collision_mask_value"> - <return type="void" /> - <argument index="0" name="layer_number" type="int" /> - <argument index="1" name="value" type="bool" /> - <description> - Based on [code]value[/code], enables or disables the specified layer in the [member collision_mask], given a [code]layer_number[/code] between 1 and 32. - </description> - </method> - </methods> - <members> - <member name="clip_to_areas" type="bool" setter="set_clip_to_areas" getter="is_clip_to_areas_enabled" default="false"> - If [code]true[/code], the camera stops on contact with [Area3D]s. - </member> - <member name="clip_to_bodies" type="bool" setter="set_clip_to_bodies" getter="is_clip_to_bodies_enabled" default="true"> - If [code]true[/code], the camera stops on contact with [PhysicsBody3D]s. - </member> - <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1"> - The camera's collision mask. Only objects in at least one collision layer matching the mask will be detected. See [url=https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information. - </member> - <member name="margin" type="float" setter="set_margin" getter="get_margin" default="0.0"> - The camera's collision margin. The camera can't get closer than this distance to a colliding object. - </member> - <member name="process_callback" type="int" setter="set_process_callback" getter="get_process_callback" enum="ClippedCamera3D.ClipProcessCallback" default="0"> - The camera's process callback. See [enum ClipProcessCallback]. - </member> - </members> - <constants> - <constant name="CLIP_PROCESS_PHYSICS" value="0" enum="ClipProcessCallback"> - The camera updates with the [code]_physics_process[/code] callback. - </constant> - <constant name="CLIP_PROCESS_IDLE" value="1" enum="ClipProcessCallback"> - The camera updates with the [code]_process[/code] callback. - </constant> - </constants> -</class> diff --git a/doc/classes/CodeEdit.xml b/doc/classes/CodeEdit.xml index d856990ff8..bd1f3af436 100644 --- a/doc/classes/CodeEdit.xml +++ b/doc/classes/CodeEdit.xml @@ -5,7 +5,7 @@ </brief_description> <description> CodeEdit is a specialised [TextEdit] designed for editing plain text code files. It contains a bunch of features commonly found in code editors such as line numbers, line folding, code completion, indent management and string / comment management. - [b]Note[/b]: By default [CodeEdit] always use left-to-right text direction to correctly display source code. + [b]Note:[/b] By default [CodeEdit] always use left-to-right text direction to correctly display source code. </description> <tutorials> </tutorials> @@ -51,7 +51,7 @@ <argument index="5" name="value" type="Variant" default="0" /> <description> Submits an item to the queue of potential candidates for the autocomplete menu. Call [method update_code_completion_options] to update the list. - [b]Note[/b]: This list will replace all current candidates. + [b]Note:[/b] This list will replace all current candidates. </description> </method> <method name="add_comment_delimiter"> @@ -431,7 +431,7 @@ <argument index="0" name="force" type="bool" /> <description> Submits all completion options added with [method add_code_completion_option]. Will try to force the autoccomplete menu to popup, if [code]force[/code] is [code]true[/code]. - [b]Note[/b]: This will replace all current candidates. + [b]Note:[/b] This will replace all current candidates. </description> </method> </methods> diff --git a/doc/classes/ColorPicker.xml b/doc/classes/ColorPicker.xml index f33016cc6c..fca6a7631a 100644 --- a/doc/classes/ColorPicker.xml +++ b/doc/classes/ColorPicker.xml @@ -16,7 +16,7 @@ <argument index="0" name="color" type="Color" /> <description> Adds the given color to a list of color presets. The presets are displayed in the color picker and the user will be able to select them. - [b]Note:[/b] the presets list is only for [i]this[/i] color picker. + [b]Note:[/b] The presets list is only for [i]this[/i] color picker. </description> </method> <method name="erase_preset"> diff --git a/doc/classes/ConcavePolygonShape3D.xml b/doc/classes/ConcavePolygonShape3D.xml index ac569a8992..fbbd0b4876 100644 --- a/doc/classes/ConcavePolygonShape3D.xml +++ b/doc/classes/ConcavePolygonShape3D.xml @@ -5,7 +5,7 @@ </brief_description> <description> Concave polygon shape resource, which can be set into a [PhysicsBody3D] or area. This shape is created by feeding a list of triangles. - Note: when used for collision, [ConcavePolygonShape3D] is intended to work with static [PhysicsBody3D] nodes like [StaticBody3D] and will not work with [CharacterBody3D] or [RigidDynamicBody3D] with a mode other than Static. + [b]Note:[/b] When used for collision, [ConcavePolygonShape3D] is intended to work with static [PhysicsBody3D] nodes like [StaticBody3D] and will not work with [CharacterBody3D] or [RigidDynamicBody3D] with a mode other than Static. </description> <tutorials> <link title="3D Physics Tests Demo">https://godotengine.org/asset-library/asset/675</link> diff --git a/doc/classes/Container.xml b/doc/classes/Container.xml index e78eb8d259..24e73534d3 100644 --- a/doc/classes/Container.xml +++ b/doc/classes/Container.xml @@ -29,6 +29,11 @@ <member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" override="true" enum="Control.MouseFilter" default="1" /> </members> <signals> + <signal name="pre_sort_children"> + <description> + Emitted when children are going to be sorted. + </description> + </signal> <signal name="sort_children"> <description> Emitted when sorting the children is needed. @@ -36,7 +41,10 @@ </signal> </signals> <constants> - <constant name="NOTIFICATION_SORT_CHILDREN" value="50"> + <constant name="NOTIFICATION_PRE_SORT_CHILDREN" value="50"> + Notification just before children are going to be sorted, in case there's something to process beforehand. + </constant> + <constant name="NOTIFICATION_SORT_CHILDREN" value="51"> Notification for when sorting the children, it must be obeyed immediately. </constant> </constants> diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml index b00bf1c250..7c8239977f 100644 --- a/doc/classes/Control.xml +++ b/doc/classes/Control.xml @@ -16,7 +16,7 @@ [b]Note:[/b] Theme items are [i]not[/i] [Object] properties. This means you can't access their values using [method Object.get] and [method Object.set]. Instead, use the [code]get_theme_*[/code] and [code]add_theme_*_override[/code] methods provided by this class. </description> <tutorials> - <link title="GUI tutorial index">https://docs.godotengine.org/en/latest/tutorials/ui/index.html</link> + <link title="GUI documentation index">https://docs.godotengine.org/en/latest/tutorials/ui/index.html</link> <link title="Custom drawing in 2D">https://docs.godotengine.org/en/latest/tutorials/2d/custom_drawing_in_2d.html</link> <link title="Control node gallery">https://docs.godotengine.org/en/latest/tutorials/ui/control_node_gallery.html</link> <link title="All GUI Demos">https://github.com/godotengine/godot-demo-projects/tree/master/gui</link> @@ -458,6 +458,27 @@ See [method get_theme_color] for details. </description> </method> + <method name="get_theme_default_base_scale" qualifiers="const"> + <return type="float" /> + <description> + Returns the default base scale value from the first matching [Theme] in the tree if that [Theme] has a valid [member Theme.default_base_scale] value. + See [method get_theme_color] for details. + </description> + </method> + <method name="get_theme_default_font" qualifiers="const"> + <return type="Font" /> + <description> + Returns the default font from the first matching [Theme] in the tree if that [Theme] has a valid [member Theme.default_font] value. + See [method get_theme_color] for details. + </description> + </method> + <method name="get_theme_default_font_size" qualifiers="const"> + <return type="int" /> + <description> + Returns the default font size value from the first matching [Theme] in the tree if that [Theme] has a valid [member Theme.default_font_size] value. + See [method get_theme_color] for details. + </description> + </method> <method name="get_theme_font" qualifiers="const"> <return type="Font" /> <argument index="0" name="name" type="StringName" /> @@ -1023,7 +1044,7 @@ <member name="rect_scale" type="Vector2" setter="set_scale" getter="get_scale" default="Vector2(1, 1)"> The node's scale, relative to its [member rect_size]. Change this property to scale the node around its [member rect_pivot_offset]. The Control's [member hint_tooltip] will also scale according to this value. [b]Note:[/b] This property is mainly intended to be used for animation purposes. Text inside the Control will look pixelated or blurry when the Control is scaled. To support multiple resolutions in your project, use an appropriate viewport stretch mode as described in the [url=https://docs.godotengine.org/en/latest/tutorials/viewports/multiple_resolutions.html]documentation[/url] instead of scaling Controls individually. - [b]Note:[/b] If the Control node is a child of a [Container] node, the scale will be reset to [code]Vector2(1, 1)[/code] when the scene is instantiated. To set the Control's scale when it's instantiated, wait for one frame using [code]yield(get_tree(), "idle_frame")[/code] then set its [member rect_scale] property. + [b]Note:[/b] If the Control node is a child of a [Container] node, the scale will be reset to [code]Vector2(1, 1)[/code] when the scene is instantiated. To set the Control's scale when it's instantiated, wait for one frame using [code]yield(get_tree(), "process_frame")[/code] then set its [member rect_scale] property. </member> <member name="rect_size" type="Vector2" setter="_set_size" getter="get_size" default="Vector2(0, 0)"> The size of the node's bounding rectangle, in pixels. [Container] nodes update this property automatically. diff --git a/doc/classes/Crypto.xml b/doc/classes/Crypto.xml index a87c8bfab2..04aee347e0 100644 --- a/doc/classes/Crypto.xml +++ b/doc/classes/Crypto.xml @@ -88,7 +88,7 @@ <argument index="1" name="ciphertext" type="PackedByteArray" /> <description> Decrypt the given [code]ciphertext[/code] with the provided private [code]key[/code]. - [b]Note[/b]: The maximum size of accepted ciphertext is limited by the key size. + [b]Note:[/b] The maximum size of accepted ciphertext is limited by the key size. </description> </method> <method name="encrypt"> @@ -97,7 +97,7 @@ <argument index="1" name="plaintext" type="PackedByteArray" /> <description> Encrypt the given [code]plaintext[/code] with the provided public [code]key[/code]. - [b]Note[/b]: The maximum size of accepted plaintext is limited by the key size. + [b]Note:[/b] The maximum size of accepted plaintext is limited by the key size. </description> </method> <method name="generate_random_bytes"> diff --git a/doc/classes/CryptoKey.xml b/doc/classes/CryptoKey.xml index 5665c629a8..111da858ea 100644 --- a/doc/classes/CryptoKey.xml +++ b/doc/classes/CryptoKey.xml @@ -23,7 +23,7 @@ <argument index="1" name="public_only" type="bool" default="false" /> <description> Loads a key from [code]path[/code]. If [code]public_only[/code] is [code]true[/code], only the public key will be loaded. - [b]Note[/b]: [code]path[/code] should be a "*.pub" file if [code]public_only[/code] is [code]true[/code], a "*.key" file otherwise. + [b]Note:[/b] [code]path[/code] should be a "*.pub" file if [code]public_only[/code] is [code]true[/code], a "*.key" file otherwise. </description> </method> <method name="load_from_string"> @@ -40,7 +40,7 @@ <argument index="1" name="public_only" type="bool" default="false" /> <description> Saves a key to the given [code]path[/code]. If [code]public_only[/code] is [code]true[/code], only the public key will be saved. - [b]Note[/b]: [code]path[/code] should be a "*.pub" file if [code]public_only[/code] is [code]true[/code], a "*.key" file otherwise. + [b]Note:[/b] [code]path[/code] should be a "*.pub" file if [code]public_only[/code] is [code]true[/code], a "*.key" file otherwise. </description> </method> <method name="save_to_string"> diff --git a/doc/classes/DTLSServer.xml b/doc/classes/DTLSServer.xml index 16e65eaadf..f98d8813c9 100644 --- a/doc/classes/DTLSServer.xml +++ b/doc/classes/DTLSServer.xml @@ -160,7 +160,7 @@ <argument index="0" name="udp_peer" type="PacketPeerUDP" /> <description> Try to initiate the DTLS handshake with the given [code]udp_peer[/code] which must be already connected (see [method PacketPeerUDP.connect_to_host]). - [b]Note[/b]: You must check that the state of the return PacketPeerUDP is [constant PacketPeerDTLS.STATUS_HANDSHAKING], as it is normal that 50% of the new connections will be invalid due to cookie exchange. + [b]Note:[/b] You must check that the state of the return PacketPeerUDP is [constant PacketPeerDTLS.STATUS_HANDSHAKING], as it is normal that 50% of the new connections will be invalid due to cookie exchange. </description> </method> </methods> diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index adc1eab393..bab1a261ab 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -177,7 +177,7 @@ [b]Note:[/b] When declaring a dictionary with [code]const[/code], the dictionary itself can still be mutated by defining the values of individual keys. Using [code]const[/code] will only prevent assigning the constant with another value after it was initialized. </description> <tutorials> - <link title="GDScript basics: Dictionary">https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/gdscript_basics.html#dictionary</link> + <link title="GDScript basics: Dictionary">https://docs.godotengine.org/en/latest/tutorials/scripting/gdscript/gdscript_basics.html#dictionary</link> <link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link> <link title="OS Test Demo">https://godotengine.org/asset-library/asset/677</link> </tutorials> diff --git a/doc/classes/Directory.xml b/doc/classes/Directory.xml index c8fda27989..93f04ff2a2 100644 --- a/doc/classes/Directory.xml +++ b/doc/classes/Directory.xml @@ -54,7 +54,7 @@ [/codeblocks] </description> <tutorials> - <link title="File system">https://docs.godotengine.org/en/latest/getting_started/step_by_step/filesystem.html</link> + <link title="File system">https://docs.godotengine.org/en/latest/tutorials/scripting/filesystem.html</link> </tutorials> <methods> <method name="change_dir"> diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml index 7eff8db59c..01ca23c217 100644 --- a/doc/classes/DisplayServer.xml +++ b/doc/classes/DisplayServer.xml @@ -556,6 +556,7 @@ <return type="int" enum="DisplayServer.WindowMode" /> <argument index="0" name="window_id" type="int" default="0" /> <description> + Returns the current window's mode. </description> </method> <method name="window_get_position" qualifiers="const"> @@ -666,6 +667,8 @@ <argument index="0" name="mode" type="int" enum="DisplayServer.WindowMode" /> <argument index="1" name="window_id" type="int" default="0" /> <description> + Sets window mode for the given window to [code]mode[/code]. See [enum WindowMode] for possible values and how each mode behaves. + [b]Note:[/b] Setting the window to fullscreen forcibly sets the borderless flag to [code]true[/code], so make sure to set it back to [code]false[/code] when not wanted. </description> </method> <method name="window_set_mouse_passthrough"> diff --git a/doc/classes/EditorPlugin.xml b/doc/classes/EditorPlugin.xml index 93a9cea45e..4aa6963f57 100644 --- a/doc/classes/EditorPlugin.xml +++ b/doc/classes/EditorPlugin.xml @@ -7,7 +7,7 @@ Plugins are used by the editor to extend functionality. The most common types of plugins are those which edit a given node or resource type, import plugins and export plugins. See also [EditorScript] to add functions to the editor. </description> <tutorials> - <link title="Editor plugins tutorial index">https://docs.godotengine.org/en/latest/tutorials/plugins/editor/index.html</link> + <link title="Editor plugins documentation index">https://docs.godotengine.org/en/latest/tutorials/plugins/editor/index.html</link> </tutorials> <methods> <method name="_apply_changes" qualifiers="virtual"> diff --git a/doc/classes/EditorResourcePreview.xml b/doc/classes/EditorResourcePreview.xml index 4dc46945cf..c780045263 100644 --- a/doc/classes/EditorResourcePreview.xml +++ b/doc/classes/EditorResourcePreview.xml @@ -32,7 +32,7 @@ <argument index="3" name="userdata" type="Variant" /> <description> Queue the [code]resource[/code] being edited for preview. Once the preview is ready, the [code]receiver[/code]'s [code]receiver_func[/code] will be called. The [code]receiver_func[/code] must take the following four arguments: [String] path, [Texture2D] preview, [Texture2D] thumbnail_preview, [Variant] userdata. [code]userdata[/code] can be anything, and will be returned when [code]receiver_func[/code] is called. - [b]Note[/b]: If it was not possible to create the preview the [code]receiver_func[/code] will still be called, but the preview will be null. + [b]Note:[/b] If it was not possible to create the preview the [code]receiver_func[/code] will still be called, but the preview will be null. </description> </method> <method name="queue_resource_preview"> @@ -43,7 +43,7 @@ <argument index="3" name="userdata" type="Variant" /> <description> Queue a resource file located at [code]path[/code] for preview. Once the preview is ready, the [code]receiver[/code]'s [code]receiver_func[/code] will be called. The [code]receiver_func[/code] must take the following four arguments: [String] path, [Texture2D] preview, [Texture2D] thumbnail_preview, [Variant] userdata. [code]userdata[/code] can be anything, and will be returned when [code]receiver_func[/code] is called. - [b]Note[/b]: If it was not possible to create the preview the [code]receiver_func[/code] will still be called, but the preview will be null. + [b]Note:[/b] If it was not possible to create the preview the [code]receiver_func[/code] will still be called, but the preview will be null. </description> </method> <method name="remove_preview_generator"> diff --git a/doc/classes/EditorScenePostImport.xml b/doc/classes/EditorScenePostImport.xml index 241531c35f..8a731a6d1d 100644 --- a/doc/classes/EditorScenePostImport.xml +++ b/doc/classes/EditorScenePostImport.xml @@ -52,7 +52,7 @@ [/codeblocks] </description> <tutorials> - <link title="Importing 3D scenes: Custom script">https://docs.godotengine.org/en/latest/getting_started/workflow/assets/importing_scenes.html#custom-script</link> + <link title="Importing 3D scenes: Custom script">https://docs.godotengine.org/en/latest/tutorials/assets_pipeline/importing_scenes.html#custom-script</link> </tutorials> <methods> <method name="_post_import" qualifiers="virtual"> diff --git a/doc/classes/File.xml b/doc/classes/File.xml index cf08029c72..811aeb8aab 100644 --- a/doc/classes/File.xml +++ b/doc/classes/File.xml @@ -45,7 +45,7 @@ [b]Note:[/b] Files are automatically closed only if the process exits "normally" (such as by clicking the window manager's close button or pressing [b]Alt + F4[/b]). If you stop the project execution by pressing [b]F8[/b] while the project is running, the file won't be closed as the game process will be killed. You can work around this by calling [method flush] at regular intervals. </description> <tutorials> - <link title="File system">https://docs.godotengine.org/en/latest/getting_started/step_by_step/filesystem.html</link> + <link title="File system">https://docs.godotengine.org/en/latest/tutorials/scripting/filesystem.html</link> <link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link> </tutorials> <methods> diff --git a/doc/classes/FontData.xml b/doc/classes/FontData.xml index a814685388..7b1fc2ab42 100644 --- a/doc/classes/FontData.xml +++ b/doc/classes/FontData.xml @@ -23,7 +23,8 @@ <argument index="0" name="cache_index" type="int" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all rendered glyphs information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method remove_texture] to remove them manually. + Removes all rendered glyphs information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method remove_texture] to remove them manually. </description> </method> <method name="clear_kerning_map"> @@ -46,7 +47,8 @@ <argument index="0" name="cache_index" type="int" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all textures from font cache entry. Note: This function will not remove glyphs associated with the texture, use [method remove_glyph] to remove them manually. + Removes all textures from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, use [method remove_glyph] to remove them manually. </description> </method> <method name="find_cache" qualifiers="const"> @@ -97,7 +99,8 @@ <argument index="1" name="size" type="int" /> <argument index="2" name="glyph" type="int" /> <description> - Returns glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Returns glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="get_glyph_index" qualifiers="const"> @@ -364,7 +367,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="glyph" type="int" /> <description> - Removes specified rendered glyph information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method remove_texture] to remove them manually. + Removes specified rendered glyph information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method remove_texture] to remove them manually. </description> </method> <method name="remove_kerning"> @@ -404,7 +408,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="texture_index" type="int" /> <description> - Removes specified texture from font cache entry. Note: This function will not remove glyphs associated with the texture, remove them manually, using [method remove_glyph]. + Removes specified texture from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, remove them manually, using [method remove_glyph]. </description> </method> <method name="render_glyph"> @@ -472,7 +477,8 @@ <argument index="2" name="glyph" type="int" /> <argument index="3" name="advance" type="Vector2" /> <description> - Sets glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Sets glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="set_glyph_offset"> diff --git a/doc/classes/GPUParticles3D.xml b/doc/classes/GPUParticles3D.xml index 3f7b20f274..0bed561de3 100644 --- a/doc/classes/GPUParticles3D.xml +++ b/doc/classes/GPUParticles3D.xml @@ -8,7 +8,7 @@ Use the [code]process_material[/code] property to add a [ParticlesMaterial] to configure particle appearance and behavior. Alternatively, you can add a [ShaderMaterial] which will be applied to all particles. </description> <tutorials> - <link title="Controlling thousands of fish with Particles">https://docs.godotengine.org/en/latest/tutorials/3d/vertex_animation/controlling_thousands_of_fish.html</link> + <link title="Controlling thousands of fish with Particles">https://docs.godotengine.org/en/latest/tutorials/performance/vertex_animation/controlling_thousands_of_fish.html</link> <link title="Third Person Shooter Demo">https://godotengine.org/asset-library/asset/678</link> </tutorials> <methods> diff --git a/doc/classes/Image.xml b/doc/classes/Image.xml index 5d79e22c49..492bddca1f 100644 --- a/doc/classes/Image.xml +++ b/doc/classes/Image.xml @@ -9,7 +9,7 @@ [b]Note:[/b] The maximum image size is 16384×16384 pixels due to graphics hardware limitations. Larger images may fail to import. </description> <tutorials> - <link title="Importing images">https://docs.godotengine.org/en/latest/getting_started/workflow/assets/importing_images.html</link> + <link title="Importing images">https://docs.godotengine.org/en/latest/tutorials/assets_pipeline/importing_images.html</link> </tutorials> <methods> <method name="adjust_bcs"> diff --git a/doc/classes/EditorSceneImporterMesh.xml b/doc/classes/ImporterMesh.xml index 5d57a76d5f..ab344f908c 100644 --- a/doc/classes/EditorSceneImporterMesh.xml +++ b/doc/classes/ImporterMesh.xml @@ -1,12 +1,12 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="EditorSceneImporterMesh" inherits="Resource" version="4.0"> +<class name="ImporterMesh" inherits="Resource" version="4.0"> <brief_description> A [Resource] that contains vertex array-based geometry during the import process. </brief_description> <description> - EditorSceneImporterMesh is a type of [Resource] analogous to [ArrayMesh]. It contains vertex array-based geometry, divided in [i]surfaces[/i]. Each surface contains a completely separate array and a material used to draw it. Design wise, a mesh with multiple surfaces is preferred to a single surface, because objects created in 3D editing software commonly contain multiple materials. + ImporterMesh is a type of [Resource] analogous to [ArrayMesh]. It contains vertex array-based geometry, divided in [i]surfaces[/i]. Each surface contains a completely separate array and a material used to draw it. Design wise, a mesh with multiple surfaces is preferred to a single surface, because objects created in 3D editing software commonly contain multiple materials. - Unlike its runtime counterpart, [EditorSceneImporterMesh] contains mesh data before various import steps, such as lod and shadow mesh generation, have taken place. Modify surface data by calling [method clear], followed by [method add_surface] for each surface. + Unlike its runtime counterpart, [ImporterMesh] contains mesh data before various import steps, such as lod and shadow mesh generation, have taken place. Modify surface data by calling [method clear], followed by [method add_surface] for each surface. </description> <tutorials> </tutorials> @@ -37,7 +37,7 @@ <method name="clear"> <return type="void" /> <description> - Removes all surfaces and blend shapes from this [EditorSceneImporterMesh]. + Removes all surfaces and blend shapes from this [ImporterMesh]. </description> </method> <method name="get_blend_shape_count" qualifiers="const"> @@ -69,7 +69,7 @@ <return type="ArrayMesh" /> <argument index="0" name="base_mesh" type="ArrayMesh" default="null" /> <description> - Returns the mesh data represented by this [EditorSceneImporterMesh] as a usable [ArrayMesh]. + Returns the mesh data represented by this [ImporterMesh] as a usable [ArrayMesh]. This method caches the returned mesh, and subsequent calls will return the cached data until [method clear] is called. If not yet cached and [code]base_mesh[/code] is provided, [code]base_mesh[/code] will be used and mutated. </description> diff --git a/doc/classes/EditorSceneImporterMeshNode3D.xml b/doc/classes/ImporterMeshInstance3D.xml index 848448110e..6d572f543b 100644 --- a/doc/classes/EditorSceneImporterMeshNode3D.xml +++ b/doc/classes/ImporterMeshInstance3D.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="EditorSceneImporterMeshNode3D" inherits="Node3D" version="4.0"> +<class name="ImporterMeshInstance3D" inherits="Node3D" version="4.0"> <brief_description> </brief_description> <description> @@ -7,7 +7,7 @@ <tutorials> </tutorials> <members> - <member name="mesh" type="EditorSceneImporterMesh" setter="set_mesh" getter="get_mesh"> + <member name="mesh" type="ImporterMesh" setter="set_mesh" getter="get_mesh"> </member> <member name="skeleton_path" type="NodePath" setter="set_skeleton_path" getter="get_skeleton_path" default="NodePath("")"> </member> diff --git a/doc/classes/Input.xml b/doc/classes/Input.xml index ebbcd2b894..00ead31115 100644 --- a/doc/classes/Input.xml +++ b/doc/classes/Input.xml @@ -7,7 +7,7 @@ A singleton that deals with inputs. This includes key presses, mouse buttons and movement, joypads, and input actions. Actions and their events can be set in the [b]Input Map[/b] tab in the [b]Project > Project Settings[/b], or with the [InputMap] class. </description> <tutorials> - <link title="Inputs tutorial index">https://docs.godotengine.org/en/latest/tutorials/inputs/index.html</link> + <link title="Inputs documentation index">https://docs.godotengine.org/en/latest/tutorials/inputs/index.html</link> <link title="2D Dodge The Creeps Demo">https://godotengine.org/asset-library/asset/515</link> <link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link> </tutorials> @@ -386,6 +386,7 @@ </constant> <constant name="CURSOR_DRAG" value="6" enum="CursorShape"> Drag cursor. Usually displayed when dragging something. + [b]Note:[/b] Windows lacks a dragging cursor, so [constant CURSOR_DRAG] is the same as [constant CURSOR_MOVE] for this platform. </constant> <constant name="CURSOR_CAN_DROP" value="7" enum="CursorShape"> Can drop cursor. Usually displayed when dragging something to indicate that it can be dropped at the current position. diff --git a/doc/classes/JavaScript.xml b/doc/classes/JavaScript.xml index 5865ad734e..2bb2666df4 100644 --- a/doc/classes/JavaScript.xml +++ b/doc/classes/JavaScript.xml @@ -8,7 +8,7 @@ [b]Note:[/b] This singleton can be disabled at build-time to improve security. By default, the JavaScript singleton is enabled. Official export templates also have the JavaScript singleton enabled. See [url=https://docs.godotengine.org/en/latest/development/compiling/compiling_for_web.html]Compiling for the Web[/url] in the documentation for more information. </description> <tutorials> - <link title="Exporting for the Web: Calling JavaScript from script">https://docs.godotengine.org/en/latest/getting_started/workflow/export/exporting_for_web.html#calling-javascript-from-script</link> + <link title="Exporting for the Web: Calling JavaScript from script">https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_web.html#calling-javascript-from-script</link> </tutorials> <methods> <method name="create_callback"> diff --git a/doc/classes/JavaScriptObject.xml b/doc/classes/JavaScriptObject.xml index 5aa54a7d0c..6dd8702d5f 100644 --- a/doc/classes/JavaScriptObject.xml +++ b/doc/classes/JavaScriptObject.xml @@ -31,7 +31,7 @@ # [0, 9, [JavaScriptObject:1180]] print(args) [/codeblock] - Note: Only available in the "HTML5" platform. + [b]Note:[/b] Only available in the HTML5 platform. </description> <tutorials> </tutorials> diff --git a/doc/classes/KinematicCollision2D.xml b/doc/classes/KinematicCollision2D.xml index 29fc4700fd..23b01a0fc9 100644 --- a/doc/classes/KinematicCollision2D.xml +++ b/doc/classes/KinematicCollision2D.xml @@ -14,43 +14,74 @@ <return type="float" /> <argument index="0" name="up_direction" type="Vector2" default="Vector2(0, -1)" /> <description> - The collision angle according to [code]up_direction[/code], which is [code]Vector2.UP[/code] by default. This value is always positive. + Returns the collision angle according to [code]up_direction[/code], which is [code]Vector2.UP[/code] by default. This value is always positive. + </description> + </method> + <method name="get_collider" qualifiers="const"> + <return type="Object" /> + <description> + Returns the colliding body's attached [Object]. + </description> + </method> + <method name="get_collider_id" qualifiers="const"> + <return type="int" /> + <description> + Returns the unique instance ID of the colliding body's attached [Object]. See [method Object.get_instance_id]. + </description> + </method> + <method name="get_collider_rid" qualifiers="const"> + <return type="RID" /> + <description> + Returns the colliding body's [RID] used by the [PhysicsServer2D]. + </description> + </method> + <method name="get_collider_shape" qualifiers="const"> + <return type="Object" /> + <description> + Returns the colliding body's shape. + </description> + </method> + <method name="get_collider_shape_index" qualifiers="const"> + <return type="int" /> + <description> + Returns the colliding body's shape index. See [CollisionObject2D]. + </description> + </method> + <method name="get_collider_velocity" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the colliding body's velocity. + </description> + </method> + <method name="get_local_shape" qualifiers="const"> + <return type="Object" /> + <description> + Returns the moving object's colliding shape. + </description> + </method> + <method name="get_normal" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the colliding body's shape's normal at the point of collision. + </description> + </method> + <method name="get_position" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the point of collision in global coordinates. + </description> + </method> + <method name="get_remainder" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the moving object's remaining movement vector. + </description> + </method> + <method name="get_travel" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the moving object's travel before collision. </description> </method> </methods> - <members> - <member name="collider" type="Object" setter="" getter="get_collider"> - The colliding body. - </member> - <member name="collider_id" type="int" setter="" getter="get_collider_id" default="0"> - The colliding body's unique instance ID. See [method Object.get_instance_id]. - </member> - <member name="collider_rid" type="RID" setter="" getter="get_collider_rid"> - The colliding body's [RID] used by the [PhysicsServer2D]. - </member> - <member name="collider_shape" type="Object" setter="" getter="get_collider_shape"> - The colliding body's shape. - </member> - <member name="collider_shape_index" type="int" setter="" getter="get_collider_shape_index" default="0"> - The colliding shape's index. See [CollisionObject2D]. - </member> - <member name="collider_velocity" type="Vector2" setter="" getter="get_collider_velocity" default="Vector2(0, 0)"> - The colliding object's velocity. - </member> - <member name="local_shape" type="Object" setter="" getter="get_local_shape"> - The moving object's colliding shape. - </member> - <member name="normal" type="Vector2" setter="" getter="get_normal" default="Vector2(0, 0)"> - The colliding body's shape's normal at the point of collision. - </member> - <member name="position" type="Vector2" setter="" getter="get_position" default="Vector2(0, 0)"> - The point of collision, in global coordinates. - </member> - <member name="remainder" type="Vector2" setter="" getter="get_remainder" default="Vector2(0, 0)"> - The moving object's remaining movement vector. - </member> - <member name="travel" type="Vector2" setter="" getter="get_travel" default="Vector2(0, 0)"> - The distance the moving object traveled before collision. - </member> - </members> </class> diff --git a/doc/classes/KinematicCollision3D.xml b/doc/classes/KinematicCollision3D.xml index 3db6fe019b..372113b281 100644 --- a/doc/classes/KinematicCollision3D.xml +++ b/doc/classes/KinematicCollision3D.xml @@ -15,108 +15,89 @@ <argument index="0" name="collision_index" type="int" default="0" /> <argument index="1" name="up_direction" type="Vector3" default="Vector3(0, 1, 0)" /> <description> - The collision angle according to [code]up_direction[/code], which is [code]Vector3.UP[/code] by default. This value is always positive. + Returns the collision angle according to [code]up_direction[/code], which is [code]Vector3.UP[/code] by default. This value is always positive. </description> </method> <method name="get_collider" qualifiers="const"> <return type="Object" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider by index (the latest by default). + Returns the colliding body's attached [Object] given a collision index (the deepest collision by default). </description> </method> <method name="get_collider_id" qualifiers="const"> <return type="int" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider ID by index (the latest by default). + Returns the unique instance ID of the colliding body's attached [Object] given a collision index (the deepest collision by default). See [method Object.get_instance_id]. </description> </method> <method name="get_collider_rid" qualifiers="const"> <return type="RID" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider RID by index (the latest by default). + Returns the colliding body's [RID] used by the [PhysicsServer3D] given a collision index (the deepest collision by default). </description> </method> <method name="get_collider_shape" qualifiers="const"> <return type="Object" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider shape by index (the latest by default). + Returns the colliding body's shape given a collision index (the deepest collision by default). </description> </method> <method name="get_collider_shape_index" qualifiers="const"> <return type="int" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider shape index by index (the latest by default). + Returns the colliding body's shape index given a collision index (the deepest collision by default). See [CollisionObject3D]. </description> </method> <method name="get_collider_velocity" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider velocity by index (the latest by default). + Returns the colliding body's velocity given a collision index (the deepest collision by default). + </description> + </method> + <method name="get_collision_count" qualifiers="const"> + <return type="int" /> + <description> + Returns the number of detected collisions. </description> </method> <method name="get_local_shape" qualifiers="const"> <return type="Object" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider velocity by index (the latest by default). + Returns the moving object's colliding shape given a collision index (the deepest collision by default). </description> </method> <method name="get_normal" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider normal by index (the latest by default). + Returns the colliding body's shape's normal at the point of collision given a collision index (the deepest collision by default). </description> </method> <method name="get_position" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> - Returns the collider collision point by index (the latest by default). + Returns the point of collision in global coordinates given a collision index (the deepest collision by default). + </description> + </method> + <method name="get_remainder" qualifiers="const"> + <return type="Vector3" /> + <description> + Returns the moving object's remaining movement vector. + </description> + </method> + <method name="get_travel" qualifiers="const"> + <return type="Vector3" /> + <description> + Returns the moving object's travel before collision. </description> </method> </methods> - <members> - <member name="collider" type="Object" setter="" getter="get_best_collider"> - The colliding body. - </member> - <member name="collider_id" type="int" setter="" getter="get_best_collider_id" default="0"> - The colliding body's unique instance ID. See [method Object.get_instance_id]. - </member> - <member name="collider_rid" type="RID" setter="" getter="get_best_collider_rid"> - The colliding body's [RID] used by the [PhysicsServer3D]. - </member> - <member name="collider_shape" type="Object" setter="" getter="get_best_collider_shape"> - The colliding body's shape. - </member> - <member name="collider_shape_index" type="int" setter="" getter="get_best_collider_shape_index" default="0"> - The colliding shape's index. See [CollisionObject3D]. - </member> - <member name="collider_velocity" type="Vector3" setter="" getter="get_best_collider_velocity" default="Vector3(0, 0, 0)"> - The colliding object's velocity. - </member> - <member name="collision_count" type="int" setter="" getter="get_collision_count" default="0"> - </member> - <member name="local_shape" type="Object" setter="" getter="get_best_local_shape"> - The moving object's colliding shape. - </member> - <member name="normal" type="Vector3" setter="" getter="get_best_normal" default="Vector3(0, 0, 0)"> - The colliding body's shape's normal at the point of collision. - </member> - <member name="position" type="Vector3" setter="" getter="get_best_position" default="Vector3(0, 0, 0)"> - The point of collision, in global coordinates. - </member> - <member name="remainder" type="Vector3" setter="" getter="get_remainder" default="Vector3(0, 0, 0)"> - The moving object's remaining movement vector. - </member> - <member name="travel" type="Vector3" setter="" getter="get_travel" default="Vector3(0, 0, 0)"> - The distance the moving object traveled before collision. - </member> - </members> </class> diff --git a/doc/classes/LineEdit.xml b/doc/classes/LineEdit.xml index 83e3f5b05a..4ad71d1e80 100644 --- a/doc/classes/LineEdit.xml +++ b/doc/classes/LineEdit.xml @@ -175,7 +175,7 @@ </member> <member name="caret_mid_grapheme" type="bool" setter="set_caret_mid_grapheme_enabled" getter="is_caret_mid_grapheme_enabled" default="false"> Allow moving caret, selecting and removing the individual composite character components. - Note: [kbd]Backspace[/kbd] is always removing individual composite character components. + [b]Note:[/b] [kbd]Backspace[/kbd] is always removing individual composite character components. </member> <member name="clear_button_enabled" type="bool" setter="set_clear_button_enabled" getter="is_clear_button_enabled" default="false"> If [code]true[/code], the [LineEdit] will show a clear button if [code]text[/code] is not empty, which can be used to clear the text quickly. diff --git a/doc/classes/Material.xml b/doc/classes/Material.xml index a3e98228c6..f77b69b1f9 100644 --- a/doc/classes/Material.xml +++ b/doc/classes/Material.xml @@ -20,11 +20,12 @@ <members> <member name="next_pass" type="Material" setter="set_next_pass" getter="get_next_pass"> Sets the [Material] to be used for the next pass. This renders the object again using a different material. - [b]Note:[/b] only applies to [StandardMaterial3D]s and [ShaderMaterial]s with type "Spatial". + [b]Note:[/b] This only applies to [StandardMaterial3D]s and [ShaderMaterial]s with type "Spatial". </member> <member name="render_priority" type="int" setter="set_render_priority" getter="get_render_priority" default="0"> Sets the render priority for transparent objects in 3D scenes. Higher priority objects will be sorted in front of lower priority objects. - [b]Note:[/b] this only applies to sorting of transparent objects. This will not impact how transparent objects are sorted relative to opaque objects. This is because opaque objects are not sorted, while transparent objects are sorted from back to front (subject to priority). + [b]Note:[/b] This only applies to [StandardMaterial3D]s and [ShaderMaterial]s with type "Spatial". + [b]Note:[/b] This only applies to sorting of transparent objects. This will not impact how transparent objects are sorted relative to opaque objects. This is because opaque objects are not sorted, while transparent objects are sorted from back to front (subject to priority). </member> </members> <constants> diff --git a/doc/classes/MultiMesh.xml b/doc/classes/MultiMesh.xml index 7b4a53a810..7890bbcc33 100644 --- a/doc/classes/MultiMesh.xml +++ b/doc/classes/MultiMesh.xml @@ -10,8 +10,8 @@ Since instances may have any behavior, the AABB used for visibility must be provided by the user. </description> <tutorials> - <link title="Animating thousands of fish with MultiMeshInstance">https://docs.godotengine.org/en/latest/tutorials/3d/vertex_animation/animating_thousands_of_fish.html</link> - <link title="Optimization using MultiMeshes">https://docs.godotengine.org/en/latest/tutorials/optimization/using_multimesh.html</link> + <link title="Animating thousands of fish with MultiMeshInstance">https://docs.godotengine.org/en/latest/tutorials/performance/vertex_animation/animating_thousands_of_fish.html</link> + <link title="Optimization using MultiMeshes">https://docs.godotengine.org/en/latest/tutorials/performance/using_multimesh.html</link> </tutorials> <methods> <method name="get_aabb" qualifiers="const"> diff --git a/doc/classes/MultiMeshInstance3D.xml b/doc/classes/MultiMeshInstance3D.xml index 7bf05d2d34..158579e952 100644 --- a/doc/classes/MultiMeshInstance3D.xml +++ b/doc/classes/MultiMeshInstance3D.xml @@ -8,9 +8,9 @@ This is useful to optimize the rendering of a high amount of instances of a given mesh (for example trees in a forest or grass strands). </description> <tutorials> - <link title="Animating thousands of fish with MultiMeshInstance">https://docs.godotengine.org/en/latest/tutorials/3d/vertex_animation/animating_thousands_of_fish.html</link> + <link title="Animating thousands of fish with MultiMeshInstance">https://docs.godotengine.org/en/latest/tutorials/performance/vertex_animation/animating_thousands_of_fish.html</link> <link title="Using MultiMeshInstance">https://docs.godotengine.org/en/latest/tutorials/3d/using_multi_mesh_instance.html</link> - <link title="Optimization using MultiMeshes">https://docs.godotengine.org/en/latest/tutorials/optimization/using_multimesh.html</link> + <link title="Optimization using MultiMeshes">https://docs.godotengine.org/en/latest/tutorials/performance/using_multimesh.html</link> </tutorials> <members> <member name="multimesh" type="MultiMesh" setter="set_multimesh" getter="get_multimesh"> diff --git a/doc/classes/MultiplayerReplicator.xml b/doc/classes/MultiplayerReplicator.xml index e0c309ef39..0f97cc1d0a 100644 --- a/doc/classes/MultiplayerReplicator.xml +++ b/doc/classes/MultiplayerReplicator.xml @@ -95,7 +95,7 @@ <argument index="1" name="peer_id" type="int" default="0" /> <description> Manually request a sync for all the instances of the scene identified by [code]scene_id[/code]. This function will trigger the default sync behaviour, or call your send custom send callable if specified in [method sync_config]. - Note: The default implementation only allow syncing from server to clients. + [b]Note:[/b] The default implementation only allow syncing from server to clients. </description> </method> <method name="sync_config"> diff --git a/doc/classes/Mutex.xml b/doc/classes/Mutex.xml index eb9bec1104..a840cb2ec7 100644 --- a/doc/classes/Mutex.xml +++ b/doc/classes/Mutex.xml @@ -7,7 +7,7 @@ A synchronization mutex (mutual exclusion). This is used to synchronize multiple [Thread]s, and is equivalent to a binary [Semaphore]. It guarantees that only one thread can ever acquire the lock at a time. A mutex can be used to protect a critical section; however, be careful to avoid deadlocks. </description> <tutorials> - <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/threads/using_multiple_threads.html</link> + <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/performance/using_multiple_threads.html</link> </tutorials> <methods> <method name="lock"> diff --git a/doc/classes/NavigationServer2D.xml b/doc/classes/NavigationServer2D.xml index 1740093eb2..971d3839f2 100644 --- a/doc/classes/NavigationServer2D.xml +++ b/doc/classes/NavigationServer2D.xml @@ -8,7 +8,7 @@ Maps are made up of regions, which are made of navigation polygons. Together, they define the navigable areas in the 2D world. For two regions to be connected to each other, they must share a similar edge. An edge is considered connected to another if both of its two vertices are at a distance less than [code]edge_connection_margin[/code] to the respective other edge's vertex. You may assign navigation layers to regions with [method NavigationServer2D.region_set_layers], which then can be checked upon when requesting a path with [method NavigationServer2D.map_get_path]. This allows allowing or forbidding some areas to 2D objects. To use the collision avoidance system, you may use agents. You can set an agent's target velocity, then the servers will emit a callback with a modified velocity. - [b]Note:[/b] the collision avoidance system ignores regions. Using the modified velocity as-is might lead to pushing and agent outside of a navigable area. This is a limitation of the collision avoidance system, any more complex situation may require the use of the physics engine. + [b]Note:[/b] The collision avoidance system ignores regions. Using the modified velocity as-is might lead to pushing and agent outside of a navigable area. This is a limitation of the collision avoidance system, any more complex situation may require the use of the physics engine. This server keeps tracks of any call and executes them during the sync phase. This means that you can request any change to the map, using any thread, without worrying. </description> <tutorials> diff --git a/doc/classes/NavigationServer3D.xml b/doc/classes/NavigationServer3D.xml index 3e10657838..16eba8bba8 100644 --- a/doc/classes/NavigationServer3D.xml +++ b/doc/classes/NavigationServer3D.xml @@ -8,7 +8,7 @@ Maps are made up of regions, which are made of navigation meshes. Together, they define the navigable areas in the 3D world. For two regions to be connected to each other, they must share a similar edge. An edge is considered connected to another if both of its two vertices are at a distance less than [code]edge_connection_margin[/code] to the respective other edge's vertex. You may assign navigation layers to regions with [method NavigationServer3D.region_set_layers], which then can be checked upon when requesting a path with [method NavigationServer3D.map_get_path]. This allows allowing or forbidding some areas to 3D objects. To use the collision avoidance system, you may use agents. You can set an agent's target velocity, then the servers will emit a callback with a modified velocity. - [b]Note:[/b] the collision avoidance system ignores regions. Using the modified velocity as-is might lead to pushing and agent outside of a navigable area. This is a limitation of the collision avoidance system, any more complex situation may require the use of the physics engine. + [b]Note:[/b] The collision avoidance system ignores regions. Using the modified velocity as-is might lead to pushing and agent outside of a navigable area. This is a limitation of the collision avoidance system, any more complex situation may require the use of the physics engine. This server keeps tracks of any call and executes them during the sync phase. This means that you can request any change to the map, using any thread, without worrying. </description> <tutorials> @@ -234,7 +234,7 @@ <description> Process the collision avoidance agents. The result of this process is needed by the physics server, so this must be called in the main thread. - Note: This function is not thread safe. + [b]Note:[/b] This function is not thread safe. </description> </method> <method name="region_bake_navmesh" qualifiers="const"> diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index b4edcf49f4..11c42fbd4a 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -17,7 +17,7 @@ [b]Networking with nodes:[/b] After connecting to a server (or making one, see [ENetMultiplayerPeer]), it is possible to use the built-in RPC (remote procedure call) system to communicate over the network. By calling [method rpc] with a method name, it will be called locally and in all connected peers (peers = clients and the server that accepts connections). To identify which node receives the RPC call, Godot will use its [NodePath] (make sure node names are the same on all peers). Also, take a look at the high-level networking tutorial and corresponding demos. </description> <tutorials> - <link title="Scenes and nodes">https://docs.godotengine.org/en/latest/getting_started/step_by_step/scenes_and_nodes.html</link> + <link title="Nodes and scenes">https://docs.godotengine.org/en/latest/getting_started/step_by_step/nodes_and_scenes.htmltml</link> <link title="All Demos">https://github.com/godotengine/godot-demo-projects/</link> </tutorials> <methods> diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml index ed045f8390..5a84364b92 100644 --- a/doc/classes/Object.xml +++ b/doc/classes/Object.xml @@ -29,7 +29,7 @@ [b]Note:[/b] Unlike references to a [RefCounted], references to an Object stored in a variable can become invalid without warning. Therefore, it's recommended to use [RefCounted] for data classes instead of [Object]. </description> <tutorials> - <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/getting_started/workflow/best_practices/node_alternatives.html</link> + <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/tutorials/best_practices/node_alternatives.html</link> </tutorials> <methods> <method name="_get" qualifiers="virtual"> diff --git a/doc/classes/PacketPeerUDP.xml b/doc/classes/PacketPeerUDP.xml index 9b77859b50..31640eb3d8 100644 --- a/doc/classes/PacketPeerUDP.xml +++ b/doc/classes/PacketPeerUDP.xml @@ -74,7 +74,7 @@ <description> Joins the multicast group specified by [code]multicast_address[/code] using the interface identified by [code]interface_name[/code]. You can join the same multicast group with multiple interfaces. Use [method IP.get_local_interfaces] to know which are available. - Note: Some Android devices might require the [code]CHANGE_WIFI_MULTICAST_STATE[/code] permission for multicast to work. + [b]Note:[/b] Some Android devices might require the [code]CHANGE_WIFI_MULTICAST_STATE[/code] permission for multicast to work. </description> </method> <method name="leave_multicast_group"> @@ -90,7 +90,7 @@ <argument index="0" name="enabled" type="bool" /> <description> Enable or disable sending of broadcast packets (e.g. [code]set_dest_address("255.255.255.255", 4343)[/code]. This option is disabled by default. - Note: Some Android devices might require the [code]CHANGE_WIFI_MULTICAST_STATE[/code] permission and this option to be enabled to receive broadcast packets too. + [b]Note:[/b] Some Android devices might require the [code]CHANGE_WIFI_MULTICAST_STATE[/code] permission and this option to be enabled to receive broadcast packets too. </description> </method> <method name="set_dest_address"> @@ -99,7 +99,7 @@ <argument index="1" name="port" type="int" /> <description> Sets the destination address and port for sending packets and variables. A hostname will be resolved using DNS if needed. - Note: [method set_broadcast_enabled] must be enabled before sending packets to a broadcast address (e.g. [code]255.255.255.255[/code]). + [b]Note:[/b] [method set_broadcast_enabled] must be enabled before sending packets to a broadcast address (e.g. [code]255.255.255.255[/code]). </description> </method> <method name="wait"> diff --git a/doc/classes/PhysicsServer2D.xml b/doc/classes/PhysicsServer2D.xml index b5b6a7ea58..d55feff829 100644 --- a/doc/classes/PhysicsServer2D.xml +++ b/doc/classes/PhysicsServer2D.xml @@ -584,14 +584,10 @@ <method name="body_test_motion"> <return type="bool" /> <argument index="0" name="body" type="RID" /> - <argument index="1" name="from" type="Transform2D" /> - <argument index="2" name="motion" type="Vector2" /> - <argument index="3" name="margin" type="float" default="0.08" /> - <argument index="4" name="result" type="PhysicsTestMotionResult2D" default="null" /> - <argument index="5" name="collide_separation_ray" type="bool" default="false" /> - <argument index="6" name="exclude" type="Array" default="[]" /> - <description> - Returns [code]true[/code] if a collision would result from moving in the given direction from a given point in space. Margin increases the size of the shapes involved in the collision detection. [PhysicsTestMotionResult2D] can be passed to return additional information in. + <argument index="1" name="parameters" type="PhysicsTestMotionParameters2D" /> + <argument index="2" name="result" type="PhysicsTestMotionResult2D" default="null" /> + <description> + Returns [code]true[/code] if a collision would result from moving along a motion vector from a given point in space. [PhysicsTestMotionParameters2D] is passed to set motion parameters. [PhysicsTestMotionResult2D] can be passed to return additional information. </description> </method> <method name="capsule_shape_create"> diff --git a/doc/classes/PhysicsServer3D.xml b/doc/classes/PhysicsServer3D.xml index 1d1ca54dbb..0e32d1defa 100644 --- a/doc/classes/PhysicsServer3D.xml +++ b/doc/classes/PhysicsServer3D.xml @@ -577,15 +577,10 @@ <method name="body_test_motion"> <return type="bool" /> <argument index="0" name="body" type="RID" /> - <argument index="1" name="from" type="Transform3D" /> - <argument index="2" name="motion" type="Vector3" /> - <argument index="3" name="margin" type="float" default="0.001" /> - <argument index="4" name="result" type="PhysicsTestMotionResult3D" default="null" /> - <argument index="5" name="collide_separation_ray" type="bool" default="false" /> - <argument index="6" name="exclude" type="Array" default="[]" /> - <argument index="7" name="max_collisions" type="int" default="1" /> - <description> - Returns [code]true[/code] if a collision would result from moving in the given direction from a given point in space. Margin increases the size of the shapes involved in the collision detection. [PhysicsTestMotionResult3D] can be passed to return additional information in. + <argument index="1" name="parameters" type="PhysicsTestMotionParameters3D" /> + <argument index="2" name="result" type="PhysicsTestMotionResult3D" default="null" /> + <description> + Returns [code]true[/code] if a collision would result from moving along a motion vector from a given point in space. [PhysicsTestMotionParameters3D] is passed to set motion parameters. [PhysicsTestMotionResult3D] can be passed to return additional information. </description> </method> <method name="box_shape_create"> diff --git a/doc/classes/PhysicsTestMotionParameters2D.xml b/doc/classes/PhysicsTestMotionParameters2D.xml new file mode 100644 index 0000000000..46c1827b97 --- /dev/null +++ b/doc/classes/PhysicsTestMotionParameters2D.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="PhysicsTestMotionParameters2D" inherits="RefCounted" version="4.0"> + <brief_description> + Parameters to be sent to a 2D body motion test. + </brief_description> + <description> + This class contains parameters used in [method PhysicsServer2D.body_test_motion]. + </description> + <tutorials> + </tutorials> + <members> + <member name="collide_separation_ray" type="bool" setter="set_collide_separation_ray_enabled" getter="is_collide_separation_ray_enabled" default="false"> + If set to [code]true[/code], shapes of type [constant PhysicsServer2D.SHAPE_SEPARATION_RAY] are used to detect collisions and can stop the motion. Can be useful when snapping to the ground. + If set to [code]false[/code], shapes of type [constant PhysicsServer2D.SHAPE_SEPARATION_RAY] are only used for separation when overlapping with other bodies. That's the main use for separation ray shapes. + </member> + <member name="exclude_bodies" type="Array" setter="set_exclude_bodies" getter="get_exclude_bodies" default="[]"> + Optional array of body [RID] to exclude from collision. + </member> + <member name="exclude_objects" type="Array" setter="set_exclude_objects" getter="get_exclude_objects" default="[]"> + Optional array of object unique instance ID to exclude from collision. See [method Object.get_instance_id]. + </member> + <member name="from" type="Transform2D" setter="set_from" getter="get_from" default="Transform2D(1, 0, 0, 1, 0, 0)"> + Transform in global space where the motion should start. Usually set to [member Node2D.global_transform] for the current body's transform. + </member> + <member name="margin" type="float" setter="set_margin" getter="get_margin" default="0.08"> + Increases the size of the shapes involved in the collision detection. + </member> + <member name="motion" type="Vector2" setter="set_motion" getter="get_motion" default="Vector2(0, 0)"> + Motion vector to define the length and direction of the motion to test. + </member> + </members> +</class> diff --git a/doc/classes/PhysicsTestMotionParameters3D.xml b/doc/classes/PhysicsTestMotionParameters3D.xml new file mode 100644 index 0000000000..d66aee3ae6 --- /dev/null +++ b/doc/classes/PhysicsTestMotionParameters3D.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="PhysicsTestMotionParameters3D" inherits="RefCounted" version="4.0"> + <brief_description> + Parameters to be sent to a 3D body motion test. + </brief_description> + <description> + This class contains parameters used in [method PhysicsServer3D.body_test_motion]. + </description> + <tutorials> + </tutorials> + <members> + <member name="collide_separation_ray" type="bool" setter="set_collide_separation_ray_enabled" getter="is_collide_separation_ray_enabled" default="false"> + If set to [code]true[/code], shapes of type [constant PhysicsServer3D.SHAPE_SEPARATION_RAY] are used to detect collisions and can stop the motion. Can be useful when snapping to the ground. + If set to [code]false[/code], shapes of type [constant PhysicsServer3D.SHAPE_SEPARATION_RAY] are only used for separation when overlapping with other bodies. That's the main use for separation ray shapes. + </member> + <member name="exclude_bodies" type="Array" setter="set_exclude_bodies" getter="get_exclude_bodies" default="[]"> + Optional array of body [RID] to exclude from collision. + </member> + <member name="exclude_objects" type="Array" setter="set_exclude_objects" getter="get_exclude_objects" default="[]"> + Optional array of object unique instance ID to exclude from collision. See [method Object.get_instance_id]. + </member> + <member name="from" type="Transform3D" setter="set_from" getter="get_from" default="Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)"> + Transform in global space where the motion should start. Usually set to [member Node3D.global_transform] for the current body's transform. + </member> + <member name="margin" type="float" setter="set_margin" getter="get_margin" default="0.001"> + Increases the size of the shapes involved in the collision detection. + </member> + <member name="max_collisions" type="int" setter="set_max_collisions" getter="get_max_collisions" default="1"> + Maximum number of returned collisions, between [code]1[/code] and [code]32[/code]. Always returns the deepest detected collisions. + </member> + <member name="motion" type="Vector3" setter="set_motion" getter="get_motion" default="Vector3(0, 0, 0)"> + Motion vector to define the length and direction of the motion to test. + </member> + </members> +</class> diff --git a/doc/classes/PhysicsTestMotionResult2D.xml b/doc/classes/PhysicsTestMotionResult2D.xml index 8d594af673..355365cf25 100644 --- a/doc/classes/PhysicsTestMotionResult2D.xml +++ b/doc/classes/PhysicsTestMotionResult2D.xml @@ -1,35 +1,91 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="PhysicsTestMotionResult2D" inherits="RefCounted" version="4.0"> <brief_description> + Result from a 2D body motion test. </brief_description> <description> + This class contains the motion and collision result from [method PhysicsServer2D.body_test_motion]. </description> <tutorials> </tutorials> - <members> - <member name="collider" type="Object" setter="" getter="get_collider"> - </member> - <member name="collider_id" type="int" setter="" getter="get_collider_id" default="0"> - </member> - <member name="collider_rid" type="RID" setter="" getter="get_collider_rid"> - </member> - <member name="collider_shape" type="int" setter="" getter="get_collider_shape" default="0"> - </member> - <member name="collider_velocity" type="Vector2" setter="" getter="get_collider_velocity" default="Vector2(0, 0)"> - </member> - <member name="collision_depth" type="float" setter="" getter="get_collision_depth" default="0.0"> - </member> - <member name="collision_normal" type="Vector2" setter="" getter="get_collision_normal" default="Vector2(0, 0)"> - </member> - <member name="collision_point" type="Vector2" setter="" getter="get_collision_point" default="Vector2(0, 0)"> - </member> - <member name="collision_safe_fraction" type="float" setter="" getter="get_collision_safe_fraction" default="0.0"> - </member> - <member name="collision_unsafe_fraction" type="float" setter="" getter="get_collision_unsafe_fraction" default="0.0"> - </member> - <member name="remainder" type="Vector2" setter="" getter="get_remainder" default="Vector2(0, 0)"> - </member> - <member name="travel" type="Vector2" setter="" getter="get_travel" default="Vector2(0, 0)"> - </member> - </members> + <methods> + <method name="get_collider" qualifiers="const"> + <return type="Object" /> + <description> + Returns the colliding body's attached [Object], if a collision occured. + </description> + </method> + <method name="get_collider_id" qualifiers="const"> + <return type="int" /> + <description> + Returns the unique instance ID of the colliding body's attached [Object], if a collision occured. See [method Object.get_instance_id]. + </description> + </method> + <method name="get_collider_rid" qualifiers="const"> + <return type="RID" /> + <description> + Returns the colliding body's [RID] used by the [PhysicsServer2D], if a collision occured. + </description> + </method> + <method name="get_collider_shape" qualifiers="const"> + <return type="int" /> + <description> + Returns the colliding body's shape index, if a collision occured. See [CollisionObject2D]. + </description> + </method> + <method name="get_collider_velocity" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the colliding body's velocity, if a collision occured. + </description> + </method> + <method name="get_collision_depth" qualifiers="const"> + <return type="float" /> + <description> + Returns the length of overlap along the collision normal, if a collision occured. + </description> + </method> + <method name="get_collision_local_shape" qualifiers="const"> + <return type="int" /> + <description> + Returns the moving object's colliding shape, if a collision occured. + </description> + </method> + <method name="get_collision_normal" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the colliding body's shape's normal at the point of collision, if a collision occured. + </description> + </method> + <method name="get_collision_point" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the point of collision in global coordinates, if a collision occured. + </description> + </method> + <method name="get_collision_safe_fraction" qualifiers="const"> + <return type="float" /> + <description> + Returns the maximum fraction of the motion that can occur without a collision, between [code]0[/code] and [code]1[/code]. + </description> + </method> + <method name="get_collision_unsafe_fraction" qualifiers="const"> + <return type="float" /> + <description> + Returns the minimum fraction of the motion needed to collide, if a collision occured, between [code]0[/code] and [code]1[/code]. + </description> + </method> + <method name="get_remainder" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the moving object's remaining movement vector. + </description> + </method> + <method name="get_travel" qualifiers="const"> + <return type="Vector2" /> + <description> + Returns the moving object's travel before collision. + </description> + </method> + </methods> </class> diff --git a/doc/classes/PhysicsTestMotionResult3D.xml b/doc/classes/PhysicsTestMotionResult3D.xml index 8aa087e99a..282c140568 100644 --- a/doc/classes/PhysicsTestMotionResult3D.xml +++ b/doc/classes/PhysicsTestMotionResult3D.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="PhysicsTestMotionResult3D" inherits="RefCounted" version="4.0"> <brief_description> + Result from a 3D body motion test. </brief_description> <description> + This class contains the motion and collision result from [method PhysicsServer3D.body_test_motion]. </description> <tutorials> </tutorials> @@ -11,77 +13,94 @@ <return type="Object" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the colliding body's attached [Object] given a collision index (the deepest collision by default), if a collision occured. </description> </method> <method name="get_collider_id" qualifiers="const"> <return type="int" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the unique instance ID of the colliding body's attached [Object] given a collision index (the deepest collision by default), if a collision occured. See [method Object.get_instance_id]. </description> </method> <method name="get_collider_rid" qualifiers="const"> <return type="RID" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the colliding body's [RID] used by the [PhysicsServer3D] given a collision index (the deepest collision by default), if a collision occured. </description> </method> <method name="get_collider_shape" qualifiers="const"> <return type="int" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the colliding body's shape index given a collision index (the deepest collision by default), if a collision occured. See [CollisionObject3D]. </description> </method> <method name="get_collider_velocity" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the colliding body's velocity given a collision index (the deepest collision by default), if a collision occured. + </description> + </method> + <method name="get_collision_count" qualifiers="const"> + <return type="int" /> + <description> + Returns the number of detected collisions. </description> </method> <method name="get_collision_depth" qualifiers="const"> <return type="float" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the length of overlap along the collision normal given a collision index (the deepest collision by default), if a collision occured. + </description> + </method> + <method name="get_collision_local_shape" qualifiers="const"> + <return type="int" /> + <argument index="0" name="collision_index" type="int" default="0" /> + <description> + Returns the moving object's colliding shape given a collision index (the deepest collision by default), if a collision occured. </description> </method> <method name="get_collision_normal" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the colliding body's shape's normal at the point of collision given a collision index (the deepest collision by default), if a collision occured. </description> </method> <method name="get_collision_point" qualifiers="const"> <return type="Vector3" /> <argument index="0" name="collision_index" type="int" default="0" /> <description> + Returns the point of collision in global coordinates given a collision index (the deepest collision by default), if a collision occured. + </description> + </method> + <method name="get_collision_safe_fraction" qualifiers="const"> + <return type="float" /> + <description> + Returns the maximum fraction of the motion that can occur without a collision, between [code]0[/code] and [code]1[/code]. + </description> + </method> + <method name="get_collision_unsafe_fraction" qualifiers="const"> + <return type="float" /> + <description> + Returns the minimum fraction of the motion needed to collide, if a collision occured, between [code]0[/code] and [code]1[/code]. + </description> + </method> + <method name="get_remainder" qualifiers="const"> + <return type="Vector3" /> + <description> + Returns the moving object's remaining movement vector. + </description> + </method> + <method name="get_travel" qualifiers="const"> + <return type="Vector3" /> + <description> + Returns the moving object's travel before collision. </description> </method> </methods> - <members> - <member name="collider" type="Object" setter="" getter="get_best_collider"> - </member> - <member name="collider_id" type="int" setter="" getter="get_best_collider_id" default="0"> - </member> - <member name="collider_rid" type="RID" setter="" getter="get_best_collider_rid"> - </member> - <member name="collider_shape" type="int" setter="" getter="get_best_collider_shape" default="0"> - </member> - <member name="collider_velocity" type="Vector3" setter="" getter="get_best_collider_velocity" default="Vector3(0, 0, 0)"> - </member> - <member name="collision_count" type="int" setter="" getter="get_collision_count" default="0"> - </member> - <member name="collision_depth" type="float" setter="" getter="get_best_collision_depth" default="0.0"> - </member> - <member name="collision_normal" type="Vector3" setter="" getter="get_best_collision_normal" default="Vector3(0, 0, 0)"> - </member> - <member name="collision_point" type="Vector3" setter="" getter="get_best_collision_point" default="Vector3(0, 0, 0)"> - </member> - <member name="remainder" type="Vector3" setter="" getter="get_remainder" default="Vector3(0, 0, 0)"> - </member> - <member name="safe_fraction" type="float" setter="" getter="get_safe_fraction" default="0.0"> - </member> - <member name="travel" type="Vector3" setter="" getter="get_travel" default="Vector3(0, 0, 0)"> - </member> - <member name="unsafe_fraction" type="float" setter="" getter="get_unsafe_fraction" default="0.0"> - </member> - </members> </class> diff --git a/doc/classes/Plane.xml b/doc/classes/Plane.xml index bc9b3cafb5..78e1e81752 100644 --- a/doc/classes/Plane.xml +++ b/doc/classes/Plane.xml @@ -7,7 +7,7 @@ Plane represents a normalized plane equation. Basically, "normal" is the normal of the plane (a,b,c normalized), and "d" is the distance from the origin to the plane (in the direction of "normal"). "Over" or "Above" the plane is considered the side of the plane towards where the normal is pointing. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> </tutorials> <methods> <method name="Plane" qualifiers="constructor"> diff --git a/doc/classes/RayCast2D.xml b/doc/classes/RayCast2D.xml index ce5d48cfa4..592c074a77 100644 --- a/doc/classes/RayCast2D.xml +++ b/doc/classes/RayCast2D.xml @@ -70,7 +70,7 @@ <return type="Vector2" /> <description> Returns the collision point at which the ray intersects the closest object. - [b]Note:[/b] this point is in the [b]global[/b] coordinate system. + [b]Note:[/b] This point is in the [b]global[/b] coordinate system. </description> </method> <method name="is_colliding" qualifiers="const"> diff --git a/doc/classes/Rect2.xml b/doc/classes/Rect2.xml index e585224818..a6bb81b589 100644 --- a/doc/classes/Rect2.xml +++ b/doc/classes/Rect2.xml @@ -9,7 +9,7 @@ The 3D counterpart to [Rect2] is [AABB]. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="Advanced vector math">https://docs.godotengine.org/en/latest/tutorials/math/vectors_advanced.html</link> </tutorials> diff --git a/doc/classes/Rect2i.xml b/doc/classes/Rect2i.xml index 2f6f4de66d..0ba013cade 100644 --- a/doc/classes/Rect2i.xml +++ b/doc/classes/Rect2i.xml @@ -8,7 +8,7 @@ It uses integer coordinates. If you need floating-point coordinates, use [Rect2] instead. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> </tutorials> <methods> diff --git a/doc/classes/RefCounted.xml b/doc/classes/RefCounted.xml index 5f18ccc14d..d965d2ea10 100644 --- a/doc/classes/RefCounted.xml +++ b/doc/classes/RefCounted.xml @@ -10,7 +10,7 @@ [b]Note:[/b] In C#, references will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free references that are no longer in use. This means that unused references will linger on for a while before being removed. </description> <tutorials> - <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/getting_started/workflow/best_practices/node_alternatives.html</link> + <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/tutorials/best_practices/node_alternatives.html</link> </tutorials> <methods> <method name="init_ref"> diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml index d40ad80d68..c79ed2a8b8 100644 --- a/doc/classes/RenderingServer.xml +++ b/doc/classes/RenderingServer.xml @@ -15,7 +15,7 @@ In 2D, all visible objects are some form of canvas item. In order to be visible, a canvas item needs to be the child of a canvas attached to a viewport, or it needs to be the child of another canvas item that is eventually attached to the canvas. </description> <tutorials> - <link title="Optimization using Servers">https://docs.godotengine.org/en/latest/tutorials/optimization/using_servers.html</link> + <link title="Optimization using Servers">https://docs.godotengine.org/en/latest/tutorials/performance/using_servers.html</link> </tutorials> <methods> <method name="bake_render_uv2"> @@ -2351,7 +2351,8 @@ <argument index="0" name="particles" type="RID" /> <argument index="1" name="material" type="RID" /> <description> - Sets the material for processing the particles. Note: this is not the material used to draw the materials. Equivalent to [member GPUParticles3D.process_material]. + Sets the material for processing the particles. + [b]Note:[/b] This is not the material used to draw the materials. Equivalent to [member GPUParticles3D.process_material]. </description> </method> <method name="particles_set_randomness_ratio"> diff --git a/doc/classes/Resource.xml b/doc/classes/Resource.xml index 45b68f342c..327183893b 100644 --- a/doc/classes/Resource.xml +++ b/doc/classes/Resource.xml @@ -8,8 +8,8 @@ [b]Note:[/b] In C#, resources will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free resources that are no longer in use. This means that unused resources will linger on for a while before being removed. </description> <tutorials> - <link title="Resources">https://docs.godotengine.org/en/latest/getting_started/step_by_step/resources.html</link> - <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/getting_started/workflow/best_practices/node_alternatives.html</link> + <link title="Resources">https://docs.godotengine.org/en/latest/tutorials/scripting/resources.html</link> + <link title="When and how to avoid using nodes for everything">https://docs.godotengine.org/en/latest/tutorials/best_practices/node_alternatives.html</link> </tutorials> <methods> <method name="duplicate" qualifiers="const"> diff --git a/doc/classes/RichTextEffect.xml b/doc/classes/RichTextEffect.xml index cf4b4f4a48..62323722f7 100644 --- a/doc/classes/RichTextEffect.xml +++ b/doc/classes/RichTextEffect.xml @@ -19,7 +19,7 @@ [b]Note:[/b] As soon as a [RichTextLabel] contains at least one [RichTextEffect], it will continuously process the effect unless the project is paused. This may impact battery life negatively. </description> <tutorials> - <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/gui/bbcode_in_richtextlabel.html</link> + <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/ui/bbcode_in_richtextlabel.html</link> <link title="RichTextEffect test project (third-party)">https://github.com/Eoin-ONeill-Yokai/Godot-Rich-Text-Effect-Test-Project</link> </tutorials> <methods> diff --git a/doc/classes/RichTextLabel.xml b/doc/classes/RichTextLabel.xml index 50db1dc122..a2e1c3d2c2 100644 --- a/doc/classes/RichTextLabel.xml +++ b/doc/classes/RichTextLabel.xml @@ -11,7 +11,7 @@ [b]Note:[/b] Unlike [Label], RichTextLabel doesn't have a [i]property[/i] to horizontally align text to the center. Instead, enable [member bbcode_enabled] and surround the text in a [code][center][/code] tag as follows: [code][center]Example[/center][/code]. There is currently no built-in way to vertically align text either, but this can be emulated by relying on anchors/containers and the [member fit_content_height] property. </description> <tutorials> - <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/gui/bbcode_in_richtextlabel.html</link> + <link title="BBCode in RichTextLabel">https://docs.godotengine.org/en/latest/tutorials/ui/bbcode_in_richtextlabel.html</link> <link title="GUI Rich Text/BBcode Demo">https://godotengine.org/asset-library/asset/132</link> <link title="OS Test Demo">https://godotengine.org/asset-library/asset/677</link> </tutorials> diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml index 8d7427611a..68f2d9a8d8 100644 --- a/doc/classes/SceneTree.xml +++ b/doc/classes/SceneTree.xml @@ -9,8 +9,8 @@ [SceneTree] is the default [MainLoop] implementation used by scenes, and is thus in charge of the game loop. </description> <tutorials> - <link title="SceneTree">https://docs.godotengine.org/en/latest/getting_started/step_by_step/scene_tree.html</link> - <link title="Multiple resolutions">https://docs.godotengine.org/en/latest/tutorials/viewports/multiple_resolutions.html</link> + <link title="SceneTree">https://docs.godotengine.org/en/latest/tutorials/scripting/scene_tree.html</link> + <link title="Multiple resolutions">https://docs.godotengine.org/en/latest/tutorials/rendering/multiple_resolutions.html</link> </tutorials> <methods> <method name="call_group" qualifiers="vararg"> diff --git a/doc/classes/Script.xml b/doc/classes/Script.xml index b7a4f448b0..7c59e87848 100644 --- a/doc/classes/Script.xml +++ b/doc/classes/Script.xml @@ -8,7 +8,7 @@ The [code]new[/code] method of a script subclass creates a new instance. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. </description> <tutorials> - <link title="Scripting">https://docs.godotengine.org/en/latest/getting_started/step_by_step/scripting.html</link> + <link title="Scripting documentation index">https://docs.godotengine.org/en/latest/tutorials/scripting/index.html</link> </tutorials> <methods> <method name="can_instantiate" qualifiers="const"> diff --git a/doc/classes/Semaphore.xml b/doc/classes/Semaphore.xml index 2f3fa021d4..9ff9cc0c87 100644 --- a/doc/classes/Semaphore.xml +++ b/doc/classes/Semaphore.xml @@ -7,7 +7,7 @@ A synchronization semaphore which can be used to synchronize multiple [Thread]s. Initialized to zero on creation. Be careful to avoid deadlocks. For a binary version, see [Mutex]. </description> <tutorials> - <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/threads/using_multiple_threads.html</link> + <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/performance/using_multiple_threads.html</link> </tutorials> <methods> <method name="post"> diff --git a/doc/classes/Shader.xml b/doc/classes/Shader.xml index bc5457b8ce..14c5ba9247 100644 --- a/doc/classes/Shader.xml +++ b/doc/classes/Shader.xml @@ -7,8 +7,7 @@ This class allows you to define a custom shader program that can be used by a [ShaderMaterial]. Shaders allow you to write your own custom behavior for rendering objects or updating particle information. For a detailed explanation and usage, please see the tutorials linked below. </description> <tutorials> - <link title="Shading tutorial index">https://docs.godotengine.org/en/latest/tutorials/shading/index.html</link> - <link title="What are shaders?">https://docs.godotengine.org/en/latest/tutorials/shading/your_first_shader/what_are_shaders.html</link> + <link title="Shaders documentation index">https://docs.godotengine.org/en/latest/tutorials/shaders/index.html</link> </tutorials> <methods> <method name="get_default_texture_param" qualifiers="const"> diff --git a/doc/classes/ShaderMaterial.xml b/doc/classes/ShaderMaterial.xml index 13f2e2fe5f..d5fc3fd210 100644 --- a/doc/classes/ShaderMaterial.xml +++ b/doc/classes/ShaderMaterial.xml @@ -7,7 +7,7 @@ A material that uses a custom [Shader] program to render either items to screen or process particles. You can create multiple materials for the same shader but configure different values for the uniforms defined in the shader. </description> <tutorials> - <link title="Shading tutorial index">https://docs.godotengine.org/en/latest/tutorials/shading/index.html</link> + <link title="Shaders documentation index">https://docs.godotengine.org/en/latest/tutorials/shaders/index.html</link> </tutorials> <methods> <method name="get_shader_param" qualifiers="const"> @@ -36,7 +36,8 @@ <argument index="0" name="param" type="StringName" /> <argument index="1" name="value" type="Variant" /> <description> - Changes the value set for this material of a uniform in the shader. [b]Note:[/b] [code]param[/code] must match the name of the uniform in the code exactly. + Changes the value set for this material of a uniform in the shader. + [b]Note:[/b] [code]param[/code] must match the name of the uniform in the code exactly. </description> </method> </methods> diff --git a/doc/classes/SkeletonModification2DCCDIK.xml b/doc/classes/SkeletonModification2DCCDIK.xml index ab9a482609..6cbc24f100 100644 --- a/doc/classes/SkeletonModification2DCCDIK.xml +++ b/doc/classes/SkeletonModification2DCCDIK.xml @@ -4,7 +4,7 @@ A modification that uses CCDIK to manipulate a series of bones to reach a target in 2D. </brief_description> <description> - This [SkeletonModification2D] uses an algorithm called [b]C[/b]yclic [b]C[/b]oordinate [b]D[/b]escent [b]I[/b]nverse [b]K[/b]inematics, or CCDIK, to manipulate a chain of bones in a [Skeleton2D] so it reaches a defined target. + This [SkeletonModification2D] uses an algorithm called Cyclic Coordinate Descent Inverse Kinematics, or CCDIK, to manipulate a chain of bones in a [Skeleton2D] 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. diff --git a/doc/classes/SkeletonModification2DFABRIK.xml b/doc/classes/SkeletonModification2DFABRIK.xml index 16c22a45d3..82b99d20bd 100644 --- a/doc/classes/SkeletonModification2DFABRIK.xml +++ b/doc/classes/SkeletonModification2DFABRIK.xml @@ -4,7 +4,7 @@ A modification that uses FABRIK to manipulate a series of [Bone2D] nodes to reach a target. </brief_description> <description> - This [SkeletonModification2D] uses an algorithm called [b]F[/b]orward [b]A[/b]nd [b]B[/b]ackward [b]R[/b]eaching [b]I[/b]nverse [b]K[/b]inematics, or FABRIK, to rotate a bone chain so that it reaches a target. + This [SkeletonModification2D] 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 [SkeletonModification2DCCDIK]. FABRIK also supports angle constraints, which are fully taken into account when solving. [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 [Bone2D] nodes! FABRIK joints hold the data needed for each [Bone2D] in the bone chain used by FABRIK. diff --git a/doc/classes/SkeletonModification3DCCDIK.xml b/doc/classes/SkeletonModification3DCCDIK.xml index ef3200a07a..55777ab0f4 100644 --- a/doc/classes/SkeletonModification3DCCDIK.xml +++ b/doc/classes/SkeletonModification3DCCDIK.xml @@ -4,7 +4,7 @@ A modification that uses CCDIK to manipulate a series of bones to reach a target. </brief_description> <description> - This [SkeletonModification3D] uses an algorithm called [b]C[/b]yclic [b]C[/b]oordinate [b]D[/b]escent [b]I[/b]nverse [b]K[/b]inematics, or CCDIK, to maniuplate a chain of bones in a Skeleton so it reaches a defined target. + This [SkeletonModification3D] uses an algorithm called Cyclic Coordinate Descent Inverse Kinematics, or CCDIK, to maniuplate 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. diff --git a/doc/classes/SkeletonModification3DFABRIK.xml b/doc/classes/SkeletonModification3DFABRIK.xml index 4c4e01e9d1..1c69ad7b3f 100644 --- a/doc/classes/SkeletonModification3DFABRIK.xml +++ b/doc/classes/SkeletonModification3DFABRIK.xml @@ -4,7 +4,7 @@ A modification that uses FABRIK to manipulate a series of bones to reach a target. </brief_description> <description> - This [SkeletonModification3D] uses an algorithm called [b]F[/b]orward [b]A[/b]nd [b]B[/b]ackward [b]R[/b]eaching [b]I[/b]nverse [b]K[/b]inematics, or FABRIK, to rotate a bone chain so that it reaches a target. + 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. @@ -67,7 +67,7 @@ <argument index="0" name="joint_idx" type="int" /> <description> Returns a boolean indiciating 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. + [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"> @@ -132,7 +132,7 @@ <argument index="1" name="use_target_basis" type="bool" /> <description> Sets whether the FABRIK joint at [code]joint_idx[/code] 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. + [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"> diff --git a/doc/classes/SkeletonModification3DStackHolder.xml b/doc/classes/SkeletonModification3DStackHolder.xml index 138f9818ab..eeaa509ed7 100644 --- a/doc/classes/SkeletonModification3DStackHolder.xml +++ b/doc/classes/SkeletonModification3DStackHolder.xml @@ -5,7 +5,7 @@ </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. + [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> diff --git a/doc/classes/StandardMaterial3D.xml b/doc/classes/StandardMaterial3D.xml index 8a36a734f1..43ba95e345 100644 --- a/doc/classes/StandardMaterial3D.xml +++ b/doc/classes/StandardMaterial3D.xml @@ -5,5 +5,6 @@ <description> </description> <tutorials> + <link title="Standard Material 3D">https://docs.godotengine.org/en/latest/tutorials/3d/standard_material_3d.html</link> </tutorials> </class> diff --git a/doc/classes/StreamPeer.xml b/doc/classes/StreamPeer.xml index 0622626846..805f056289 100644 --- a/doc/classes/StreamPeer.xml +++ b/doc/classes/StreamPeer.xml @@ -173,7 +173,7 @@ <argument index="0" name="value" type="String" /> <description> Puts a zero-terminated ASCII string into the stream prepended by a 32-bit unsigned integer representing its size. - Note: To put an ASCII string without prepending its size, you can use [method put_data]: + [b]Note:[/b] To put an ASCII string without prepending its size, you can use [method put_data]: [codeblocks] [gdscript] put_data("Hello world".to_ascii()) @@ -217,7 +217,7 @@ <argument index="0" name="value" type="String" /> <description> Puts a zero-terminated UTF-8 string into the stream prepended by a 32 bits unsigned integer representing its size. - Note: To put an UTF-8 string without prepending its size, you can use [method put_data]: + [b]Note:[/b] To put an UTF-8 string without prepending its size, you can use [method put_data]: [codeblocks] [gdscript] put_data("Hello world".to_utf8()) diff --git a/doc/classes/String.xml b/doc/classes/String.xml index 0991788483..10ce03c4b2 100644 --- a/doc/classes/String.xml +++ b/doc/classes/String.xml @@ -7,7 +7,7 @@ This is the built-in string class (and the one used by GDScript). It supports Unicode and provides all necessary means for string handling. Strings are reference-counted and use a copy-on-write approach, so passing them around is cheap in resources. </description> <tutorials> - <link title="GDScript format strings">https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/gdscript_format_string.html</link> + <link title="GDScript format strings">https://docs.godotengine.org/en/latest/tutorials/scripting/gdscript/gdscript_format_string.html</link> </tutorials> <methods> <method name="String" qualifiers="constructor"> diff --git a/doc/classes/SubViewport.xml b/doc/classes/SubViewport.xml index 28866699f6..c2a76b587f 100644 --- a/doc/classes/SubViewport.xml +++ b/doc/classes/SubViewport.xml @@ -6,8 +6,8 @@ <description> </description> <tutorials> + <link title="Using Viewports">https://docs.godotengine.org/en/latest/tutorials/rendering/viewports.html</link> <link title="Viewport and canvas transforms">https://docs.godotengine.org/en/latest/tutorials/2d/2d_transforms.html</link> - <link title="Viewports tutorial index">https://docs.godotengine.org/en/latest/tutorials/viewports/index.html</link> <link title="GUI in 3D Demo">https://godotengine.org/asset-library/asset/127</link> <link title="3D in 2D Demo">https://godotengine.org/asset-library/asset/128</link> <link title="2D in 3D Demo">https://godotengine.org/asset-library/asset/129</link> diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml index 6a38c1a117..0e39381991 100644 --- a/doc/classes/TextEdit.xml +++ b/doc/classes/TextEdit.xml @@ -599,7 +599,7 @@ <argument index="3" name="to_column" type="int" /> <description> Removes text between the given positions. - [b]Note:[/b]This does not adjust the caret or selection, which as a result it can end up in an invalid position. + [b]Note:[/b] This does not adjust the caret or selection, which as a result it can end up in an invalid position. </description> </method> <method name="search" qualifiers="const"> @@ -902,7 +902,7 @@ </member> <member name="caret_mid_grapheme" type="bool" setter="set_caret_mid_grapheme_enabled" getter="is_caret_mid_grapheme_enabled" default="false"> Allow moving caret, selecting and removing the individual composite character components. - Note: [kbd]Backspace[/kbd] is always removing individual composite character components. + [b]Note:[/b] [kbd]Backspace[/kbd] is always removing individual composite character components. </member> <member name="caret_move_on_right_click" type="bool" setter="set_move_caret_on_right_click_enabled" getter="is_move_caret_on_right_click_enabled" default="true"> If [code]true[/code], a right-click moves the caret at the mouse position before displaying the context menu. diff --git a/doc/classes/TextServer.xml b/doc/classes/TextServer.xml index 18ace85465..b10c7bcc96 100644 --- a/doc/classes/TextServer.xml +++ b/doc/classes/TextServer.xml @@ -21,8 +21,8 @@ <argument index="1" name="orientation" type="int" enum="TextServer.Orientation" default="0" /> <description> Creates new buffer for complex text layout, with the given [code]direction[/code] and [code]orientation[/code]. To free the resulting buffer, use [method free_rid] method. - Note: Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. - Note: Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. + [b]Note:[/b] Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. + [b]Note:[/b] Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. </description> </method> <method name="draw_hex_code_box" qualifiers="const"> @@ -41,7 +41,8 @@ <argument index="0" name="font_rid" type="RID" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all rendered glyphs information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method font_remove_texture] to remove them manually. + Removes all rendered glyphs information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method font_remove_texture] to remove them manually. </description> </method> <method name="font_clear_kerning_map"> @@ -64,7 +65,8 @@ <argument index="0" name="font_rid" type="RID" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all textures from font cache entry. Note: This function will not remove glyphs associated with the texture, use [method font_remove_glyph] to remove them manually. + Removes all textures from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, use [method font_remove_glyph] to remove them manually. </description> </method> <method name="font_draw_glyph" qualifiers="const"> @@ -77,7 +79,7 @@ <argument index="5" name="color" type="Color" default="Color(1, 1, 1, 1)" /> <description> Draws single glyph into a canvas item at the position, using [code]font_rid[/code] at the size [code]size[/code]. - Note: Glyph index is specific to the font, use glyphs indices returned by [method shaped_text_get_glyphs] or [method font_get_glyph_index]. + [b]Note:[/b] Glyph index is specific to the font, use glyphs indices returned by [method shaped_text_get_glyphs] or [method font_get_glyph_index]. </description> </method> <method name="font_draw_glyph_outline" qualifiers="const"> @@ -91,7 +93,7 @@ <argument index="6" name="color" type="Color" default="Color(1, 1, 1, 1)" /> <description> Draws single glyph outline of size [code]outline_size[/code] into a canvas item at the position, using [code]font_rid[/code] at the size [code]size[/code]. - Note: Glyph index is specific to the font, use glyphs indices returned by [method shaped_text_get_glyphs] or [method font_get_glyph_index]. + [b]Note:[/b] Glyph index is specific to the font, use glyphs indices returned by [method shaped_text_get_glyphs] or [method font_get_glyph_index]. </description> </method> <method name="font_get_ascent" qualifiers="const"> @@ -129,7 +131,8 @@ <argument index="1" name="size" type="int" /> <argument index="2" name="glyph" type="int" /> <description> - Returns glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Returns glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="font_get_glyph_contours" qualifiers="const"> @@ -404,7 +407,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="glyph" type="int" /> <description> - Removes specified rendered glyph information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method font_remove_texture] to remove them manually. + Removes specified rendered glyph information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method font_remove_texture] to remove them manually. </description> </method> <method name="font_remove_kerning"> @@ -446,7 +450,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="texture_index" type="int" /> <description> - Removes specified texture from font cache entry. Note: This function will not remove glyphs associated with the texture, remove them manually, using [method font_remove_glyph]. + Removes specified texture from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, remove them manually, using [method font_remove_glyph]. </description> </method> <method name="font_render_glyph"> @@ -523,7 +528,7 @@ <argument index="0" name="oversampling" type="float" /> <description> Sets oversampling factor, shared by all font in the TextServer. - Note: This value can be automaticaly changed by display server. + [b]Note:[/b] This value can be automaticaly changed by display server. </description> </method> <method name="font_set_glyph_advance"> @@ -533,7 +538,8 @@ <argument index="2" name="glyph" type="int" /> <argument index="3" name="advance" type="Vector2" /> <description> - Sets glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Sets glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="font_set_glyph_offset"> @@ -797,7 +803,7 @@ <argument index="0" name="filename" type="String" /> <description> Loads optional TextServer database (e.g. ICU break iterators and dictionaries). - Note: This function should be called before any other TextServer functions used, otherwise it won't have any effect. + [b]Note:[/b] This function should be called before any other TextServer functions used, otherwise it won't have any effect. </description> </method> <method name="name_to_tag" qualifiers="const"> @@ -827,7 +833,7 @@ <argument index="0" name="filename" type="String" /> <description> Saves optional TextServer database (e.g. ICU break iterators and dictionaries) to the file. - Note: This function is used by during project export, to include TextServer database. + [b]Note:[/b] This function is used by during project export, to include TextServer database. </description> </method> <method name="shaped_text_add_object"> @@ -900,7 +906,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns the text ascent (number of pixels above the baseline for horizontal layout or to the left of baseline for vertical). - Note: overall ascent can be higher than font ascent, if some glyphs are displaced from the baseline. + [b]Note:[/b] Overall ascent can be higher than font ascent, if some glyphs are displaced from the baseline. </description> </method> <method name="shaped_text_get_carets" qualifiers="const"> @@ -916,7 +922,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns the text descent (number of pixels below the baseline for horizontal layout or to the right of baseline for vertical). - Note: overall descent can be higher than font descent, if some glyphs are displaced from the baseline. + [b]Note:[/b] Overall descent can be higher than font descent, if some glyphs are displaced from the baseline. </description> </method> <method name="shaped_text_get_direction" qualifiers="const"> @@ -1032,7 +1038,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns [code]true[/code] if text buffer is configured to display hexadecimal codes in place of invalid characters. - Note: If set to [code]false[/code], nothing is displayed in place of invalid characters. + [b]Note:[/b] If set to [code]false[/code], nothing is displayed in place of invalid characters. </description> </method> <method name="shaped_text_get_range" qualifiers="const"> @@ -1167,7 +1173,7 @@ <argument index="1" name="direction" type="int" enum="TextServer.Direction" default="0" /> <description> Sets desired text direction. If set to [code]TEXT_DIRECTION_AUTO[/code], direction will be detected based on the buffer contents and current locale. - Note: Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. + [b]Note:[/b] Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. </description> </method> <method name="shaped_text_set_orientation"> @@ -1176,7 +1182,7 @@ <argument index="1" name="orientation" type="int" enum="TextServer.Orientation" default="0" /> <description> Sets desired text orientation. - Note: Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. + [b]Note:[/b] Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. </description> </method> <method name="shaped_text_set_preserve_control"> @@ -1200,7 +1206,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Shapes buffer if it's not shaped. Returns [code]true[/code] if the string is shaped successfully. - Note: It is not necessary to call this function manually, buffer will be shaped automatically as soon as any of its output data is requested. + [b]Note:[/b] It is not necessary to call this function manually, buffer will be shaped automatically as soon as any of its output data is requested. </description> </method> <method name="shaped_text_sort_logical"> diff --git a/doc/classes/TextServerExtension.xml b/doc/classes/TextServerExtension.xml index 29571463d2..99382d5463 100644 --- a/doc/classes/TextServerExtension.xml +++ b/doc/classes/TextServerExtension.xml @@ -21,8 +21,8 @@ <argument index="1" name="orientation" type="int" enum="TextServer.Orientation" /> <description> Creates new buffer for complex text layout, with the given [code]direction[/code] and [code]orientation[/code]. To free the resulting buffer, use [method _free] method. - Note: Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. - Note: Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. + [b]Note:[/b] Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. + [b]Note:[/b] Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. </description> </method> <method name="_draw_hex_code_box" qualifiers="virtual const"> @@ -41,7 +41,8 @@ <argument index="0" name="font_rid" type="RID" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all rendered glyphs information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method _font_remove_texture] to remove them manually. + Removes all rendered glyphs information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method _font_remove_texture] to remove them manually. </description> </method> <method name="_font_clear_kerning_map" qualifiers="virtual"> @@ -64,7 +65,8 @@ <argument index="0" name="font_rid" type="RID" /> <argument index="1" name="size" type="Vector2i" /> <description> - Removes all textures from font cache entry. Note: This function will not remove glyphs associated with the texture, use [method _font_remove_glyph] to remove them manually. + Removes all textures from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, use [method _font_remove_glyph] to remove them manually. </description> </method> <method name="_font_draw_glyph" qualifiers="virtual const"> @@ -77,7 +79,7 @@ <argument index="5" name="color" type="Color" /> <description> Draws single glyph into a canvas item at the position, using [code]font_rid[/code] at the size [code]size[/code]. - Note: Glyph index is specific to the font, use glyphs indices returned by [method _shaped_text_get_glyphs] or [method _font_get_glyph_index]. + [b]Note:[/b] Glyph index is specific to the font, use glyphs indices returned by [method _shaped_text_get_glyphs] or [method _font_get_glyph_index]. </description> </method> <method name="_font_draw_glyph_outline" qualifiers="virtual const"> @@ -91,7 +93,7 @@ <argument index="6" name="color" type="Color" /> <description> Draws single glyph outline of size [code]outline_size[/code] into a canvas item at the position, using [code]font_rid[/code] at the size [code]size[/code]. - Note: Glyph index is specific to the font, use glyphs indices returned by [method _shaped_text_get_glyphs] or [method _font_get_glyph_index]. + [b]Note:[/b] Glyph index is specific to the font, use glyphs indices returned by [method _shaped_text_get_glyphs] or [method _font_get_glyph_index]. </description> </method> <method name="_font_get_ascent" qualifiers="virtual const"> @@ -129,7 +131,8 @@ <argument index="1" name="size" type="int" /> <argument index="2" name="glyph" type="int" /> <description> - Returns glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Returns glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="_font_get_glyph_contours" qualifiers="virtual const"> @@ -404,7 +407,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="glyph" type="int" /> <description> - Removes specified rendered glyph information from the cache entry. Note: This function will not remove textures associated with the glyphs, use [method _font_remove_texture] to remove them manually. + Removes specified rendered glyph information from the cache entry. + [b]Note:[/b] This function will not remove textures associated with the glyphs, use [method _font_remove_texture] to remove them manually. </description> </method> <method name="_font_remove_kerning" qualifiers="virtual"> @@ -446,7 +450,8 @@ <argument index="1" name="size" type="Vector2i" /> <argument index="2" name="texture_index" type="int" /> <description> - Removes specified texture from font cache entry. Note: This function will not remove glyphs associated with the texture, remove them manually, using [method _font_remove_glyph]. + Removes specified texture from font cache entry. + [b]Note:[/b] This function will not remove glyphs associated with the texture, remove them manually, using [method _font_remove_glyph]. </description> </method> <method name="_font_render_glyph" qualifiers="virtual"> @@ -531,7 +536,7 @@ <argument index="0" name="oversampling" type="float" /> <description> Sets oversampling factor, shared by all font in the TextServer. - Note: This value can be automaticaly changed by display server. + [b]Note:[/b] This value can be automaticaly changed by display server. </description> </method> <method name="_font_set_glyph_advance" qualifiers="virtual"> @@ -541,7 +546,8 @@ <argument index="2" name="glyph" type="int" /> <argument index="3" name="advance" type="Vector2" /> <description> - Sets glyph advance (offset of the next glyph). Note: advance for glyphs outlines is the same as the base glyph advance and is not saved. + Sets glyph advance (offset of the next glyph). + [b]Note:[/b] Advance for glyphs outlines is the same as the base glyph advance and is not saved. </description> </method> <method name="_font_set_glyph_offset" qualifiers="virtual"> @@ -804,7 +810,7 @@ <argument index="0" name="filename" type="String" /> <description> Loads optional TextServer database (e.g. ICU break iterators and dictionaries). - Note: This function should be called before any other TextServer functions used, otherwise it won't have any effect. + [b]Note:[/b] This function should be called before any other TextServer functions used, otherwise it won't have any effect. </description> </method> <method name="_name_to_tag" qualifiers="virtual const"> @@ -834,7 +840,7 @@ <argument index="0" name="filename" type="String" /> <description> Saves optional TextServer database (e.g. ICU break iterators and dictionaries) to the file. - Note: This function is used by during project export, to include TextServer database. + [b]Note:[/b] This function is used by during project export, to include TextServer database. </description> </method> <method name="_shaped_text_add_object" qualifiers="virtual"> @@ -906,7 +912,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns the text ascent (number of pixels above the baseline for horizontal layout or to the left of baseline for vertical). - Note: overall ascent can be higher than font ascent, if some glyphs are displaced from the baseline. + [b]Note:[/b] Overall ascent can be higher than font ascent, if some glyphs are displaced from the baseline. </description> </method> <method name="_shaped_text_get_carets" qualifiers="virtual const"> @@ -923,7 +929,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns the text descent (number of pixels below the baseline for horizontal layout or to the right of baseline for vertical). - Note: overall descent can be higher than font descent, if some glyphs are displaced from the baseline. + [b]Note:[/b] Overall descent can be higher than font descent, if some glyphs are displaced from the baseline. </description> </method> <method name="_shaped_text_get_direction" qualifiers="virtual const"> @@ -1041,7 +1047,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Returns [code]true[/code] if text buffer is configured to display hexadecimal codes in place of invalid characters. - Note: If set to [code]false[/code], nothing is displayed in place of invalid characters. + [b]Note:[/b] If set to [code]false[/code], nothing is displayed in place of invalid characters. </description> </method> <method name="_shaped_text_get_range" qualifiers="virtual const"> @@ -1176,7 +1182,7 @@ <argument index="1" name="direction" type="int" enum="TextServer.Direction" /> <description> Sets desired text direction. If set to [code]TEXT_DIRECTION_AUTO[/code], direction will be detected based on the buffer contents and current locale. - Note: Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. + [b]Note:[/b] Direction is ignored if server does not support [code]FEATURE_BIDI_LAYOUT[/code] feature. </description> </method> <method name="_shaped_text_set_orientation" qualifiers="virtual"> @@ -1185,7 +1191,7 @@ <argument index="1" name="orientation" type="int" enum="TextServer.Orientation" /> <description> Sets desired text orientation. - Note: Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. + [b]Note:[/b] Orientation is ignored if server does not support [code]FEATURE_VERTICAL_LAYOUT[/code] feature. </description> </method> <method name="_shaped_text_set_preserve_control" qualifiers="virtual"> @@ -1209,7 +1215,7 @@ <argument index="0" name="shaped" type="RID" /> <description> Shapes buffer if it's not shaped. Returns [code]true[/code] if the string is shaped successfully. - Note: It is not necessary to call this function manually, buffer will be shaped automatically as soon as any of its output data is requested. + [b]Note:[/b] It is not necessary to call this function manually, buffer will be shaped automatically as soon as any of its output data is requested. </description> </method> <method name="_shaped_text_sort_logical" qualifiers="virtual"> diff --git a/doc/classes/TextServerManager.xml b/doc/classes/TextServerManager.xml index aa2177c3b1..d6a1cde945 100644 --- a/doc/classes/TextServerManager.xml +++ b/doc/classes/TextServerManager.xml @@ -5,7 +5,7 @@ </brief_description> <description> [TextServerManager] is the API backend for loading, enumeration and switching [TextServer]s. - Note: Switching text server at runtime is possible, but will invalidate all fonts and text buffers. Make sure to unload all controls, fonts, and themes before doing so. + [b]Note:[/b] Switching text server at runtime is possible, but will invalidate all fonts and text buffers. Make sure to unload all controls, fonts, and themes before doing so. </description> <tutorials> </tutorials> diff --git a/doc/classes/Theme.xml b/doc/classes/Theme.xml index edf5874432..52a419ce0f 100644 --- a/doc/classes/Theme.xml +++ b/doc/classes/Theme.xml @@ -8,7 +8,7 @@ Theme resources can alternatively be loaded by writing them in a [code].theme[/code] file, see the documentation for more information. </description> <tutorials> - <link title="GUI skinning">https://docs.godotengine.org/en/latest/tutorials/gui/gui_skinning.html</link> + <link title="GUI skinning">https://docs.godotengine.org/en/latest/tutorials/ui/gui_skinning.html</link> </tutorials> <methods> <method name="clear"> @@ -273,6 +273,24 @@ Returns [code]false[/code] if the theme does not have [code]theme_type[/code]. </description> </method> + <method name="has_default_base_scale" qualifiers="const"> + <return type="bool" /> + <description> + Returns [code]true[/code] if this theme has a valid [member default_base_scale] value. + </description> + </method> + <method name="has_default_font" qualifiers="const"> + <return type="bool" /> + <description> + Returns [code]true[/code] if this theme has a valid [member default_font] value. + </description> + </method> + <method name="has_default_font_size" qualifiers="const"> + <return type="bool" /> + <description> + Returns [code]true[/code] if this theme has a valid [member default_font_size] value. + </description> + </method> <method name="has_font" qualifiers="const"> <return type="bool" /> <argument index="0" name="name" type="StringName" /> @@ -479,16 +497,22 @@ Marks [code]theme_type[/code] as being a variation of [code]base_type[/code]. This adds [code]theme_type[/code] as a suggested option for [member Control.theme_type_variation] on a [Control] that is of the [code]base_type[/code] class. Variations can also be nested, i.e. [code]base_type[/code] can be another variation. If a chain of variations ends with a [code]base_type[/code] matching a class of a [Control], the whole chain is going to be suggested as options. - Note: Suggestions only show up if this [Theme] is set as the project default theme. See [member ProjectSettings.gui/theme/custom]. + [b]Note:[/b] Suggestions only show up if this [Theme] is set as the project default theme. See [member ProjectSettings.gui/theme/custom]. </description> </method> </methods> <members> + <member name="default_base_scale" type="float" setter="set_default_base_scale" getter="get_default_base_scale" default="0.0"> + The default base scale factor of this [Theme] resource. Used by some controls to scale their visual properties based on a global scale factor. If this value is set to [code]0.0[/code], the global scale factor is used. + Use [method has_default_base_scale] to check if this value is valid. + </member> <member name="default_font" type="Font" setter="set_default_font" getter="get_default_font"> - The theme's default font. + The default font of this [Theme] resource. Used as a fallback value for font items defined in this theme, but having invalid values. If this value is also invalid, the global default value is used. + Use [method has_default_font] to check if this value is valid. </member> <member name="default_font_size" type="int" setter="set_default_font_size" getter="get_default_font_size" default="-1"> - The theme's default font size. Set to [code]-1[/code] to ignore and use global default. + The default font size of this [Theme] resource. Used as a fallback value for font size items defined in this theme, but having invalid values. If this value is set to [code]-1[/code], the global default value is used. + Use [method has_default_font_size] to check if this value is valid. </member> </members> <constants> diff --git a/doc/classes/Thread.xml b/doc/classes/Thread.xml index ae5c0761b1..d5069dd8f3 100644 --- a/doc/classes/Thread.xml +++ b/doc/classes/Thread.xml @@ -8,8 +8,8 @@ [b]Note:[/b] Breakpoints won't break on code if it's running in a thread. This is a current limitation of the GDScript debugger. </description> <tutorials> - <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/threads/using_multiple_threads.html</link> - <link title="Thread-safe APIs">https://docs.godotengine.org/en/latest/tutorials/threads/thread_safe_apis.html</link> + <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/performance/using_multiple_threads.html</link> + <link title="Thread-safe APIs">https://docs.godotengine.org/en/latest/tutorials/performance/thread_safe_apis.html</link> <link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link> </tutorials> <methods> diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml index e5fe823be6..532c9a7128 100644 --- a/doc/classes/TileMap.xml +++ b/doc/classes/TileMap.xml @@ -73,7 +73,7 @@ <return type="Vector2i" /> <argument index="0" name="body" type="RID" /> <description> - Returns the coodinates of the tile for given physics body RID. Such RID can be retrieved from [member KinematicCollision2D.collider_rid], when colliding with a tile. + Returns the coodinates of the tile for given physics body RID. Such RID can be retrieved from [method KinematicCollision2D.get_collider_rid], when colliding with a tile. </description> </method> <method name="get_layer_name" qualifiers="const"> diff --git a/doc/classes/Timer.xml b/doc/classes/Timer.xml index b91f159160..a6ea5738d5 100644 --- a/doc/classes/Timer.xml +++ b/doc/classes/Timer.xml @@ -22,7 +22,7 @@ <argument index="0" name="time_sec" type="float" default="-1" /> <description> Starts the timer. Sets [code]wait_time[/code] to [code]time_sec[/code] if [code]time_sec > 0[/code]. This also resets the remaining time to [code]wait_time[/code]. - [b]Note:[/b] this method will not resume a paused timer. See [member paused]. + [b]Note:[/b] This method will not resume a paused timer. See [member paused]. </description> </method> <method name="stop"> diff --git a/doc/classes/TouchScreenButton.xml b/doc/classes/TouchScreenButton.xml index e75a41a936..f1becb6906 100644 --- a/doc/classes/TouchScreenButton.xml +++ b/doc/classes/TouchScreenButton.xml @@ -30,7 +30,7 @@ </member> <member name="passby_press" type="bool" setter="set_passby_press" getter="is_passby_press_enabled" default="false"> If [code]true[/code], the [signal pressed] and [signal released] signals are emitted whenever a pressed finger goes in and out of the button, even if the pressure started outside the active area of the button. - [b]Note:[/b] this is a "pass-by" (not "bypass") press mode. + [b]Note:[/b] This is a "pass-by" (not "bypass") press mode. </member> <member name="pressed" type="Texture2D" setter="set_texture_pressed" getter="get_texture_pressed"> The button's texture for the pressed state. diff --git a/doc/classes/Transform2D.xml b/doc/classes/Transform2D.xml index 4fd788467d..d64752a00f 100644 --- a/doc/classes/Transform2D.xml +++ b/doc/classes/Transform2D.xml @@ -8,7 +8,7 @@ For more information, read the "Matrices and transforms" documentation article. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Matrices and transforms">https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html</link> <link title="Matrix Transform Demo">https://godotengine.org/asset-library/asset/584</link> <link title="2.5D Demo">https://godotengine.org/asset-library/asset/583</link> diff --git a/doc/classes/Transform3D.xml b/doc/classes/Transform3D.xml index 337e7d2693..63a7746328 100644 --- a/doc/classes/Transform3D.xml +++ b/doc/classes/Transform3D.xml @@ -8,7 +8,7 @@ For more information, read the "Matrices and transforms" documentation article. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Matrices and transforms">https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html</link> <link title="Using 3D transforms">https://docs.godotengine.org/en/latest/tutorials/3d/using_transforms.html</link> <link title="Matrix Transform Demo">https://godotengine.org/asset-library/asset/584</link> diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml index b61d5bea0e..4035fb0ad2 100644 --- a/doc/classes/Vector2.xml +++ b/doc/classes/Vector2.xml @@ -9,7 +9,7 @@ [b]Note:[/b] In a boolean context, a Vector2 will evaluate to [code]false[/code] if it's equal to [code]Vector2(0, 0)[/code]. Otherwise, a Vector2 will always evaluate to [code]true[/code]. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="Advanced vector math">https://docs.godotengine.org/en/latest/tutorials/math/vectors_advanced.html</link> <link title="3Blue1Brown Essence of Linear Algebra">https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab</link> diff --git a/doc/classes/Vector2i.xml b/doc/classes/Vector2i.xml index 2e69d6efdf..52fd8c6780 100644 --- a/doc/classes/Vector2i.xml +++ b/doc/classes/Vector2i.xml @@ -9,7 +9,7 @@ [b]Note:[/b] In a boolean context, a Vector2i will evaluate to [code]false[/code] if it's equal to [code]Vector2i(0, 0)[/code]. Otherwise, a Vector2i will always evaluate to [code]true[/code]. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="3Blue1Brown Essence of Linear Algebra">https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab</link> </tutorials> diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml index 9f2ea7b2a0..267a0d2e9e 100644 --- a/doc/classes/Vector3.xml +++ b/doc/classes/Vector3.xml @@ -9,7 +9,7 @@ [b]Note:[/b] In a boolean context, a Vector3 will evaluate to [code]false[/code] if it's equal to [code]Vector3(0, 0, 0)[/code]. Otherwise, a Vector3 will always evaluate to [code]true[/code]. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="Advanced vector math">https://docs.godotengine.org/en/latest/tutorials/math/vectors_advanced.html</link> <link title="3Blue1Brown Essence of Linear Algebra">https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab</link> diff --git a/doc/classes/Vector3i.xml b/doc/classes/Vector3i.xml index bc3712ba3e..2a7ee1ffb8 100644 --- a/doc/classes/Vector3i.xml +++ b/doc/classes/Vector3i.xml @@ -9,7 +9,7 @@ [b]Note:[/b] In a boolean context, a Vector3i will evaluate to [code]false[/code] if it's equal to [code]Vector3i(0, 0, 0)[/code]. Otherwise, a Vector3i will always evaluate to [code]true[/code]. </description> <tutorials> - <link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> + <link title="Math documentation index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link> <link title="Vector math">https://docs.godotengine.org/en/latest/tutorials/math/vector_math.html</link> <link title="3Blue1Brown Essence of Linear Algebra">https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab</link> </tutorials> diff --git a/doc/classes/Viewport.xml b/doc/classes/Viewport.xml index 06a7177bfc..cdb9e7632b 100644 --- a/doc/classes/Viewport.xml +++ b/doc/classes/Viewport.xml @@ -12,8 +12,8 @@ Finally, viewports can also behave as render targets, in which case they will not be visible unless the associated texture is used to draw. </description> <tutorials> + <link title="Using Viewports">https://docs.godotengine.org/en/latest/tutorials/rendering/viewports.html</link> <link title="Viewport and canvas transforms">https://docs.godotengine.org/en/latest/tutorials/2d/2d_transforms.html</link> - <link title="Viewports tutorial index">https://docs.godotengine.org/en/latest/tutorials/viewports/index.html</link> <link title="GUI in 3D Demo">https://godotengine.org/asset-library/asset/127</link> <link title="3D in 2D Demo">https://godotengine.org/asset-library/asset/128</link> <link title="2D in 3D Demo">https://godotengine.org/asset-library/asset/129</link> diff --git a/doc/classes/VisualShaderNode.xml b/doc/classes/VisualShaderNode.xml index 2cff70b4f1..b752e94490 100644 --- a/doc/classes/VisualShaderNode.xml +++ b/doc/classes/VisualShaderNode.xml @@ -7,7 +7,7 @@ Visual shader graphs consist of various nodes. Each node in the graph is a separate object and they are represented as a rectangular boxes with title and a set of properties. Each node has also connection ports that allow to connect it to another nodes and control the flow of the shader. </description> <tutorials> - <link title="VisualShaders">https://docs.godotengine.org/en/latest/tutorials/shading/visual_shaders.html</link> + <link title="VisualShaders">https://docs.godotengine.org/en/latest/tutorials/shaders/visual_shaders.html</link> </tutorials> <methods> <method name="clear_default_input_values"> diff --git a/doc/classes/VisualShaderNodeInput.xml b/doc/classes/VisualShaderNodeInput.xml index 68f64ad98e..46d7dd6322 100644 --- a/doc/classes/VisualShaderNodeInput.xml +++ b/doc/classes/VisualShaderNodeInput.xml @@ -7,7 +7,7 @@ Gives access to input variables (built-ins) available for the shader. See the shading reference for the list of available built-ins for each shader type (check [code]Tutorials[/code] section for link). </description> <tutorials> - <link title="Shading reference index">https://docs.godotengine.org/en/stable/tutorials/shading/shading_reference/index.html</link> + <link title="Shading reference index">https://docs.godotengine.org/en/latest/tutorials/shaders/shader_reference/index.html</link> </tutorials> <methods> <method name="get_input_real_name" qualifiers="const"> diff --git a/doc/classes/VoxelGI.xml b/doc/classes/VoxelGI.xml index eceb651d5e..f6470782ee 100644 --- a/doc/classes/VoxelGI.xml +++ b/doc/classes/VoxelGI.xml @@ -9,7 +9,7 @@ [b]Note:[/b] Meshes should have sufficiently thick walls to avoid light leaks (avoid one-sided walls). For interior levels, enclose your level geometry in a sufficiently large box and bridge the loops to close the mesh. </description> <tutorials> - <link title="GI probes">https://docs.godotengine.org/en/latest/tutorials/3d/voxel_gi.html</link> + <link title="GI probes">https://docs.godotengine.org/en/latest/tutorials/3d/gi_probes.html</link> <link title="Third Person Shooter Demo">https://godotengine.org/asset-library/asset/678</link> </tutorials> <methods> diff --git a/doc/classes/Window.xml b/doc/classes/Window.xml index 15d844aacb..0653c8b453 100644 --- a/doc/classes/Window.xml +++ b/doc/classes/Window.xml @@ -59,6 +59,21 @@ <description> </description> </method> + <method name="get_theme_default_base_scale" qualifiers="const"> + <return type="float" /> + <description> + </description> + </method> + <method name="get_theme_default_font" qualifiers="const"> + <return type="Font" /> + <description> + </description> + </method> + <method name="get_theme_default_font_size" qualifiers="const"> + <return type="int" /> + <description> + </description> + </method> <method name="get_theme_font" qualifiers="const"> <return type="Font" /> <argument index="0" name="name" type="StringName" /> diff --git a/doc/classes/XRCamera3D.xml b/doc/classes/XRCamera3D.xml index 682a797b5e..31f05ca06c 100644 --- a/doc/classes/XRCamera3D.xml +++ b/doc/classes/XRCamera3D.xml @@ -8,6 +8,6 @@ The position and orientation of this node is automatically updated by the XR Server to represent the location of the HMD if such tracking is available and can thus be used by game logic. Note that, in contrast to the XR Controller, the render thread has access to the most up-to-date tracking data of the HMD and the location of the XRCamera3D can lag a few milliseconds behind what is used for rendering as a result. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> </class> diff --git a/doc/classes/XRController3D.xml b/doc/classes/XRController3D.xml index 1a05a7b651..35edf5c2b2 100644 --- a/doc/classes/XRController3D.xml +++ b/doc/classes/XRController3D.xml @@ -9,7 +9,7 @@ The position of the controller node is automatically updated by the [XRServer]. This makes this node ideal to add child nodes to visualize the controller. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <methods> <method name="get_controller_name" qualifiers="const"> diff --git a/doc/classes/XRInterface.xml b/doc/classes/XRInterface.xml index 2a740ab1e8..ffc2bc138d 100644 --- a/doc/classes/XRInterface.xml +++ b/doc/classes/XRInterface.xml @@ -8,7 +8,7 @@ Interfaces should be written in such a way that simply enabling them will give us a working setup. You can query the available interfaces through [XRServer]. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <methods> <method name="get_camera_feed_id"> diff --git a/doc/classes/XROrigin3D.xml b/doc/classes/XROrigin3D.xml index cdf319093c..0d8acfeb1b 100644 --- a/doc/classes/XROrigin3D.xml +++ b/doc/classes/XROrigin3D.xml @@ -10,7 +10,7 @@ For example, if your character is driving a car, the XROrigin3D node should be a child node of this car. Or, if you're implementing a teleport system to move your character, you should change the position of this node. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <members> <member name="world_scale" type="float" setter="set_world_scale" getter="get_world_scale" default="1.0"> diff --git a/doc/classes/XRPositionalTracker.xml b/doc/classes/XRPositionalTracker.xml index 8cc7c872b6..d231bfde74 100644 --- a/doc/classes/XRPositionalTracker.xml +++ b/doc/classes/XRPositionalTracker.xml @@ -9,7 +9,7 @@ The [XRController3D] and [XRAnchor3D] both consume objects of this type and should be used in your project. The positional trackers are just under-the-hood objects that make this all work. These are mostly exposed so that GDNative-based interfaces can interact with them. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <methods> <method name="get_joy_id" qualifiers="const"> diff --git a/doc/classes/XRServer.xml b/doc/classes/XRServer.xml index 85170804cc..0929094fd1 100644 --- a/doc/classes/XRServer.xml +++ b/doc/classes/XRServer.xml @@ -7,7 +7,7 @@ The AR/VR server is the heart of our Advanced and Virtual Reality solution and handles all the processing. </description> <tutorials> - <link title="VR tutorial index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> + <link title="VR documentation index">https://docs.godotengine.org/en/latest/tutorials/vr/index.html</link> </tutorials> <methods> <method name="add_interface"> diff --git a/doc/tools/makerst.py b/doc/tools/makerst.py index a23324fd24..1ec9627c2c 100755 --- a/doc/tools/makerst.py +++ b/doc/tools/makerst.py @@ -871,7 +871,7 @@ def rstize_text(text, state): # type: (str, State) -> str inside_url = True url_has_name = False elif cmd == "/url": - tag_text = ("" if url_has_name else url_link) + " <" + url_link + ">`_" + tag_text = ("" if url_has_name else url_link) + " <" + url_link + ">`__" tag_depth -= 1 escape_post = True inside_url = False @@ -1053,6 +1053,11 @@ def make_method_signature( ret_type = method_def.return_type.to_rst(state) ref_type = "method" + # FIXME: Need to add proper support for operator methods, but generating a unique + # and valid ref for them is not trivial. + if method_def.name.startswith("operator "): + make_ref = False + out = "" if make_ref: @@ -1102,6 +1107,7 @@ def make_footer(): # type: () -> str ".. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`\n" ".. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`\n" ".. |constructor| replace:: :abbr:`constructor (This method is used to construct a type.)`\n" + ".. |static| replace:: :abbr:`static (This method doesn't need an instance to be called, so it can be called directly using the class name.)`\n" ".. |operator| replace:: :abbr:`operator (This method describes a valid operator to use with this type as left-hand operand.)`\n" ) # fmt: on @@ -1126,9 +1132,9 @@ def make_link(url, title): # type: (str, str) -> str # External link, for example: # `http://enet.bespin.org/usergroup0.html` if title != "": - return "`" + title + " <" + url + ">`_" + return "`" + title + " <" + url + ">`__" else: - return "`" + url + " <" + url + ">`_" + return "`" + url + " <" + url + ">`__" if __name__ == "__main__": diff --git a/drivers/unix/ip_unix.cpp b/drivers/unix/ip_unix.cpp index 8a880ab9c8..d32592e81a 100644 --- a/drivers/unix/ip_unix.cpp +++ b/drivers/unix/ip_unix.cpp @@ -36,9 +36,9 @@ #ifdef WINDOWS_ENABLED #include <stdio.h> -#include <winsock2.h> -// Needs to be included after winsocks2.h +#define WIN32_LEAN_AND_MEAN #include <windows.h> +#include <winsock2.h> #include <ws2tcpip.h> #ifndef UWP_ENABLED #include <iphlpapi.h> diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp index 276fda2a8f..3b2f078120 100644 --- a/drivers/wasapi/audio_driver_wasapi.cpp +++ b/drivers/wasapi/audio_driver_wasapi.cpp @@ -274,7 +274,7 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error"); } - bool using_audio_client_3 = !p_capture; // IID_IAudioClient3 is only used for adjustable output latency (not input) + using_audio_client_3 = !p_capture; // IID_IAudioClient3 is only used for adjustable output latency (not input) if (using_audio_client_3) { hr = device->Activate(IID_IAudioClient3, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client); if (hr != S_OK) { @@ -301,7 +301,7 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c } if (using_audio_client_3) { - AudioClientProperties audioProps; + AudioClientProperties audioProps{}; audioProps.cbSize = sizeof(AudioClientProperties); audioProps.bIsOffload = FALSE; audioProps.eCategory = AudioCategory_GameEffects; @@ -378,6 +378,13 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c // Due to WASAPI Shared Mode we have no control of the buffer size buffer_frames = max_frames; + + int64_t latency = 0; + audio_output.audio_client->GetStreamLatency(&latency); + // WASAPI REFERENCE_TIME units are 100 nanoseconds per unit + // https://docs.microsoft.com/en-us/windows/win32/directshow/reference-time + // Convert REFTIME to seconds as godot uses for latency + real_latency = (float)latency / (float)REFTIMES_PER_SEC; } else { IAudioClient3 *device_audio_client_3 = (IAudioClient3 *)p_device->audio_client; @@ -411,6 +418,11 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c hr = device_audio_client_3->InitializeSharedAudioStream(0, period_frames, pwfex, nullptr); ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: InitializeSharedAudioStream failed with error 0x" + String::num_uint64(hr, 16) + "."); + uint32_t output_latency_in_frames; + WAVEFORMATEX *current_pwfex; + device_audio_client_3->GetCurrentSharedModeEnginePeriod(¤t_pwfex, &output_latency_in_frames); + real_latency = (float)output_latency_in_frames / (float)current_pwfex->nSamplesPerSec; + CoTaskMemFree(current_pwfex); } if (p_capture) { @@ -518,6 +530,10 @@ int AudioDriverWASAPI::get_mix_rate() const { return mix_rate; } +float AudioDriverWASAPI::get_latency() { + return real_latency; +} + AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const { return get_speaker_mode_by_total_channels(channels); } diff --git a/drivers/wasapi/audio_driver_wasapi.h b/drivers/wasapi/audio_driver_wasapi.h index 312b6a6781..6df9b4d2ee 100644 --- a/drivers/wasapi/audio_driver_wasapi.h +++ b/drivers/wasapi/audio_driver_wasapi.h @@ -39,6 +39,7 @@ #include <audioclient.h> #include <mmdeviceapi.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> class AudioDriverWASAPI : public AudioDriver { @@ -72,6 +73,8 @@ class AudioDriverWASAPI : public AudioDriver { int mix_rate = 0; int buffer_frames = 0; int target_latency_ms = 0; + float real_latency = 0.0; + bool using_audio_client_3 = false; bool thread_exited = false; mutable bool exit_thread = false; @@ -98,6 +101,7 @@ public: virtual Error init(); virtual void start(); virtual int get_mix_rate() const; + virtual float get_latency(); virtual SpeakerMode get_speaker_mode() const; virtual Array get_device_list(); virtual String get_device(); diff --git a/drivers/windows/dir_access_windows.cpp b/drivers/windows/dir_access_windows.cpp index f7a5f7279e..3e98e36d14 100644 --- a/drivers/windows/dir_access_windows.cpp +++ b/drivers/windows/dir_access_windows.cpp @@ -37,6 +37,7 @@ #include <stdio.h> #include <wchar.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> /* @@ -256,6 +257,11 @@ Error DirAccessWindows::rename(String p_path, String p_new_path) { // If we're only changing file name case we need to do a little juggling if (p_path.to_lower() == p_new_path.to_lower()) { + if (dir_exists(p_path)) { + // The path is a dir; just rename + return ::_wrename((LPCWSTR)(p_path.utf16().get_data()), (LPCWSTR)(p_new_path.utf16().get_data())) == 0 ? OK : FAILED; + } + // The path is a file; juggle WCHAR tmpfile[MAX_PATH]; if (!GetTempFileNameW((LPCWSTR)(fix_path(get_current_dir()).utf16().get_data()), nullptr, 0, tmpfile)) { diff --git a/drivers/windows/file_access_windows.cpp b/drivers/windows/file_access_windows.cpp index 775c999b15..035c44a28c 100644 --- a/drivers/windows/file_access_windows.cpp +++ b/drivers/windows/file_access_windows.cpp @@ -37,6 +37,7 @@ #include <share.h> // _SH_DENYNO #include <shlwapi.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <errno.h> diff --git a/drivers/winmidi/midi_driver_winmidi.h b/drivers/winmidi/midi_driver_winmidi.h index bb9a87d610..2f691489b3 100644 --- a/drivers/winmidi/midi_driver_winmidi.h +++ b/drivers/winmidi/midi_driver_winmidi.h @@ -37,6 +37,7 @@ #include "core/templates/vector.h" #include <stdio.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mmsystem.h> diff --git a/drivers/xaudio2/audio_driver_xaudio2.h b/drivers/xaudio2/audio_driver_xaudio2.h index d3938a19d0..c1910d3f5d 100644 --- a/drivers/xaudio2/audio_driver_xaudio2.h +++ b/drivers/xaudio2/audio_driver_xaudio2.h @@ -36,6 +36,7 @@ #include "servers/audio_server.h" #include <mmsystem.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <wrl/client.h> #include <xaudio2.h> diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp index a88adf3634..2010ee01db 100644 --- a/editor/editor_export.cpp +++ b/editor/editor_export.cpp @@ -1046,17 +1046,19 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> & return err; } } - if (FileAccess::exists(ResourceUID::CACHE_FILE)) { - Vector<uint8_t> array = FileAccess::get_file_as_array(ResourceUID::CACHE_FILE); - err = p_func(p_udata, ResourceUID::CACHE_FILE, array, idx, total, enc_in_filters, enc_ex_filters, key); + String resource_cache_file = ResourceUID::get_cache_file(); + if (FileAccess::exists(resource_cache_file)) { + Vector<uint8_t> array = FileAccess::get_file_as_array(resource_cache_file); + err = p_func(p_udata, resource_cache_file, array, idx, total, enc_in_filters, enc_ex_filters, key); if (err != OK) { return err; } } - if (FileAccess::exists(NativeExtension::EXTENSION_LIST_CONFIG_FILE)) { - Vector<uint8_t> array = FileAccess::get_file_as_array(NativeExtension::EXTENSION_LIST_CONFIG_FILE); - err = p_func(p_udata, NativeExtension::EXTENSION_LIST_CONFIG_FILE, array, idx, total, enc_in_filters, enc_ex_filters, key); + String extension_list_config_file = NativeExtension::get_extension_list_config_file(); + if (FileAccess::exists(extension_list_config_file)) { + Vector<uint8_t> array = FileAccess::get_file_as_array(extension_list_config_file); + err = p_func(p_udata, extension_list_config_file, array, idx, total, enc_in_filters, enc_ex_filters, key); if (err != OK) { return err; } diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp index 8956983646..675234959a 100644 --- a/editor/editor_file_dialog.cpp +++ b/editor/editor_file_dialog.cpp @@ -588,7 +588,7 @@ void EditorFileDialog::_item_list_item_rmb_selected(int p_item, const Vector2 &p continue; } Dictionary item_meta = item_list->get_item_metadata(i); - if (String(item_meta["path"]).begins_with("res://.godot")) { + if (String(item_meta["path"]).begins_with(ProjectSettings::get_singleton()->get_project_data_path())) { allow_delete = false; break; } diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp index 0882b525d7..953989aadd 100644 --- a/editor/editor_file_system.cpp +++ b/editor/editor_file_system.cpp @@ -2163,6 +2163,10 @@ Error EditorFileSystem::_resource_import(const String &p_path) { } bool EditorFileSystem::_should_skip_directory(const String &p_path) { + if (p_path == ProjectSettings::get_singleton()->get_project_data_path()) { + return true; + } + if (FileAccess::exists(p_path.plus_file("project.godot"))) { // skip if another project inside this return true; @@ -2228,7 +2232,7 @@ void EditorFileSystem::move_group_file(const String &p_path, const String &p_new } ResourceUID::ID EditorFileSystem::_resource_saver_get_resource_id_for_path(const String &p_path, bool p_generate) { - if (!p_path.is_resource_file() || p_path.begins_with("res://.godot")) { + if (!p_path.is_resource_file() || p_path.begins_with(ProjectSettings::get_singleton()->get_project_data_path())) { //saved externally (configuration file) or internal file, do not assign an ID. return ResourceUID::INVALID_ID; } @@ -2286,17 +2290,18 @@ bool EditorFileSystem::_scan_extensions() { } } + String extension_list_config_file = NativeExtension::get_extension_list_config_file(); if (extensions.size()) { if (extensions_added.size() || extensions_removed.size()) { //extensions were added or removed - FileAccessRef f = FileAccess::open(NativeExtension::EXTENSION_LIST_CONFIG_FILE, FileAccess::WRITE); + FileAccessRef f = FileAccess::open(extension_list_config_file, FileAccess::WRITE); for (const String &E : extensions) { f->store_line(E); } } } else { - if (loaded_extensions.size() || FileAccess::exists(NativeExtension::EXTENSION_LIST_CONFIG_FILE)) { //extensions were removed + if (loaded_extensions.size() || FileAccess::exists(extension_list_config_file)) { //extensions were removed DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - da->remove(NativeExtension::EXTENSION_LIST_CONFIG_FILE); + da->remove(extension_list_config_file); } } diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index a8f05baf8f..5fd0a41788 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -49,6 +49,7 @@ #include "core/version.h" #include "core/version_hash.gen.h" #include "main/main.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/gui/center_container.h" #include "scene/gui/control.h" #include "scene/gui/dialogs.h" @@ -113,7 +114,6 @@ #include "editor/import/resource_importer_texture_atlas.h" #include "editor/import/resource_importer_wav.h" #include "editor/import/scene_import_settings.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "editor/import_dock.h" #include "editor/multi_node_edit.h" #include "editor/node_dock.h" @@ -3852,8 +3852,6 @@ void EditorNode::register_editor_types() { GDREGISTER_CLASS(EditorSpinSlider); GDREGISTER_CLASS(EditorResourcePicker); GDREGISTER_CLASS(EditorScriptPicker); - GDREGISTER_CLASS(EditorSceneImporterMesh); - GDREGISTER_CLASS(EditorSceneImporterMeshNode3D); GDREGISTER_VIRTUAL_CLASS(FileSystemDock); diff --git a/editor/editor_paths.cpp b/editor/editor_paths.cpp index c9817190dd..71f13c0c2f 100644 --- a/editor/editor_paths.cpp +++ b/editor/editor_paths.cpp @@ -87,6 +87,8 @@ void EditorPaths::_bind_methods() { EditorPaths::EditorPaths() { singleton = this; + project_data_dir = ProjectSettings::get_singleton()->get_project_data_path(); + // Self-contained mode if a `._sc_` or `_sc_` file is present in executable dir. String exe_path = OS::get_singleton()->get_executable_path().get_base_dir(); { @@ -183,7 +185,7 @@ EditorPaths::EditorPaths() { } } - // Validate or create project-specific editor data dir (`res://.godot`), + // Validate or create project-specific editor data dir, // including shader cache subdir. if (Main::is_project_manager() || Main::is_cmdline_tool()) { @@ -205,8 +207,9 @@ EditorPaths::EditorPaths() { dir_res->make_dir("editor"); } // Imported assets dir. - if (!dir_res->dir_exists(ProjectSettings::IMPORTED_FILES_PATH)) { - dir_res->make_dir(ProjectSettings::IMPORTED_FILES_PATH); + String imported_files_path = ProjectSettings::get_singleton()->get_imported_files_path(); + if (!dir_res->dir_exists(imported_files_path)) { + dir_res->make_dir(imported_files_path); } } } diff --git a/editor/editor_paths.h b/editor/editor_paths.h index 2c156b7c96..cf94ed797a 100644 --- a/editor/editor_paths.h +++ b/editor/editor_paths.h @@ -41,7 +41,7 @@ class EditorPaths : public Object { String data_dir; // Editor data (templates, shader cache, etc.). String config_dir; // Editor config (settings, profiles, themes, etc.). String cache_dir; // Editor cache (thumbnails, tmp generated files). - String project_data_dir = "res://.godot"; // Project-specific data (metadata, shader cache, etc.). + String project_data_dir; // Project-specific data (metadata, shader cache, etc.). bool self_contained = false; // Self-contained means everything goes to `editor_data` dir. String self_contained_file; // Self-contained file with configuration. diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index f0e97a7787..43d458c58e 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -480,6 +480,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { // SceneTree _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); + _initial_set("docks/scene_tree/auto_expand_to_selected", true); // FileSystem EDITOR_SETTING(Variant::INT, PROPERTY_HINT_RANGE, "docks/filesystem/thumbnail_size", 64, "32,128,16") diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index 76658c5adb..2d4db48f2a 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -293,7 +293,8 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme = Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { Ref<Theme> theme = Ref<Theme>(memnew(Theme)); - const float default_contrast = 0.3; + // Controls may rely on the scale for their internal drawing logic. + theme->set_default_theme_base_scale(EDSCALE); // Theme settings Color accent_color = EDITOR_GET("interface/theme/accent_color"); @@ -311,6 +312,8 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { Color preset_base_color; float preset_contrast = 0; + const float default_contrast = 0.3; + // Please use alphabetical order if you're adding a new theme here // (after "Custom") diff --git a/editor/find_in_files.cpp b/editor/find_in_files.cpp index 380b269675..283496c0f1 100644 --- a/editor/find_in_files.cpp +++ b/editor/find_in_files.cpp @@ -233,8 +233,9 @@ void FindInFiles::_scan_dir(String path, PackedStringArray &out_folders) { break; } - // Ignore special dirs (such as .git and .import) - if (file == "." || file == ".." || file.begins_with(".")) { + // Ignore special dirs (such as .git and project data directory) + String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name(); + if (file.begins_with(".") || file == project_data_dir_name) { continue; } if (dir->current_is_hidden()) { diff --git a/editor/import/editor_import_collada.cpp b/editor/import/editor_import_collada.cpp index 3de7426302..4b01595028 100644 --- a/editor/import/editor_import_collada.cpp +++ b/editor/import/editor_import_collada.cpp @@ -33,8 +33,8 @@ #include "core/os/os.h" #include "editor/editor_node.h" #include "editor/import/collada.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "scene/3d/camera_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/light_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/node_3d.h" @@ -42,6 +42,7 @@ #include "scene/3d/skeleton_3d.h" #include "scene/animation/animation_player.h" #include "scene/resources/animation.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/packed_scene.h" #include "scene/resources/surface_tool.h" @@ -68,7 +69,7 @@ struct ColladaImport { Map<String, NodeMap> node_map; //map from collada node to engine node Map<String, String> node_name_map; //map from collada node to engine node - Map<String, Ref<EditorSceneImporterMesh>> mesh_cache; + Map<String, Ref<ImporterMesh>> mesh_cache; Map<String, Ref<Curve3D>> curve_cache; Map<String, Ref<Material>> material_cache; Map<Collada::Node *, Skeleton3D *> skeleton_map; @@ -87,7 +88,7 @@ struct ColladaImport { Error _create_scene(Collada::Node *p_node, Node3D *p_parent); Error _create_resources(Collada::Node *p_node, bool p_use_compression); Error _create_material(const String &p_target); - Error _create_mesh_surfaces(bool p_optimize, Ref<EditorSceneImporterMesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<EditorSceneImporterMesh>> p_morph_meshes = Vector<Ref<EditorSceneImporterMesh>>(), bool p_use_compression = false, bool p_use_mesh_material = false); + Error _create_mesh_surfaces(bool p_optimize, Ref<ImporterMesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<ImporterMesh>> p_morph_meshes = Vector<Ref<ImporterMesh>>(), bool p_use_compression = false, bool p_use_mesh_material = false); Error load(const String &p_path, int p_flags, bool p_force_make_tangents = false, bool p_use_compression = false); void _fix_param_animation_tracks(); void create_animation(int p_clip, bool p_make_tracks_in_all_bones, bool p_import_value_tracks); @@ -282,8 +283,8 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Node3D *p_parent) { node = memnew(Path3D); } else { //mesh since nothing else - node = memnew(EditorSceneImporterMeshNode3D); - //Object::cast_to<EditorSceneImporterMeshNode3D>(node)->set_flag(GeometryInstance3D::FLAG_USE_BAKED_LIGHT, true); + node = memnew(ImporterMeshInstance3D); + //Object::cast_to<ImporterMeshInstance3D>(node)->set_flag(GeometryInstance3D::FLAG_USE_BAKED_LIGHT, true); } } break; case Collada::Node::TYPE_SKELETON: { @@ -457,7 +458,7 @@ Error ColladaImport::_create_material(const String &p_target) { return OK; } -Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<EditorSceneImporterMesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<EditorSceneImporterMesh>> p_morph_meshes, bool p_use_compression, bool p_use_mesh_material) { +Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<ImporterMesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<ImporterMesh>> p_morph_meshes, bool p_use_compression, bool p_use_mesh_material) { bool local_xform_mirror = p_local_xform.basis.determinant() < 0; if (p_morph_data) { @@ -1087,10 +1088,10 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres } } - if (Object::cast_to<EditorSceneImporterMeshNode3D>(node)) { + if (Object::cast_to<ImporterMeshInstance3D>(node)) { Collada::NodeGeometry *ng2 = static_cast<Collada::NodeGeometry *>(p_node); - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(node); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(node); ERR_FAIL_COND_V(!mi, ERR_BUG); @@ -1099,7 +1100,7 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres String meshid; Transform3D apply_xform; Vector<int> bone_remap; - Vector<Ref<EditorSceneImporterMesh>> morphs; + Vector<Ref<ImporterMesh>> morphs; if (ng2->controller) { String ngsource = ng2->source; @@ -1168,10 +1169,10 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres for (int i = 0; i < names.size(); i++) { String meshid2 = names[i]; if (collada.state.mesh_data_map.has(meshid2)) { - Ref<EditorSceneImporterMesh> mesh = Ref<EditorSceneImporterMesh>(memnew(EditorSceneImporterMesh)); + Ref<ImporterMesh> mesh = Ref<ImporterMesh>(memnew(ImporterMesh)); const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid2]; mesh->set_name(meshdata.name); - Error err = _create_mesh_surfaces(false, mesh, ng2->material_map, meshdata, apply_xform, bone_remap, skin, nullptr, Vector<Ref<EditorSceneImporterMesh>>(), false); + Error err = _create_mesh_surfaces(false, mesh, ng2->material_map, meshdata, apply_xform, bone_remap, skin, nullptr, Vector<Ref<ImporterMesh>>(), false); ERR_FAIL_COND_V(err, err); morphs.push_back(mesh); @@ -1194,7 +1195,7 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres meshid = ng2->source; } - Ref<EditorSceneImporterMesh> mesh; + Ref<ImporterMesh> mesh; if (mesh_cache.has(meshid)) { mesh = mesh_cache[meshid]; } else { @@ -1202,7 +1203,7 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres //bleh, must ignore invalid ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(meshid), ERR_INVALID_DATA); - mesh = Ref<EditorSceneImporterMesh>(memnew(EditorSceneImporterMesh)); + mesh = Ref<ImporterMesh>(memnew(ImporterMesh)); const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid]; String name = meshdata.name; if (name == "") { diff --git a/editor/import/editor_importer_bake_reset.cpp b/editor/import/editor_importer_bake_reset.cpp index fb5de941ae..451a07351c 100644 --- a/editor/import/editor_importer_bake_reset.cpp +++ b/editor/import/editor_importer_bake_reset.cpp @@ -33,8 +33,8 @@ #include "core/error/error_list.h" #include "core/error/error_macros.h" #include "core/math/transform_3d.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "resource_importer_scene.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/node_3d.h" #include "scene/3d/skeleton_3d.h" @@ -71,7 +71,7 @@ void BakeReset::_bake_animation_pose(Node *scene, const String &p_bake_anim) { while (!queue.is_empty()) { List<Node *>::Element *E = queue.front(); Node *node = E->get(); - EditorSceneImporterMeshNode3D *editor_mesh_3d = scene->cast_to<EditorSceneImporterMeshNode3D>(node); + ImporterMeshInstance3D *editor_mesh_3d = scene->cast_to<ImporterMeshInstance3D>(node); MeshInstance3D *mesh_3d = scene->cast_to<MeshInstance3D>(node); if (scene->cast_to<Skeleton3D>(node)) { Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(node); diff --git a/editor/import/resource_importer_obj.cpp b/editor/import/resource_importer_obj.cpp index 34bc0a7d8d..4f75faedcb 100644 --- a/editor/import/resource_importer_obj.cpp +++ b/editor/import/resource_importer_obj.cpp @@ -32,10 +32,10 @@ #include "core/io/file_access.h" #include "core/io/resource_saver.h" -#include "editor/import/scene_importer_mesh.h" -#include "editor/import/scene_importer_mesh_node_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/node_3d.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/mesh.h" #include "scene/resources/surface_tool.h" @@ -439,13 +439,13 @@ Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, in Node3D *scene = memnew(Node3D); for (const Ref<Mesh> &m : meshes) { - Ref<EditorSceneImporterMesh> mesh; + Ref<ImporterMesh> mesh; mesh.instantiate(); for (int i = 0; i < m->get_surface_count(); i++) { mesh->add_surface(m->surface_get_primitive_type(i), m->surface_get_arrays(i), Array(), Dictionary(), m->surface_get_material(i)); } - EditorSceneImporterMeshNode3D *mi = memnew(EditorSceneImporterMeshNode3D); + ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D); mi->set_mesh(mesh); mi->set_name(m->get_name()); scene->add_child(mi); diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp index 2c9bc7dadf..1e93113488 100644 --- a/editor/import/resource_importer_scene.cpp +++ b/editor/import/resource_importer_scene.cpp @@ -34,9 +34,9 @@ #include "editor/editor_node.h" #include "editor/import/editor_importer_bake_reset.h" #include "editor/import/scene_import_settings.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "scene/3d/area_3d.h" #include "scene/3d/collision_shape_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/navigation_region_3d.h" #include "scene/3d/physics_body_3d.h" @@ -44,6 +44,7 @@ #include "scene/animation/animation_player.h" #include "scene/resources/animation.h" #include "scene/resources/box_shape_3d.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/packed_scene.h" #include "scene/resources/resource_format_text.h" #include "scene/resources/separation_ray_shape_3d.h" @@ -233,7 +234,7 @@ static String _fixstr(const String &p_what, const String &p_str) { return what; } -static void _pre_gen_shape_list(Ref<EditorSceneImporterMesh> &mesh, Vector<Ref<Shape3D>> &r_shape_list, bool p_convex) { +static void _pre_gen_shape_list(Ref<ImporterMesh> &mesh, Vector<Ref<Shape3D>> &r_shape_list, bool p_convex) { ERR_FAIL_NULL_MSG(mesh, "Cannot generate shape list with null mesh value"); if (!p_convex) { Ref<Shape3D> shape = mesh->create_trimesh_shape(); @@ -249,7 +250,7 @@ static void _pre_gen_shape_list(Ref<EditorSceneImporterMesh> &mesh, Vector<Ref<S } } -Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map) { +Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &collision_map) { // children first for (int i = 0; i < p_node->get_child_count(); i++) { Node *r = _pre_fix_node(p_node->get_child(i), p_root, collision_map); @@ -267,10 +268,10 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E return nullptr; } - if (Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + if (Object::cast_to<ImporterMeshInstance3D>(p_node)) { + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> m = mi->get_mesh(); + Ref<ImporterMesh> m = mi->get_mesh(); if (m.is_valid()) { for (int i = 0; i < m->get_surface_count(); i++) { @@ -331,9 +332,9 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E if (isroot) { return p_node; } - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); if (mi) { - Ref<EditorSceneImporterMesh> mesh = mi->get_mesh(); + Ref<ImporterMesh> mesh = mi->get_mesh(); if (mesh.is_valid()) { Vector<Ref<Shape3D>> shapes; @@ -398,13 +399,13 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E colshape->set_owner(sb->get_owner()); } - } else if (_teststr(name, "rigid") && Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { + } else if (_teststr(name, "rigid") && Object::cast_to<ImporterMeshInstance3D>(p_node)) { if (isroot) { return p_node; } - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); - Ref<EditorSceneImporterMesh> mesh = mi->get_mesh(); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); + Ref<ImporterMesh> mesh = mi->get_mesh(); if (mesh.is_valid()) { Vector<Ref<Shape3D>> shapes; @@ -426,10 +427,10 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E _add_shapes(rigid_body, shapes); } - } else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + } else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<ImporterMeshInstance3D>(p_node)) { + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> mesh = mi->get_mesh(); + Ref<ImporterMesh> mesh = mi->get_mesh(); if (mesh.is_valid()) { Vector<Ref<Shape3D>> shapes; @@ -465,14 +466,14 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E } } - } else if (_teststr(name, "navmesh") && Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { + } else if (_teststr(name, "navmesh") && Object::cast_to<ImporterMeshInstance3D>(p_node)) { if (isroot) { return p_node; } - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> mesh = mi->get_mesh(); + Ref<ImporterMesh> mesh = mi->get_mesh(); ERR_FAIL_COND_V(mesh.is_null(), nullptr); NavigationRegion3D *nmi = memnew(NavigationRegion3D); @@ -484,12 +485,12 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E memdelete(p_node); p_node = nmi; - } else if (Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { + } else if (Object::cast_to<ImporterMeshInstance3D>(p_node)) { //last attempt, maybe collision inside the mesh data - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> mesh = mi->get_mesh(); + Ref<ImporterMesh> mesh = mi->get_mesh(); if (!mesh.is_null()) { Vector<Ref<Shape3D>> shapes; if (collision_map.has(mesh)) { @@ -517,7 +518,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E return p_node; } -Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) { +Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<ImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) { // children first for (int i = 0; i < p_node->get_child_count(); i++) { Node *r = _post_fix_node(p_node->get_child(i), p_root, collision_map, r_scanned_meshes, p_node_data, p_material_data, p_animation_data, p_animation_fps); @@ -546,10 +547,10 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref< return nullptr; } - if (Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + if (Object::cast_to<ImporterMeshInstance3D>(p_node)) { + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> m = mi->get_mesh(); + Ref<ImporterMesh> m = mi->get_mesh(); if (m.is_valid()) { if (!r_scanned_meshes.has(m)) { @@ -669,10 +670,10 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref< } //navmesh (node may have changed type above) - if (Object::cast_to<EditorSceneImporterMeshNode3D>(p_node)) { - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + if (Object::cast_to<ImporterMeshInstance3D>(p_node)) { + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node); - Ref<EditorSceneImporterMesh> m = mi->get_mesh(); + Ref<ImporterMesh> m = mi->get_mesh(); if (m.is_valid()) { if (node_settings.has("generate/navmesh")) { @@ -1247,7 +1248,7 @@ Ref<Animation> ResourceImporterScene::import_animation_from_other_importer(Edito } void ResourceImporterScene::_generate_meshes(Node *p_node, const Dictionary &p_mesh_data, bool p_generate_lods, bool p_create_shadow_meshes, LightBakeMode p_light_bake_mode, float p_lightmap_texel_size, const Vector<uint8_t> &p_src_lightmap_cache, Vector<Vector<uint8_t>> &r_lightmap_caches) { - EditorSceneImporterMeshNode3D *src_mesh_node = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + ImporterMeshInstance3D *src_mesh_node = Object::cast_to<ImporterMeshInstance3D>(p_node); if (src_mesh_node) { //is mesh MeshInstance3D *mesh_node = memnew(MeshInstance3D); @@ -1452,7 +1453,7 @@ Node *ResourceImporterScene::pre_import(const String &p_source_file) { return nullptr; } - Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> collision_map; + Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> collision_map; _pre_fix_node(scene, scene, collision_map); @@ -1527,8 +1528,8 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p animation_data = subresources["animations"]; } - Set<Ref<EditorSceneImporterMesh>> scanned_meshes; - Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> collision_map; + Set<Ref<ImporterMesh>> scanned_meshes; + Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> collision_map; _pre_fix_node(scene, scene, collision_map); _post_fix_node(scene, scene, collision_map, scanned_meshes, node_data, material_data, animation_data, fps); diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h index e232b715be..2a67fa9aae 100644 --- a/editor/import/resource_importer_scene.h +++ b/editor/import/resource_importer_scene.h @@ -41,7 +41,7 @@ class Material; class AnimationPlayer; -class EditorSceneImporterMesh; +class ImporterMesh; class EditorSceneImporter : public RefCounted { GDCLASS(EditorSceneImporter, RefCounted); @@ -181,8 +181,8 @@ public: // Import scenes *after* everything else (such as textures). virtual int get_import_order() const override { return ResourceImporter::IMPORT_ORDER_SCENE; } - Node *_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map); - Node *_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps); + Node *_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &collision_map); + Node *_post_fix_node(Node *p_node, Node *p_root, Map<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<ImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps); Ref<Animation> _save_animation_to_file(Ref<Animation> anim, bool p_save_to_file, String p_save_to_path, bool p_keep_custom_tracks); void _create_clips(AnimationPlayer *anim, const Array &p_clips, bool p_bake_all); diff --git a/editor/import/scene_import_settings.cpp b/editor/import/scene_import_settings.cpp index 7ab5308a47..95a96f9e26 100644 --- a/editor/import/scene_import_settings.cpp +++ b/editor/import/scene_import_settings.cpp @@ -31,7 +31,8 @@ #include "scene_import_settings.h" #include "editor/editor_node.h" #include "editor/editor_scale.h" -#include "editor/import/scene_importer_mesh_node_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/surface_tool.h" class SceneImportSettingsData : public Object { @@ -240,7 +241,7 @@ void SceneImportSettings::_fill_scene(Node *p_node, TreeItem *p_parent_item) { p_node->set_meta("import_id", import_id); } - EditorSceneImporterMeshNode3D *src_mesh_node = Object::cast_to<EditorSceneImporterMeshNode3D>(p_node); + ImporterMeshInstance3D *src_mesh_node = Object::cast_to<ImporterMeshInstance3D>(p_node); if (src_mesh_node) { MeshInstance3D *mesh_node = memnew(MeshInstance3D); @@ -249,7 +250,7 @@ void SceneImportSettings::_fill_scene(Node *p_node, TreeItem *p_parent_item) { mesh_node->set_skin(src_mesh_node->get_skin()); mesh_node->set_skeleton_path(src_mesh_node->get_skeleton_path()); if (src_mesh_node->get_mesh().is_valid()) { - Ref<EditorSceneImporterMesh> editor_mesh = src_mesh_node->get_mesh(); + Ref<ImporterMesh> editor_mesh = src_mesh_node->get_mesh(); mesh_node->set_mesh(editor_mesh->get_mesh()); } diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp index 55e473b0ff..ea025dad3e 100644 --- a/editor/plugins/animation_player_editor_plugin.cpp +++ b/editor/plugins/animation_player_editor_plugin.cpp @@ -1466,15 +1466,15 @@ void AnimationPlayerEditor::_prepare_onion_layers_2() { } void AnimationPlayerEditor::_start_onion_skinning() { - // FIXME: Using "idle_frame" makes onion layers update one frame behind the current. - if (!get_tree()->is_connected("idle_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred))) { - get_tree()->connect("idle_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred)); + // FIXME: Using "process_frame" makes onion layers update one frame behind the current. + if (!get_tree()->is_connected("process_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred))) { + get_tree()->connect("process_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred)); } } void AnimationPlayerEditor::_stop_onion_skinning() { - if (get_tree()->is_connected("idle_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred))) { - get_tree()->disconnect("idle_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred)); + if (get_tree()->is_connected("process_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred))) { + get_tree()->disconnect("process_frame", callable_mp(this, &AnimationPlayerEditor::_prepare_onion_layers_1_deferred)); _free_onion_layers(); diff --git a/editor/plugins/node_3d_editor_gizmos.cpp b/editor/plugins/node_3d_editor_gizmos.cpp index 823a8e9d37..f1b25c0dde 100644 --- a/editor/plugins/node_3d_editor_gizmos.cpp +++ b/editor/plugins/node_3d_editor_gizmos.cpp @@ -1840,47 +1840,6 @@ void Camera3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { p_gizmo->add_lines(lines, material); p_gizmo->add_handles(handles, get_material("handles")); - - ClippedCamera3D *clipcam = Object::cast_to<ClippedCamera3D>(camera); - if (clipcam) { - Node3D *parent = Object::cast_to<Node3D>(camera->get_parent()); - if (!parent) { - return; - } - Vector3 cam_normal = -camera->get_global_transform().basis.get_axis(Vector3::AXIS_Z).normalized(); - Vector3 cam_x = camera->get_global_transform().basis.get_axis(Vector3::AXIS_X).normalized(); - Vector3 cam_y = camera->get_global_transform().basis.get_axis(Vector3::AXIS_Y).normalized(); - Vector3 cam_pos = camera->get_global_transform().origin; - Vector3 parent_pos = parent->get_global_transform().origin; - - Plane parent_plane(parent_pos, cam_normal); - Vector3 ray_from = parent_plane.project(cam_pos); - - lines.clear(); - lines.push_back(ray_from + cam_x * 0.5 + cam_y * 0.5); - lines.push_back(ray_from + cam_x * 0.5 + cam_y * -0.5); - - lines.push_back(ray_from + cam_x * 0.5 + cam_y * -0.5); - lines.push_back(ray_from + cam_x * -0.5 + cam_y * -0.5); - - lines.push_back(ray_from + cam_x * -0.5 + cam_y * -0.5); - lines.push_back(ray_from + cam_x * -0.5 + cam_y * 0.5); - - lines.push_back(ray_from + cam_x * -0.5 + cam_y * 0.5); - lines.push_back(ray_from + cam_x * 0.5 + cam_y * 0.5); - - if (parent_plane.distance_to(cam_pos) < 0) { - lines.push_back(ray_from); - lines.push_back(cam_pos); - } - - Transform3D local = camera->get_global_transform().affine_inverse(); - for (int i = 0; i < lines.size(); i++) { - lines.write[i] = local.xform(lines[i]); - } - - p_gizmo->add_lines(lines, material); - } } ////// diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp index 0751cba400..ea6ef8ab84 100644 --- a/editor/plugins/node_3d_editor_plugin.cpp +++ b/editor/plugins/node_3d_editor_plugin.cpp @@ -2708,15 +2708,28 @@ void Node3DEditorViewport::_notification(int p_what) { se->aabb = new_aabb; - t.translate(se->aabb.position); + Transform3D t_offset = t; // apply AABB scaling before item's global transform - Basis aabb_s; - aabb_s.scale(se->aabb.size); - t.basis = t.basis * aabb_s; + { + const Vector3 offset(0.005, 0.005, 0.005); + Basis aabb_s; + aabb_s.scale(se->aabb.size + offset); + t.translate(se->aabb.position - offset / 2); + t.basis = t.basis * aabb_s; + } + { + const Vector3 offset(0.01, 0.01, 0.01); + Basis aabb_s; + aabb_s.scale(se->aabb.size + offset); + t_offset.translate(se->aabb.position - offset / 2); + t_offset.basis = t_offset.basis * aabb_s; + } RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t); + RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset); RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t); + RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset); } if (changed || (spatial_editor->is_gizmo_visible() && !exist)) { @@ -4742,9 +4755,15 @@ Node3DEditorSelectedItem::~Node3DEditorSelectedItem() { if (sbox_instance.is_valid()) { RenderingServer::get_singleton()->free(sbox_instance); } + if (sbox_instance_offset.is_valid()) { + RenderingServer::get_singleton()->free(sbox_instance_offset); + } if (sbox_instance_xray.is_valid()) { RenderingServer::get_singleton()->free(sbox_instance_xray); } + if (sbox_instance_xray_offset.is_valid()) { + RenderingServer::get_singleton()->free(sbox_instance_xray_offset); + } } void Node3DEditor::select_gizmo_highlight_axis(int p_axis) { @@ -4847,23 +4866,39 @@ Object *Node3DEditor::_get_editor_data(Object *p_what) { si->sbox_instance = RenderingServer::get_singleton()->instance_create2( selection_box->get_rid(), sp->get_world_3d()->get_scenario()); + si->sbox_instance_offset = RenderingServer::get_singleton()->instance_create2( + selection_box->get_rid(), + sp->get_world_3d()->get_scenario()); RS::get_singleton()->instance_geometry_set_cast_shadows_setting( si->sbox_instance, RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_geometry_set_cast_shadows_setting( + si->sbox_instance_offset, + RS::SHADOW_CASTING_SETTING_OFF); // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER); + RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER); RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true); + RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true); si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2( selection_box_xray->get_rid(), sp->get_world_3d()->get_scenario()); + si->sbox_instance_xray_offset = RenderingServer::get_singleton()->instance_create2( + selection_box_xray->get_rid(), + sp->get_world_3d()->get_scenario()); RS::get_singleton()->instance_geometry_set_cast_shadows_setting( si->sbox_instance_xray, RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_geometry_set_cast_shadows_setting( + si->sbox_instance_xray_offset, + RS::SHADOW_CASTING_SETTING_OFF); // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER); - RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true); + RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER); + RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true); + RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true); return si; } @@ -4871,10 +4906,6 @@ Object *Node3DEditor::_get_editor_data(Object *p_what) { void Node3DEditor::_generate_selection_boxes() { // Use two AABBs to create the illusion of a slightly thicker line. AABB aabb(Vector3(), Vector3(1, 1, 1)); - AABB aabb_offset(Vector3(), Vector3(1, 1, 1)); - // Grow the bounding boxes slightly to avoid Z-fighting with the mesh's edges. - aabb.grow_by(0.005); - aabb_offset.grow_by(0.01); // Create a x-ray (visible through solid surfaces) and standard version of the selection box. // Both will be drawn at the same position, but with different opacity. @@ -4894,16 +4925,6 @@ void Node3DEditor::_generate_selection_boxes() { st_xray->add_vertex(b); } - for (int i = 0; i < 12; i++) { - Vector3 a, b; - aabb_offset.get_edge(i, a, b); - - st->add_vertex(a); - st->add_vertex(b); - st_xray->add_vertex(a); - st_xray->add_vertex(b); - } - Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D); mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color"); diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h index ee97c9fd3d..2d5aeaa981 100644 --- a/editor/plugins/node_3d_editor_plugin.h +++ b/editor/plugins/node_3d_editor_plugin.h @@ -431,7 +431,9 @@ public: bool last_xform_dirty; Node3D *sp; RID sbox_instance; + RID sbox_instance_offset; RID sbox_instance_xray; + RID sbox_instance_xray_offset; Ref<EditorNode3DGizmo> gizmo; Map<int, Transform3D> subgizmos; // map ID -> initial transform diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp index 2b1ca068ee..701d75fb08 100644 --- a/editor/plugins/script_text_editor.cpp +++ b/editor/plugins/script_text_editor.cpp @@ -433,10 +433,12 @@ void ScriptTextEditor::_validate_script() { int warning_nb = warnings.size(); warnings_panel->clear(); + bool has_connections_table = false; // Add missing connections. if (GLOBAL_GET("debug/gdscript/warnings/enable").booleanize()) { Node *base = get_tree()->get_edited_scene_root(); if (base && missing_connections.size() > 0) { + has_connections_table = true; warnings_panel->push_table(1); for (const Connection &connection : missing_connections) { String base_path = base->get_name(); @@ -458,6 +460,10 @@ void ScriptTextEditor::_validate_script() { code_editor->set_error_count(errors.size()); code_editor->set_warning_count(warning_nb); + if (has_connections_table) { + warnings_panel->add_newline(); + } + // Add script warnings. warnings_panel->push_table(3); for (const ScriptLanguage::Warning &w : warnings) { diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp index bc026146ef..3fbd315aec 100644 --- a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp +++ b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp @@ -131,6 +131,7 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_set(const StringName &p_na return false; } + // ID and size related properties. if (tiles.size() == 1) { const Vector2i &coords = tiles.front()->get().tile; const int &alternative = tiles.front()->get().alternative; @@ -160,36 +161,6 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_set(const StringName &p_na tile_set_atlas_source->move_tile_in_atlas(coords, TileSetSource::INVALID_ATLAS_COORDS, as_vector2i); emit_signal(SNAME("changed"), "size_in_atlas"); return true; - } else if (p_name == "animation_columns") { - bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(coords, tile_set_atlas_source->get_tile_size_in_atlas(coords), p_value, tile_set_atlas_source->get_tile_animation_separation(coords), tile_set_atlas_source->get_tile_animation_frames_count(coords), coords); - ERR_FAIL_COND_V(!has_room_for_tile, false); - tile_set_atlas_source->set_tile_animation_columns(coords, p_value); - emit_signal(SNAME("changed"), "animation_columns"); - return true; - } else if (p_name == "animation_separation") { - bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(coords, tile_set_atlas_source->get_tile_size_in_atlas(coords), tile_set_atlas_source->get_tile_animation_columns(coords), p_value, tile_set_atlas_source->get_tile_animation_frames_count(coords), coords); - ERR_FAIL_COND_V(!has_room_for_tile, false); - tile_set_atlas_source->set_tile_animation_separation(coords, p_value); - emit_signal(SNAME("changed"), "animation_separation"); - return true; - } else if (p_name == "animation_speed") { - tile_set_atlas_source->set_tile_animation_speed(coords, p_value); - emit_signal(SNAME("changed"), "animation_speed"); - return true; - } else if (p_name == "animation_frames_count") { - bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(coords, tile_set_atlas_source->get_tile_size_in_atlas(coords), tile_set_atlas_source->get_tile_animation_columns(coords), tile_set_atlas_source->get_tile_animation_separation(coords), p_value, coords); - ERR_FAIL_COND_V(!has_room_for_tile, false); - tile_set_atlas_source->set_tile_animation_frames_count(coords, p_value); - notify_property_list_changed(); - emit_signal(SNAME("changed"), "animation_separation"); - return true; - } else if (components.size() == 2 && components[0].begins_with("animation_frame_") && components[0].trim_prefix("animation_frame_").is_valid_int()) { - int frame = components[0].trim_prefix("animation_frame_").to_int(); - ERR_FAIL_INDEX_V(frame, tile_set_atlas_source->get_tile_animation_frames_count(coords), false); - if (components[1] == "duration") { - tile_set_atlas_source->set_tile_animation_frame_duration(coords, frame, p_value); - return true; - } } } else if (alternative > 0) { if (p_name == "alternative_id") { @@ -213,6 +184,74 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_set(const StringName &p_na } } + // Animation. + // Check if all tiles have an alternative_id of 0. + bool all_alternatve_id_zero = true; + for (TileSelection tile : tiles) { + if (tile.alternative != 0) { + all_alternatve_id_zero = false; + break; + } + } + + if (all_alternatve_id_zero) { + Vector<String> components = String(p_name).split("/", true, 2); + if (p_name == "animation_columns") { + for (TileSelection tile : tiles) { + bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(tile.tile, tile_set_atlas_source->get_tile_size_in_atlas(tile.tile), p_value, tile_set_atlas_source->get_tile_animation_separation(tile.tile), tile_set_atlas_source->get_tile_animation_frames_count(tile.tile), tile.tile); + if (!has_room_for_tile) { + ERR_PRINT("No room for tile"); + } else { + tile_set_atlas_source->set_tile_animation_columns(tile.tile, p_value); + } + } + emit_signal(SNAME("changed"), "animation_columns"); + return true; + } else if (p_name == "animation_separation") { + for (TileSelection tile : tiles) { + bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(tile.tile, tile_set_atlas_source->get_tile_size_in_atlas(tile.tile), tile_set_atlas_source->get_tile_animation_columns(tile.tile), p_value, tile_set_atlas_source->get_tile_animation_frames_count(tile.tile), tile.tile); + if (!has_room_for_tile) { + ERR_PRINT("No room for tile"); + } else { + tile_set_atlas_source->set_tile_animation_separation(tile.tile, p_value); + } + } + emit_signal(SNAME("changed"), "animation_separation"); + return true; + } else if (p_name == "animation_speed") { + for (TileSelection tile : tiles) { + tile_set_atlas_source->set_tile_animation_speed(tile.tile, p_value); + } + emit_signal(SNAME("changed"), "animation_speed"); + return true; + } else if (p_name == "animation_frames_count") { + for (TileSelection tile : tiles) { + bool has_room_for_tile = tile_set_atlas_source->has_room_for_tile(tile.tile, tile_set_atlas_source->get_tile_size_in_atlas(tile.tile), tile_set_atlas_source->get_tile_animation_columns(tile.tile), tile_set_atlas_source->get_tile_animation_separation(tile.tile), p_value, tile.tile); + if (!has_room_for_tile) { + ERR_PRINT("No room for tile"); + } else { + tile_set_atlas_source->set_tile_animation_frames_count(tile.tile, p_value); + } + } + notify_property_list_changed(); + emit_signal(SNAME("changed"), "animation_separation"); + return true; + } else if (components.size() == 2 && components[0].begins_with("animation_frame_") && components[0].trim_prefix("animation_frame_").is_valid_int()) { + for (TileSelection tile : tiles) { + int frame = components[0].trim_prefix("animation_frame_").to_int(); + if (frame < 0 || frame >= tile_set_atlas_source->get_tile_animation_frames_count(tile.tile)) { + ERR_PRINT(vformat("No tile animation frame with index %d", frame)); + } else { + if (components[1] == "duration") { + tile_set_atlas_source->set_tile_animation_frame_duration(tile.tile, frame, p_value); + return true; + } + } + } + } + } + + // Other properties. bool any_valid = false; for (Set<TileSelection>::Element *E = tiles.front(); E; E = E->next()) { const Vector2i &coords = E->get().tile; @@ -238,6 +277,7 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_get(const StringName &p_na return false; } + // ID and size related properties.s if (tiles.size() == 1) { const Vector2i &coords = tiles.front()->get().tile; const int &alternative = tiles.front()->get().alternative; @@ -250,27 +290,6 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_get(const StringName &p_na } else if (p_name == "size_in_atlas") { r_ret = tile_set_atlas_source->get_tile_size_in_atlas(coords); return true; - } else if (p_name == "animation_columns") { - r_ret = tile_set_atlas_source->get_tile_animation_columns(coords); - return true; - } else if (p_name == "animation_separation") { - r_ret = tile_set_atlas_source->get_tile_animation_separation(coords); - return true; - } else if (p_name == "animation_speed") { - r_ret = tile_set_atlas_source->get_tile_animation_speed(coords); - return true; - } else if (p_name == "animation_frames_count") { - r_ret = tile_set_atlas_source->get_tile_animation_frames_count(coords); - return true; - } else if (components.size() == 2 && components[0].begins_with("animation_frame_") && components[0].trim_prefix("animation_frame_").is_valid_int()) { - int frame = components[0].trim_prefix("animation_frame_").to_int(); - if (components[1] == "duration") { - if (frame < 0 || frame >= tile_set_atlas_source->get_tile_animation_frames_count(coords)) { - return false; - } - r_ret = tile_set_atlas_source->get_tile_animation_frame_duration(coords, frame); - return true; - } } } else if (alternative > 0) { if (p_name == "alternative_id") { @@ -280,6 +299,44 @@ bool TileSetAtlasSourceEditor::AtlasTileProxyObject::_get(const StringName &p_na } } + // Animation. + // Check if all tiles have an alternative_id of 0. + bool all_alternatve_id_zero = true; + for (TileSelection tile : tiles) { + if (tile.alternative != 0) { + all_alternatve_id_zero = false; + break; + } + } + + if (all_alternatve_id_zero) { + const Vector2i &coords = tiles.front()->get().tile; + + Vector<String> components = String(p_name).split("/", true, 2); + if (p_name == "animation_columns") { + r_ret = tile_set_atlas_source->get_tile_animation_columns(coords); + return true; + } else if (p_name == "animation_separation") { + r_ret = tile_set_atlas_source->get_tile_animation_separation(coords); + return true; + } else if (p_name == "animation_speed") { + r_ret = tile_set_atlas_source->get_tile_animation_speed(coords); + return true; + } else if (p_name == "animation_frames_count") { + r_ret = tile_set_atlas_source->get_tile_animation_frames_count(coords); + return true; + } else if (components.size() == 2 && components[0].begins_with("animation_frame_") && components[0].trim_prefix("animation_frame_").is_valid_int()) { + int frame = components[0].trim_prefix("animation_frame_").to_int(); + if (components[1] == "duration") { + if (frame < 0 || frame >= tile_set_atlas_source->get_tile_animation_frames_count(coords)) { + return false; + } + r_ret = tile_set_atlas_source->get_tile_animation_frame_duration(coords, frame); + return true; + } + } + } + for (Set<TileSelection>::Element *E = tiles.front(); E; E = E->next()) { // Return the first tile with a property matching the name. // Note: It's a little bit annoying, but the behavior is the same the one in MultiNodeEdit. @@ -304,29 +361,42 @@ void TileSetAtlasSourceEditor::AtlasTileProxyObject::_get_property_list(List<Pro return; } + // ID and size related properties. if (tiles.size() == 1) { if (tiles.front()->get().alternative == 0) { p_list->push_back(PropertyInfo(Variant::VECTOR2I, "atlas_coords", PROPERTY_HINT_NONE, "")); p_list->push_back(PropertyInfo(Variant::VECTOR2I, "size_in_atlas", PROPERTY_HINT_NONE, "")); - - // Animation. - p_list->push_back(PropertyInfo(Variant::NIL, "Animation", PROPERTY_HINT_NONE, "animation_", PROPERTY_USAGE_GROUP)); - p_list->push_back(PropertyInfo(Variant::INT, "animation_columns", PROPERTY_HINT_NONE, "")); - p_list->push_back(PropertyInfo(Variant::VECTOR2I, "animation_separation", PROPERTY_HINT_NONE, "")); - p_list->push_back(PropertyInfo(Variant::FLOAT, "animation_speed", PROPERTY_HINT_NONE, "")); - p_list->push_back(PropertyInfo(Variant::INT, "animation_frames_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Frames,animation_frame_")); - if (tile_set_atlas_source->get_tile_animation_frames_count(tiles.front()->get().tile) == 1) { - p_list->push_back(PropertyInfo(Variant::FLOAT, "animation_frame_0/duration", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY)); - } else { - for (int i = 0; i < tile_set_atlas_source->get_tile_animation_frames_count(tiles.front()->get().tile); i++) { - p_list->push_back(PropertyInfo(Variant::FLOAT, vformat("animation_frame_%d/duration", i), PROPERTY_HINT_NONE, "")); - } - } } else { p_list->push_back(PropertyInfo(Variant::INT, "alternative_id", PROPERTY_HINT_NONE, "")); } } + // Animation. + // Check if all tiles have an alternative_id of 0. + bool all_alternatve_id_zero = true; + for (TileSelection tile : tiles) { + if (tile.alternative != 0) { + all_alternatve_id_zero = false; + break; + } + } + + if (all_alternatve_id_zero) { + p_list->push_back(PropertyInfo(Variant::NIL, "Animation", PROPERTY_HINT_NONE, "animation_", PROPERTY_USAGE_GROUP)); + p_list->push_back(PropertyInfo(Variant::INT, "animation_columns", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::VECTOR2I, "animation_separation", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::FLOAT, "animation_speed", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::INT, "animation_frames_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Frames,animation_frame_")); + // Not optimal, but returns value for the first tile. This is similar to what MultiNodeEdit does. + if (tile_set_atlas_source->get_tile_animation_frames_count(tiles.front()->get().tile) == 1) { + p_list->push_back(PropertyInfo(Variant::FLOAT, "animation_frame_0/duration", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY)); + } else { + for (int i = 0; i < tile_set_atlas_source->get_tile_animation_frames_count(tiles.front()->get().tile); i++) { + p_list->push_back(PropertyInfo(Variant::FLOAT, vformat("animation_frame_%d/duration", i), PROPERTY_HINT_NONE, "")); + } + } + } + // Get the list of properties common to all tiles (similar to what's done in MultiNodeEdit). struct PropertyId { int occurence_id = 0; diff --git a/editor/plugins/tiles/tiles_editor_plugin.cpp b/editor/plugins/tiles/tiles_editor_plugin.cpp index f51f4625a9..d0d01a8d49 100644 --- a/editor/plugins/tiles/tiles_editor_plugin.cpp +++ b/editor/plugins/tiles/tiles_editor_plugin.cpp @@ -246,11 +246,9 @@ void TilesEditorPlugin::make_visible(bool p_visible) { if (p_visible) { tiles_editor_button->show(); editor_node->make_bottom_panel_item_visible(tiles_editor); - //get_tree()->connect_compat("idle_frame", tileset_editor, "_on_workspace_process"); } else { editor_node->hide_bottom_panel(); tiles_editor_button->hide(); - //get_tree()->disconnect_compat("idle_frame", tileset_editor, "_on_workspace_process"); } } diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index 81554c9550..e8fd3070c2 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -2123,8 +2123,8 @@ void ProjectManager::_run_project_confirm() { const String &selected = selected_list[i].project_key; String path = EditorSettings::get_singleton()->get("projects/" + selected); - // `.substr(6)` on `IMPORTED_FILES_PATH` strips away the leading "res://". - if (!DirAccess::exists(path.plus_file(ProjectSettings::IMPORTED_FILES_PATH.substr(6)))) { + // `.substr(6)` on `ProjectSettings::get_singleton()->get_imported_files_path()` strips away the leading "res://". + if (!DirAccess::exists(path.plus_file(ProjectSettings::get_singleton()->get_imported_files_path().substr(6)))) { run_error_diag->set_text(TTR("Can't run project: Assets need to be imported.\nPlease edit the project to trigger the initial import.")); run_error_diag->popup_centered(); continue; diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index ae6a161c8c..4a59eb4fb3 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -411,10 +411,6 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { } } break; case TOOL_EXPAND_COLLAPSE: { - if (!scene_tree->get_selected()) { - break; - } - Tree *tree = scene_tree->get_scene_tree(); TreeItem *selected_item = tree->get_selected(); @@ -979,6 +975,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { } EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT); } break; + case TOOL_AUTO_EXPAND: { + scene_tree->set_auto_expand_selected(!EditorSettings::get_singleton()->get("docks/scene_tree/auto_expand_to_selected"), true); + } break; case TOOL_SCENE_EDITABLE_CHILDREN: { if (!profile_allow_editing) { break; @@ -1223,6 +1222,7 @@ void SceneTreeDock::_notification(int p_what) { button_instance->set_icon(get_theme_icon(SNAME("Instance"), SNAME("EditorIcons"))); button_create_script->set_icon(get_theme_icon(SNAME("ScriptCreate"), SNAME("EditorIcons"))); button_detach_script->set_icon(get_theme_icon(SNAME("ScriptRemove"), SNAME("EditorIcons"))); + button_tree_menu->set_icon(get_theme_icon(SNAME("GuiTabMenuHl"), SNAME("EditorIcons"))); filter->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons"))); filter->set_clear_button_enabled(true); @@ -1291,12 +1291,14 @@ void SceneTreeDock::_notification(int p_what) { case NOTIFICATION_ENTER_TREE: { clear_inherit_confirm->connect("confirmed", callable_mp(this, &SceneTreeDock::_tool_selected), make_binds(TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM, false)); + scene_tree->set_auto_expand_selected(EditorSettings::get_singleton()->get("docks/scene_tree/auto_expand_to_selected"), false); } break; case NOTIFICATION_EXIT_TREE: { clear_inherit_confirm->disconnect("confirmed", callable_mp(this, &SceneTreeDock::_tool_selected)); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + scene_tree->set_auto_expand_selected(EditorSettings::get_singleton()->get("docks/scene_tree/auto_expand_to_selected"), false); button_add->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); button_instance->set_icon(get_theme_icon(SNAME("Instance"), SNAME("EditorIcons"))); button_create_script->set_icon(get_theme_icon(SNAME("ScriptCreate"), SNAME("EditorIcons"))); @@ -2694,7 +2696,6 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { menu->add_icon_shortcut(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_theme_icon(SNAME("Instance"), SNAME("EditorIcons")), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANTIATE); } - menu->add_icon_shortcut(get_theme_icon(SNAME("Collapse"), SNAME("EditorIcons")), ED_GET_SHORTCUT("scene_tree/expand_collapse_all"), TOOL_EXPAND_COLLAPSE); menu->add_separator(); existing_script = selected->get_script(); @@ -2832,6 +2833,18 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { menu->popup(); } +void SceneTreeDock::_open_tree_menu() { + menu->clear(); + + menu->add_icon_shortcut(get_theme_icon(SNAME("Collapse"), SNAME("EditorIcons")), ED_GET_SHORTCUT("scene_tree/expand_collapse_all"), TOOL_EXPAND_COLLAPSE); + menu->add_check_item(TTR("Auto Expand to Selected"), TOOL_AUTO_EXPAND); + menu->set_item_checked(menu->get_item_idx_from_text(TTR("Auto Expand to Selected")), EditorSettings::get_singleton()->get("docks/scene_tree/auto_expand_to_selected")); + + menu->set_size(Size2(1, 1)); + menu->set_position(get_screen_position() + get_local_mouse_position()); + menu->popup(); +} + void SceneTreeDock::_filter_changed(const String &p_filter) { scene_tree->set_filter(p_filter); } @@ -3271,6 +3284,11 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel filter_hbc->add_child(button_detach_script); button_detach_script->hide(); + button_tree_menu = memnew(Button); + button_tree_menu->set_flat(true); + button_tree_menu->connect("pressed", callable_mp(this, &SceneTreeDock::_open_tree_menu)); + filter_hbc->add_child(button_tree_menu); + button_hb = memnew(HBoxContainer); vbc->add_child(button_hb); diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h index ece0ca5ca4..255e026887 100644 --- a/editor/scene_tree_dock.h +++ b/editor/scene_tree_dock.h @@ -81,6 +81,7 @@ class SceneTreeDock : public VBoxContainer { TOOL_COPY_NODE_PATH, TOOL_BUTTON_MAX, TOOL_OPEN_DOCUMENTATION, + TOOL_AUTO_EXPAND, TOOL_SCENE_EDITABLE_CHILDREN, TOOL_SCENE_USE_PLACEHOLDER, TOOL_SCENE_MAKE_LOCAL, @@ -115,6 +116,7 @@ class SceneTreeDock : public VBoxContainer { Button *button_instance; Button *button_create_script; Button *button_detach_script; + Button *button_tree_menu; Button *button_2d; Button *button_3d; @@ -237,6 +239,7 @@ class SceneTreeDock : public VBoxContainer { void _quick_open(); void _tree_rmb(const Vector2 &p_menu_pos); + void _open_tree_menu(); void _filter_changed(const String &p_filter); diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp index f476da1a98..c944068455 100644 --- a/editor/scene_tree_editor.cpp +++ b/editor/scene_tree_editor.cpp @@ -737,17 +737,18 @@ void SceneTreeEditor::set_selected(Node *p_node, bool p_emit_selected) { TreeItem *item = p_node ? _find(tree->get_root(), p_node->get_path()) : nullptr; if (item) { - // make visible when it's collapsed - TreeItem *node = item->get_parent(); - while (node && node != tree->get_root()) { - node->set_collapsed(false); - node = node->get_parent(); + if (auto_expand_selected) { + // Make visible when it's collapsed. + TreeItem *node = item->get_parent(); + while (node && node != tree->get_root()) { + node->set_collapsed(false); + node = node->get_parent(); + } + item->select(0); + item->set_as_cursor(0); + selected = p_node; + tree->ensure_cursor_is_visible(); } - item->select(0); - item->set_as_cursor(0); - selected = p_node; - tree->ensure_cursor_is_visible(); - } else { if (!p_node) { selected = nullptr; @@ -1127,11 +1128,19 @@ void SceneTreeEditor::_rmb_select(const Vector2 &p_pos) { void SceneTreeEditor::update_warning() { _warning_changed(nullptr); } + void SceneTreeEditor::_warning_changed(Node *p_for_node) { //should use a timer update_timer->start(); } +void SceneTreeEditor::set_auto_expand_selected(bool p_auto, bool p_update_settings) { + if (p_update_settings) { + EditorSettings::get_singleton()->set("docks/scene_tree/auto_expand_to_selected", p_auto); + } + auto_expand_selected = p_auto; +} + void SceneTreeEditor::set_connect_to_script_mode(bool p_enable) { connect_to_script_mode = p_enable; update_tree(); diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h index acd49e8d92..4acd5d8486 100644 --- a/editor/scene_tree_editor.h +++ b/editor/scene_tree_editor.h @@ -64,6 +64,7 @@ class SceneTreeEditor : public Control { AcceptDialog *error; AcceptDialog *warning; + bool auto_expand_selected = true; bool connect_to_script_mode; bool connecting_signal; @@ -152,6 +153,7 @@ public: void update_tree() { _update_tree(); } + void set_auto_expand_selected(bool p_auto, bool p_update_settings); void set_connect_to_script_mode(bool p_enable); void set_connecting_signal(bool p_enable); diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index 171895ed24..bd8342e1aa 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -91,11 +91,13 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, // the data width in case of 8/4/1 bit images const uint32_t w = bits_per_pixel >= 24 ? width : width_bytes; const uint8_t *line = p_buffer + (line_width * (height - 1)); + const uint8_t *end_buffer = p_buffer + p_header.bmp_file_header.bmp_file_size - p_header.bmp_file_header.bmp_file_offset; for (uint64_t i = 0; i < height; i++) { const uint8_t *line_ptr = line; for (unsigned int j = 0; j < w; j++) { + ERR_FAIL_COND_V(line_ptr >= end_buffer, ERR_FILE_CORRUPT); switch (bits_per_pixel) { case 1: { uint8_t color_index = *line_ptr; diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp index 94b7e0ce38..371800d8f3 100644 --- a/modules/bullet/soft_body_bullet.cpp +++ b/modules/bullet/soft_body_bullet.cpp @@ -190,22 +190,24 @@ void SoftBodyBullet::get_node_position(int p_node_index, Vector3 &r_position) co } } -void SoftBodyBullet::set_node_mass(int node_index, btScalar p_mass) { +void SoftBodyBullet::set_node_mass(int p_node_index, btScalar p_mass) { if (0 >= p_mass) { - pin_node(node_index); + pin_node(p_node_index); } else { - unpin_node(node_index); + unpin_node(p_node_index); } if (bt_soft_body) { - bt_soft_body->setMass(node_index, p_mass); + ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); + bt_soft_body->setMass(p_node_index, p_mass); } } -btScalar SoftBodyBullet::get_node_mass(int node_index) const { +btScalar SoftBodyBullet::get_node_mass(int p_node_index) const { if (bt_soft_body) { - return bt_soft_body->getMass(node_index); + ERR_FAIL_INDEX_V(p_node_index, bt_soft_body->m_nodes.size(), 1); + return bt_soft_body->getMass(p_node_index); } else { - return -1 == search_node_pinned(node_index) ? 1 : 0; + return -1 == search_node_pinned(p_node_index) ? 1 : 0; } } @@ -418,17 +420,25 @@ void SoftBodyBullet::setup_soft_body() { // Set pinned nodes for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { - bt_soft_body->setMass(pinned_nodes[i], 0); + const int node_index = pinned_nodes[i]; + ERR_CONTINUE(0 > node_index || bt_soft_body->m_nodes.size() <= node_index); + bt_soft_body->setMass(node_index, 0); } } void SoftBodyBullet::pin_node(int p_node_index) { + if (bt_soft_body) { + ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); + } if (-1 == search_node_pinned(p_node_index)) { pinned_nodes.push_back(p_node_index); } } void SoftBodyBullet::unpin_node(int p_node_index) { + if (bt_soft_body) { + ERR_FAIL_INDEX(p_node_index, bt_soft_body->m_nodes.size()); + } const int id = search_node_pinned(p_node_index); if (-1 != id) { pinned_nodes.remove(id); diff --git a/modules/enet/doc_classes/ENetConnection.xml b/modules/enet/doc_classes/ENetConnection.xml index 00469ab44c..fcdf282a7d 100644 --- a/modules/enet/doc_classes/ENetConnection.xml +++ b/modules/enet/doc_classes/ENetConnection.xml @@ -51,7 +51,7 @@ <argument index="3" name="data" type="int" default="0" /> <description> Initiates a connection to a foreign [code]address[/code] using the specified [code]port[/code] and allocting the requested [code]channels[/code]. Optional [code]data[/code] can be passed during connection in the form of a 32 bit integer. - Note: You must call either [method create_host] or [method create_host_bound] before calling this method. + [b]Note:[/b] You must call either [method create_host] or [method create_host_bound] before calling this method. </description> </method> <method name="create_host"> @@ -121,7 +121,7 @@ <return type="Array" /> <description> Returns the list of peers associated with this host. - Note: This list might include some peers that are not fully connected or are still being disconnected. + [b]Note:[/b] This list might include some peers that are not fully connected or are still being disconnected. </description> </method> <method name="pop_statistic"> @@ -136,7 +136,7 @@ <argument index="0" name="refuse" type="bool" /> <description> Configures the DTLS server to automatically drop new connections. - Note: This method is only relevant after calling [method dtls_server_setup]. + [b]Note:[/b] This method is only relevant after calling [method dtls_server_setup]. </description> </method> <method name="service"> diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml index f9659c092a..22136c3944 100644 --- a/modules/enet/doc_classes/ENetMultiplayerPeer.xml +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -18,7 +18,7 @@ <argument index="1" name="host" type="ENetConnection" /> <description> Add a new remote peer with the given [code]peer_id[/code] connected to the given [code]host[/code]. - Note: The [code]host[/code] must have exactly one peer in the [constant ENetPacketPeer.STATE_CONNECTED] state. + [b]Note:[/b] The [code]host[/code] must have exactly one peer in the [constant ENetPacketPeer.STATE_CONNECTED] state. </description> </method> <method name="close_connection"> diff --git a/modules/fbx/data/fbx_mesh_data.cpp b/modules/fbx/data/fbx_mesh_data.cpp index dcea476275..7343bf87af 100644 --- a/modules/fbx/data/fbx_mesh_data.cpp +++ b/modules/fbx/data/fbx_mesh_data.cpp @@ -31,6 +31,7 @@ #include "fbx_mesh_data.h" #include "core/templates/local_vector.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/mesh.h" #include "scene/resources/surface_tool.h" @@ -101,7 +102,7 @@ HashMap<int, Vector2> collect_uv(const Vector<VertexData<Vector2>> *p_data, Hash return collection; } -EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression) { +ImporterMeshInstance3D *FBXMeshData::create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression) { mesh_geometry = p_mesh_geometry; // todo: make this just use a uint64_t FBX ID this is a copy of our original materials unfortunately. const std::vector<const FBXDocParser::Material *> &material_lookup = model->GetMaterials(); @@ -344,7 +345,7 @@ EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &s } // Phase 6. Compose the mesh and return it. - Ref<EditorSceneImporterMesh> mesh; + Ref<ImporterMesh> mesh; mesh.instantiate(); // Add blend shape info. @@ -380,7 +381,7 @@ EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &s in_mesh_surface_id += 1; } - EditorSceneImporterMeshNode3D *godot_mesh = memnew(EditorSceneImporterMeshNode3D); + ImporterMeshInstance3D *godot_mesh = memnew(ImporterMeshInstance3D); godot_mesh->set_mesh(mesh); const String name = ImportUtils::FBXNodeToName(model->Name()); godot_mesh->set_name(name); // hurry up compiling >.< diff --git a/modules/fbx/data/fbx_mesh_data.h b/modules/fbx/data/fbx_mesh_data.h index 24db4a5469..eec7f38cd6 100644 --- a/modules/fbx/data/fbx_mesh_data.h +++ b/modules/fbx/data/fbx_mesh_data.h @@ -35,7 +35,7 @@ #include "core/templates/local_vector.h" #include "core/templates/ordered_hash_map.h" #include "editor/import/resource_importer_scene.h" -#include "editor/import/scene_importer_mesh_node_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/resources/surface_tool.h" @@ -98,7 +98,7 @@ struct FBXMeshData : RefCounted { // translate fbx mesh data from document context to FBX Mesh Geometry Context bool valid_weight_indexes = false; - EditorSceneImporterMeshNode3D *create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression); + ImporterMeshInstance3D *create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression); void gen_weight_info(Ref<SurfaceTool> st, int vertex_id) const; @@ -107,7 +107,7 @@ struct FBXMeshData : RefCounted { int max_weight_count = 0; uint64_t armature_id = 0; bool valid_armature_id = false; - EditorSceneImporterMeshNode3D *godot_mesh_instance = nullptr; + ImporterMeshInstance3D *godot_mesh_instance = nullptr; private: void sanitize_vertex_weights(const ImportState &state); diff --git a/modules/fbx/editor_scene_importer_fbx.cpp b/modules/fbx/editor_scene_importer_fbx.cpp index e0663ab49d..e4de204cf1 100644 --- a/modules/fbx/editor_scene_importer_fbx.cpp +++ b/modules/fbx/editor_scene_importer_fbx.cpp @@ -40,9 +40,9 @@ #include "editor/editor_log.h" #include "editor/editor_node.h" #include "editor/import/resource_importer_scene.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "scene/3d/bone_attachment_3d.h" #include "scene/3d/camera_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/light_3d.h" #include "scene/main/node.h" #include "scene/resources/material.h" @@ -627,7 +627,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( node_element; node_element = node_element->next()) { Ref<FBXNode> fbx_node = node_element->get(); - EditorSceneImporterMeshNode3D *mesh_node = nullptr; + ImporterMeshInstance3D *mesh_node = nullptr; Ref<FBXMeshData> mesh_data_precached; // check for valid geometry @@ -768,7 +768,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( for (KeyValue<uint64_t, Ref<FBXMeshData>> &mesh_data : state.renderer_mesh_data) { Ref<FBXMeshData> mesh = mesh_data.value; const uint64_t mesh_id = mesh_data.key; - EditorSceneImporterMeshNode3D *mesh_instance = mesh->godot_mesh_instance; + ImporterMeshInstance3D *mesh_instance = mesh->godot_mesh_instance; const int mesh_weights = mesh->max_weight_count; Ref<FBXSkeleton> skeleton; const bool valid_armature = mesh->valid_armature_id; diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml index 3654870b09..6b3bd714b9 100644 --- a/modules/gdnative/doc_classes/GDNativeLibrary.xml +++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml @@ -7,8 +7,8 @@ A GDNative library can implement [NativeScript]s, global functions to call with the [GDNative] class, or low-level engine extensions through interfaces such as XRInterfaceGDNative. The library must be compiled for each platform and architecture that the project will run on. </description> <tutorials> - <link title="GDNative C example">https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-c-example.html</link> - <link title="GDNative C++ example">https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-cpp-example.html</link> + <link title="GDNative C example">https://docs.godotengine.org/en/latest/tutorials/scripting/gdnative/gdnative_c_example.html</link> + <link title="GDNative C++ example">https://docs.godotengine.org/en/latest/tutorials/scripting/gdnative/gdnative_cpp_example.html</link> </tutorials> <methods> <method name="get_current_dependencies" qualifiers="const"> diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml index 9d34e89f02..221374a7a4 100644 --- a/modules/gdnative/doc_classes/NativeScript.xml +++ b/modules/gdnative/doc_classes/NativeScript.xml @@ -38,7 +38,7 @@ <return type="Variant" /> <description> Constructs a new object of the base type with a script of this type already attached. - [i]Note[/i]: Any arguments passed to this function will be ignored and not passed to the native constructor function. This will change with in a future API extension. + [b]Note:[/b] Any arguments passed to this function will be ignored and not passed to the native constructor function. This will change with in a future API extension. </description> </method> </methods> diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index d45202bd40..0a448ed88c 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -8,7 +8,7 @@ [method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. </description> <tutorials> - <link title="GDScript tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/index.html</link> + <link title="GDScript documentation index">https://docs.godotengine.org/en/latest/tutorials/scripting/gdscript/index.html</link> </tutorials> <methods> <method name="get_as_byte_code" qualifiers="const"> diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index c35af9ca5b..3abd8672fa 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -244,6 +244,7 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, class_type.kind = GDScriptParser::DataType::CLASS; class_type.class_type = p_class; class_type.script_path = parser->script_path; + class_type.builtin_type = Variant::OBJECT; p_class->set_datatype(class_type); if (!p_class->extends_used) { @@ -1035,7 +1036,10 @@ void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode * return_type.is_meta_type = false; p_function->set_datatype(return_type); if (p_function->return_type) { - push_error("Constructor cannot have an explicit return type.", p_function->return_type); + GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type); + if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) { + push_error("Constructor cannot have an explicit return type.", p_function->return_type); + } } } else { GDScriptParser::DataType return_type = resolve_datatype(p_function->return_type); @@ -1198,7 +1202,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { variable_type.kind = GDScriptParser::DataType::BUILTIN; variable_type.builtin_type = Variant::INT; // Can this ever be a float or something else? p_for->variable->set_datatype(variable_type); - } else { + } else if (p_for->list) { resolve_node(p_for->list); if (p_for->list->datatype.has_container_element_type()) { variable_type = p_for->list->datatype.get_container_element_type(); @@ -1213,7 +1217,9 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { variable_type.kind = GDScriptParser::DataType::VARIANT; } } - p_for->variable->set_datatype(variable_type); + if (p_for->variable) { + p_for->variable->set_datatype(variable_type); + } resolve_suite(p_for->loop); p_for->set_datatype(p_for->loop->get_datatype()); @@ -1737,7 +1743,7 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig push_error("Cannot assign a new value to a constant.", p_assignment->assignee); } - if (!assignee_type.is_variant() && !assigned_value_type.is_variant()) { + if (!assignee_type.is_variant() && assigned_value_type.is_hard_type()) { bool compatible = true; GDScriptParser::DataType op_type = assigned_value_type; if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) { @@ -1789,27 +1795,24 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: { GDScriptParser::DataType id_type = identifier->parameter_source->get_datatype(); if (!id_type.is_hard_type()) { - id_type = assigned_value_type; - id_type.type_source = GDScriptParser::DataType::INFERRED; - id_type.is_constant = false; + 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 = assigned_value_type; - id_type.type_source = GDScriptParser::DataType::INFERRED; - id_type.is_constant = false; + id_type.kind = GDScriptParser::DataType::VARIANT; + id_type.type_source = GDScriptParser::DataType::UNDETECTED; identifier->variable_source->set_datatype(id_type); } } break; case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: { GDScriptParser::DataType id_type = identifier->bind_source->get_datatype(); if (!id_type.is_hard_type()) { - id_type = assigned_value_type; - id_type.type_source = GDScriptParser::DataType::INFERRED; - id_type.is_constant = false; + id_type.kind = GDScriptParser::DataType::VARIANT; + id_type.type_source = GDScriptParser::DataType::UNDETECTED; identifier->variable_source->set_datatype(id_type); } } break; @@ -2936,7 +2939,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri } else { GDScriptParser::DataType base_type = p_subscript->base->get_datatype(); - if (base_type.is_variant()) { + if (base_type.is_variant() || !base_type.is_hard_type()) { result_type.kind = GDScriptParser::DataType::VARIANT; mark_node_unsafe(p_subscript); } else { @@ -3059,6 +3062,9 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri result_type.kind = GDScriptParser::DataType::BUILTIN; result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED; + if (base_type.kind != GDScriptParser::DataType::BUILTIN) { + base_type.builtin_type = Variant::OBJECT; + } switch (base_type.builtin_type) { // Can't index at all. case Variant::RID: @@ -3119,6 +3125,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::PLANE: case Variant::COLOR: case Variant::DICTIONARY: + case Variant::OBJECT: result_type.kind = GDScriptParser::DataType::VARIANT; result_type.type_source = GDScriptParser::DataType::UNDETECTED; break; @@ -3133,7 +3140,6 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri } break; // Here for completeness. - case Variant::OBJECT: case Variant::VARIANT_MAX: break; } @@ -3300,7 +3306,13 @@ GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_va current = current->_owner; } - Ref<GDScriptParserRef> ref = get_parser_for(current->path); + Ref<GDScriptParserRef> ref = get_parser_for(current->get_path()); + if (ref.is_null()) { + push_error("Could not find script in path.", p_source); + GDScriptParser::DataType error_type; + error_type.kind = GDScriptParser::DataType::VARIANT; + return error_type; + } ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); GDScriptParser::ClassNode *found = ref->get_parser()->head; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 2c02291795..9eee0b57f3 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -1019,25 +1019,32 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } } else if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name)) { // Assignment to member property. - GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value); + GDScriptCodeGenerator::Address assigned_value = _parse_expression(codegen, r_error, assignment->assigned_value); if (r_error) { return GDScriptCodeGenerator::Address(); } - GDScriptCodeGenerator::Address assign_temp = assigned; + + GDScriptCodeGenerator::Address to_assign = assigned_value; + bool has_operation = assignment->operation != GDScriptParser::AssignmentNode::OP_NONE; StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name; - if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) { + if (has_operation) { + GDScriptCodeGenerator::Address op_result = codegen.add_temporary(); GDScriptCodeGenerator::Address member = codegen.add_temporary(); gen->write_get_member(member, name); - gen->write_binary_operator(assigned, assignment->variant_op, member, assigned); - gen->pop_temporary(); + gen->write_binary_operator(op_result, assignment->variant_op, member, assigned_value); + gen->pop_temporary(); // Pop member temp. + to_assign = op_result; } - gen->write_set_member(assigned, name); + gen->write_set_member(to_assign, name); - if (assign_temp.mode == GDScriptCodeGenerator::Address::TEMPORARY) { - gen->pop_temporary(); + if (to_assign.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + gen->pop_temporary(); // Pop the assigned expression or the temp result if it has operation. + } + if (has_operation && assigned_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + gen->pop_temporary(); // Pop the assigned expression if not done before. } } else { // Regular assignment. diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index 83805f626a..e49bf518a2 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -2222,8 +2222,11 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c if (obj) { List<String> options; obj->get_argument_options(p_method, p_argidx, &options); - for (const String &F : options) { - ScriptCodeCompletionOption option(F, ScriptCodeCompletionOption::KIND_FUNCTION); + for (String &opt : options) { + if (opt.is_quoted()) { + opt = opt.unquote().quote(quote_style); // Handle user preference. + } + ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_FUNCTION); r_result.insert(option.display, option); } } @@ -2643,23 +2646,26 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c } } break; case GDScriptParser::COMPLETION_GET_NODE: { + // Handles the `$Node/Path` or `$"Some NodePath"` syntax specifically. if (p_owner) { List<String> opts; p_owner->get_argument_options("get_node", 0, &opts); for (const String &E : opts) { + r_forced = true; String opt = E.strip_edges(); if (opt.is_quoted()) { - r_forced = true; - String idopt = opt.unquote(); - if (idopt.replace("/", "_").is_valid_identifier()) { - ScriptCodeCompletionOption option(idopt, ScriptCodeCompletionOption::KIND_NODE_PATH); - options.insert(option.display, option); - } else { - ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH); - options.insert(option.display, option); - } + // Remove quotes so that we can handle user preferred quote style, + // or handle NodePaths which are valid identifiers and don't need quotes. + opt = opt.unquote(); } + // The path needs quotes if it's not a valid identifier (with an exception + // for "/" as path separator, which also doesn't require quotes). + if (!opt.replace("/", "_").is_valid_identifier()) { + opt = opt.quote(quote_style); // Handle user preference. + } + ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH); + options.insert(option.display, option); } // Get autoloads. diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 63817e970a..ad75e8174c 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -1620,6 +1620,10 @@ GDScriptParser::ForNode *GDScriptParser::parse_for() { n_for->list = parse_expression(false); + if (!n_for->list) { + push_error(R"(Expected a list or range after "in".)"); + } + consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)"); // Save break/continue state. diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index c383830c82..50c1f68440 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -133,13 +133,12 @@ GDScriptTestRunner::GDScriptTestRunner(const String &p_source_dir, bool p_init_l if (do_init_languages) { init_language(p_source_dir); - - // Enable all warnings for GDScript, so we can test them. - ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/enable", true); - for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) { - String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower(); - ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/" + warning, true); - } + } + // Enable all warnings for GDScript, so we can test them. + ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/enable", true); + for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) { + String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower(); + ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/" + warning, true); } // Enable printing to show results diff --git a/modules/gdscript/tests/scripts/analyzer/features/auto_inferred_type_dont_error.out b/modules/gdscript/tests/scripts/analyzer/features/auto_inferred_type_dont_error.out index 0e9f482af4..481016138a 100644 --- a/modules/gdscript/tests/scripts/analyzer/features/auto_inferred_type_dont_error.out +++ b/modules/gdscript/tests/scripts/analyzer/features/auto_inferred_type_dont_error.out @@ -1,2 +1,6 @@ GDTEST_OK +>> WARNING +>> Line: 6 +>> UNSAFE_METHOD_ACCESS +>> The method 'free' is not present on the inferred type 'Variant' (but may be present on a subtype). Ok diff --git a/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.gd b/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.gd new file mode 100644 index 0000000000..630b20c282 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.gd @@ -0,0 +1,11 @@ +# https://github.com/godotengine/godot/issues/43503 + +var test_var = null + + +func test(): + print(test_var.x) + + +func _init(): + test_var = Vector3() diff --git a/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.out b/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.out new file mode 100644 index 0000000000..94e2ec2af8 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/class_inference_is_weak.out @@ -0,0 +1,2 @@ +GDTEST_OK +0 diff --git a/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.gd b/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.gd new file mode 100644 index 0000000000..b3784dffa3 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.gd @@ -0,0 +1,14 @@ +# https://github.com/godotengine/godot/issues/41064 +var x = true + +func test(): + var int_var: int = 0 + var dyn_var = 2 + + if x: + dyn_var = 5 + else: + dyn_var = Node.new() + + int_var = dyn_var + print(int_var) diff --git a/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.out b/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.out new file mode 100644 index 0000000000..952029f665 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/local_inference_is_weak.out @@ -0,0 +1,2 @@ +GDTEST_OK +5 diff --git a/modules/gdscript/tests/scripts/analyzer/features/subscript_self.gd b/modules/gdscript/tests/scripts/analyzer/features/subscript_self.gd new file mode 100644 index 0000000000..f9a8b23b92 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/subscript_self.gd @@ -0,0 +1,8 @@ +# https://github.com/godotengine/godot/issues/43221 +extends Node + +func test(): + name = "Node" + print(self["name"]) + self["name"] = "Changed" + print(name) diff --git a/modules/gdscript/tests/scripts/analyzer/features/subscript_self.out b/modules/gdscript/tests/scripts/analyzer/features/subscript_self.out new file mode 100644 index 0000000000..6417f4f8da --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/subscript_self.out @@ -0,0 +1,3 @@ +GDTEST_OK +Node +Changed diff --git a/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.gd b/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.gd new file mode 100644 index 0000000000..f6526aefb4 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.gd @@ -0,0 +1,13 @@ +extends Node + +func test(): + process_priority = 10 + var change = 20 + + print(process_priority) + print(change) + + process_priority += change + + print(process_priority) + print(change) diff --git a/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.out b/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.out new file mode 100644 index 0000000000..c9e6b34c77 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/assign_member_with_operation.out @@ -0,0 +1,5 @@ +GDTEST_OK +10 +20 +30 +20 diff --git a/modules/gltf/config.py b/modules/gltf/config.py index 52a97c93aa..a4736321fa 100644 --- a/modules/gltf/config.py +++ b/modules/gltf/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return env["tools"] and not env["disable_3d"] + return not env["disable_3d"] def configure(env): @@ -22,6 +22,8 @@ def get_doc_classes(): "GLTFSpecGloss", "GLTFState", "GLTFTexture", + "GLTFDocumentExtension", + "GLTFDocumentExtensionConvertImporterMesh", ] diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml index 16e649f390..8d8e25e8b3 100644 --- a/modules/gltf/doc_classes/GLTFDocument.xml +++ b/modules/gltf/doc_classes/GLTFDocument.xml @@ -30,4 +30,8 @@ </description> </method> </methods> + <members> + <member name="extensions" type="GLTFDocumentExtension[]" setter="set_extensions" getter="get_extensions" default="[]"> + </member> + </members> </class> diff --git a/modules/gltf/doc_classes/GLTFDocumentExtension.xml b/modules/gltf/doc_classes/GLTFDocumentExtension.xml new file mode 100644 index 0000000000..390bd3b30b --- /dev/null +++ b/modules/gltf/doc_classes/GLTFDocumentExtension.xml @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFDocumentExtension" inherits="Resource" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="export_post"> + <return type="int" enum="Error" /> + <argument index="0" name="document" type="GLTFDocument" /> + <description> + </description> + </method> + <method name="export_preflight"> + <return type="int" enum="Error" /> + <argument index="0" name="document" type="GLTFDocument" /> + <argument index="1" name="node" type="Node" /> + <description> + </description> + </method> + <method name="get_export_setting" qualifiers="const"> + <return type="Variant" /> + <argument index="0" name="key" type="StringName" /> + <description> + </description> + </method> + <method name="get_export_setting_keys" qualifiers="const"> + <return type="Array" /> + <description> + </description> + </method> + <method name="get_import_setting" qualifiers="const"> + <return type="Variant" /> + <argument index="0" name="key" type="StringName" /> + <description> + </description> + </method> + <method name="get_import_setting_keys" qualifiers="const"> + <return type="Array" /> + <description> + </description> + </method> + <method name="import_post"> + <return type="int" enum="Error" /> + <argument index="0" name="document" type="GLTFDocument" /> + <argument index="1" name="node" type="Node" /> + <description> + </description> + </method> + <method name="import_preflight"> + <return type="int" enum="Error" /> + <argument index="0" name="document" type="GLTFDocument" /> + <description> + </description> + </method> + <method name="set_export_setting"> + <return type="void" /> + <argument index="0" name="key" type="StringName" /> + <argument index="1" name="value" type="Variant" /> + <description> + </description> + </method> + <method name="set_import_setting"> + <return type="void" /> + <argument index="0" name="key" type="StringName" /> + <argument index="1" name="value" type="Variant" /> + <description> + </description> + </method> + </methods> +</class> diff --git a/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml b/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml new file mode 100644 index 0000000000..452eec5f4f --- /dev/null +++ b/modules/gltf/doc_classes/GLTFDocumentExtensionConvertImporterMesh.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFDocumentExtensionConvertImporterMesh" inherits="GLTFDocumentExtension" version="4.0"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> +</class> diff --git a/modules/gltf/doc_classes/GLTFMesh.xml b/modules/gltf/doc_classes/GLTFMesh.xml index 51e9fc032a..1e7199d229 100644 --- a/modules/gltf/doc_classes/GLTFMesh.xml +++ b/modules/gltf/doc_classes/GLTFMesh.xml @@ -9,7 +9,7 @@ <members> <member name="blend_weights" type="PackedFloat32Array" setter="set_blend_weights" getter="get_blend_weights" default="PackedFloat32Array()"> </member> - <member name="mesh" type="EditorSceneImporterMesh" setter="set_mesh" getter="get_mesh"> + <member name="mesh" type="ImporterMesh" setter="set_mesh" getter="get_mesh"> </member> </members> </class> diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp index 3ce5ea23dc..25fda7ef3b 100644 --- a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp +++ b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp @@ -28,6 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#if TOOLS_ENABLED #include "editor_scene_exporter_gltf_plugin.h" #include "core/config/project_settings.h" #include "core/error/error_list.h" @@ -93,3 +94,5 @@ void SceneExporterGLTFPlugin::convert_scene_to_gltf2() { file_export_lib->set_current_file(filename + String(".gltf")); file_export_lib->popup_centered_ratio(); } + +#endif // TOOLS_ENABLED diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.h b/modules/gltf/editor_scene_exporter_gltf_plugin.h index c4f277fca2..89a8e27053 100644 --- a/modules/gltf/editor_scene_exporter_gltf_plugin.h +++ b/modules/gltf/editor_scene_exporter_gltf_plugin.h @@ -31,7 +31,9 @@ #ifndef EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H #define EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H +#if TOOLS_ENABLED #include "editor/editor_plugin.h" + #include "editor_scene_importer_gltf.h" class SceneExporterGLTFPlugin : public EditorPlugin { @@ -47,5 +49,5 @@ public: bool has_main_screen() const override; SceneExporterGLTFPlugin(class EditorNode *p_node); }; - +#endif // TOOLS_ENABLED #endif // EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H diff --git a/modules/gltf/editor_scene_importer_gltf.cpp b/modules/gltf/editor_scene_importer_gltf.cpp index 12796c41d7..25875e7396 100644 --- a/modules/gltf/editor_scene_importer_gltf.cpp +++ b/modules/gltf/editor_scene_importer_gltf.cpp @@ -28,6 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#if TOOLS_ENABLED #include "editor_scene_importer_gltf.h" #include "gltf_document.h" @@ -60,3 +61,5 @@ Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path, int p_bake_fps) { return Ref<Animation>(); } + +#endif // TOOLS_ENABLED diff --git a/modules/gltf/editor_scene_importer_gltf.h b/modules/gltf/editor_scene_importer_gltf.h index eb8775b137..90663612a1 100644 --- a/modules/gltf/editor_scene_importer_gltf.h +++ b/modules/gltf/editor_scene_importer_gltf.h @@ -30,16 +30,17 @@ #ifndef EDITOR_SCENE_IMPORTER_GLTF_H #define EDITOR_SCENE_IMPORTER_GLTF_H - +#ifdef TOOLS_ENABLED #include "gltf_state.h" +#include "gltf_document_extension.h" + #include "editor/import/resource_importer_scene.h" #include "scene/main/node.h" #include "scene/resources/packed_scene.h" class Animation; -#ifdef TOOLS_ENABLED class EditorSceneImporterGLTF : public EditorSceneImporter { GDCLASS(EditorSceneImporterGLTF, EditorSceneImporter); @@ -50,5 +51,5 @@ public: virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) override; }; -#endif +#endif // TOOLS_ENABLED #endif // EDITOR_SCENE_IMPORTER_GLTF_H diff --git a/modules/gltf/gltf_accessor.cpp b/modules/gltf/gltf_accessor.cpp index daeb084916..85cec3fec4 100644 --- a/modules/gltf/gltf_accessor.cpp +++ b/modules/gltf/gltf_accessor.cpp @@ -30,6 +30,8 @@ #include "gltf_accessor.h" +#include "gltf_document_extension.h" + void GLTFAccessor::_bind_methods() { ClassDB::bind_method(D_METHOD("get_buffer_view"), &GLTFAccessor::get_buffer_view); ClassDB::bind_method(D_METHOD("set_buffer_view", "buffer_view"), &GLTFAccessor::set_buffer_view); diff --git a/modules/gltf/gltf_accessor.h b/modules/gltf/gltf_accessor.h index 57aea1026c..bec511f974 100644 --- a/modules/gltf/gltf_accessor.h +++ b/modules/gltf/gltf_accessor.h @@ -32,7 +32,9 @@ #define GLTF_ACCESSOR_H #include "core/io/resource.h" + #include "gltf_document.h" +#include "gltf_document_extension.h" struct GLTFAccessor : public Resource { GDCLASS(GLTFAccessor, Resource); diff --git a/modules/gltf/gltf_buffer_view.cpp b/modules/gltf/gltf_buffer_view.cpp index ba38a11c4c..d00e0f040f 100644 --- a/modules/gltf/gltf_buffer_view.cpp +++ b/modules/gltf/gltf_buffer_view.cpp @@ -30,6 +30,8 @@ #include "gltf_buffer_view.h" +#include "gltf_document_extension.h" + void GLTFBufferView::_bind_methods() { ClassDB::bind_method(D_METHOD("get_buffer"), &GLTFBufferView::get_buffer); ClassDB::bind_method(D_METHOD("set_buffer", "buffer"), &GLTFBufferView::set_buffer); diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index 3f1f218e78..ba98592600 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -33,6 +33,8 @@ #include "gltf_accessor.h" #include "gltf_animation.h" #include "gltf_camera.h" +#include "gltf_document_extension.h" +#include "gltf_document_extension_convert_importer_mesh.h" #include "gltf_light.h" #include "gltf_mesh.h" #include "gltf_node.h" @@ -49,6 +51,7 @@ #include "core/io/json.h" #include "core/math/disjoint_set.h" #include "core/math/vector2.h" +#include "core/variant/dictionary.h" #include "core/variant/typed_array.h" #include "core/variant/variant.h" #include "core/version.h" @@ -57,8 +60,12 @@ #include "editor/import/resource_importer_scene.h" #include "scene/2d/node_2d.h" #include "scene/3d/camera_3d.h" +#include "scene/3d/mesh_instance_3d.h" #include "scene/3d/multimesh_instance_3d.h" #include "scene/animation/animation_player.h" +#include "scene/resources/importer_mesh.h" +#include "scene/resources/mesh.h" +#include "scene/resources/multimesh.h" #include "scene/resources/surface_tool.h" #include "modules/modules_enabled.gen.h" @@ -2101,7 +2108,7 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { Array meshes; for (GLTFMeshIndex gltf_mesh_i = 0; gltf_mesh_i < state->meshes.size(); gltf_mesh_i++) { print_verbose("glTF: Serializing mesh: " + itos(gltf_mesh_i)); - Ref<EditorSceneImporterMesh> import_mesh = state->meshes.write[gltf_mesh_i]->get_mesh(); + Ref<ImporterMesh> import_mesh = state->meshes.write[gltf_mesh_i]->get_mesh(); if (import_mesh.is_null()) { continue; } @@ -2493,7 +2500,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { Array primitives = d["primitives"]; const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary(); - Ref<EditorSceneImporterMesh> import_mesh; + Ref<ImporterMesh> import_mesh; import_mesh.instantiate(); String mesh_name = "mesh"; if (d.has("name") && !String(d["name"]).is_empty()) { @@ -2732,17 +2739,18 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { bool generate_tangents = (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL")); + Ref<SurfaceTool> mesh_surface_tool; + mesh_surface_tool.instantiate(); + mesh_surface_tool->create_from_triangle_arrays(array); + if (a.has("JOINTS_0") && a.has("JOINTS_1")) { + mesh_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); + } + mesh_surface_tool->index(); if (generate_tangents) { //must generate mikktspace tangents.. ergh.. - Ref<SurfaceTool> st; - st.instantiate(); - st->create_from_triangle_arrays(array); - if (a.has("JOINTS_0") && a.has("JOINTS_1")) { - st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); - } - st->generate_tangents(); - array = st->commit_to_arrays(); + mesh_surface_tool->generate_tangents(); } + array = mesh_surface_tool->commit_to_arrays(); Array morphs; //blend shapes @@ -2772,8 +2780,6 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { array_copy[l] = array[l]; } - array_copy[Mesh::ARRAY_INDEX] = Variant(); - if (t.has("POSITION")) { Vector<Vector3> varr = _decode_accessor_as_vec3(state, t["POSITION"], true); const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX]; @@ -2852,17 +2858,17 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { array_copy[Mesh::ARRAY_TANGENT] = tangents_v4; } + Ref<SurfaceTool> blend_surface_tool; + blend_surface_tool.instantiate(); + blend_surface_tool->create_from_triangle_arrays(array_copy); + if (a.has("JOINTS_0") && a.has("JOINTS_1")) { + blend_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); + } + blend_surface_tool->index(); if (generate_tangents) { - Ref<SurfaceTool> st; - st.instantiate(); - st->create_from_triangle_arrays(array_copy); - if (a.has("JOINTS_0") && a.has("JOINTS_1")) { - st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); - } - st->deindex(); - st->generate_tangents(); - array_copy = st->commit_to_arrays(); + blend_surface_tool->generate_tangents(); } + array_copy = blend_surface_tool->commit_to_arrays(); morphs.push_back(array_copy); } @@ -2875,19 +2881,23 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { const int material = p["material"]; ERR_FAIL_INDEX_V(material, state->materials.size(), ERR_FILE_CORRUPT); Ref<BaseMaterial3D> mat3d = state->materials[material]; + ERR_FAIL_NULL_V(mat3d, ERR_FILE_CORRUPT); if (has_vertex_color) { mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); } mat = mat3d; - } else if (has_vertex_color) { + } else { Ref<StandardMaterial3D> mat3d; mat3d.instantiate(); - mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + if (has_vertex_color) { + mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + } mat = mat3d; } - - import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat, mat.is_valid() ? mat->get_name() : String(), flags); + ERR_FAIL_NULL_V(mat, ERR_FILE_CORRUPT); + import_mesh->add_surface(primitive, array, morphs, + Dictionary(), mat, mat->get_name(), flags); } Vector<float> blend_weights; @@ -3610,7 +3620,6 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { material->set_cull_mode(BaseMaterial3D::CULL_DISABLED); } } - if (d.has("alphaMode")) { const String &am = d["alphaMode"]; if (am == "BLEND") { @@ -5007,72 +5016,65 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> state, MeshInst if (p_mesh_instance->get_mesh().is_null()) { return -1; } - Ref<EditorSceneImporterMesh> import_mesh; - import_mesh.instantiate(); - Ref<Mesh> godot_mesh = p_mesh_instance->get_mesh(); - if (godot_mesh.is_null()) { - return -1; - } + Ref<ImporterMesh> current_mesh; + current_mesh.instantiate(); Vector<float> blend_weights; - Vector<String> blend_names; - int32_t blend_count = godot_mesh->get_blend_shape_count(); - blend_names.resize(blend_count); - blend_weights.resize(blend_count); - for (int32_t blend_i = 0; blend_i < godot_mesh->get_blend_shape_count(); blend_i++) { - String blend_name = godot_mesh->get_blend_shape_name(blend_i); - blend_names.write[blend_i] = blend_name; - import_mesh->add_blend_shape(blend_name); - } - for (int32_t surface_i = 0; surface_i < godot_mesh->get_surface_count(); surface_i++) { - Mesh::PrimitiveType primitive_type = godot_mesh->surface_get_primitive_type(surface_i); - Array arrays = godot_mesh->surface_get_arrays(surface_i); - Array blend_shape_arrays = godot_mesh->surface_get_blend_shape_arrays(surface_i); - Ref<Material> mat = godot_mesh->surface_get_material(surface_i); - Ref<ArrayMesh> godot_array_mesh = godot_mesh; - String surface_name; - if (godot_array_mesh.is_valid()) { - surface_name = godot_array_mesh->surface_get_name(surface_i); - } - if (p_mesh_instance->get_surface_override_material(surface_i).is_valid()) { - mat = p_mesh_instance->get_surface_override_material(surface_i); - } - if (p_mesh_instance->get_material_override().is_valid()) { - mat = p_mesh_instance->get_material_override(); - } - import_mesh->add_surface(primitive_type, arrays, blend_shape_arrays, Dictionary(), mat, surface_name, godot_mesh->surface_get_format(surface_i)); - } - for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) { - blend_weights.write[blend_i] = 0.0f; + { + Ref<Mesh> import_mesh = p_mesh_instance->get_mesh(); + Ref<ArrayMesh> import_array_mesh = p_mesh_instance->get_mesh(); + if (import_mesh->get_blend_shape_count()) { + ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED; + if (import_array_mesh.is_valid()) { + shape_mode = import_array_mesh->get_blend_shape_mode(); + } + current_mesh->set_blend_shape_mode(shape_mode); + for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) { + current_mesh->add_blend_shape(import_mesh->get_blend_shape_name(morph_i)); + } + } + for (int32_t surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) { + Array array = import_mesh->surface_get_arrays(surface_i); + Ref<Material> mat = import_mesh->surface_get_material(surface_i); + String mat_name; + if (mat.is_valid()) { + mat_name = mat->get_name(); + } + current_mesh->add_surface(import_mesh->surface_get_primitive_type(surface_i), + array, import_mesh->surface_get_blend_shape_arrays(surface_i), import_mesh->surface_get_lods(surface_i), mat, + mat_name, import_mesh->surface_get_format(surface_i)); + } + int32_t blend_count = import_mesh->get_blend_shape_count(); + blend_weights.resize(blend_count); + for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) { + blend_weights.write[blend_i] = 0.0f; + } } Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); - gltf_mesh->set_mesh(import_mesh); + gltf_mesh->set_mesh(current_mesh); gltf_mesh->set_blend_weights(blend_weights); GLTFMeshIndex mesh_i = state->meshes.size(); state->meshes.push_back(gltf_mesh); return mesh_i; } -EditorSceneImporterMeshNode3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) { +ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> state, Node *parent_node, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; ERR_FAIL_INDEX_V(gltf_node->mesh, state->meshes.size(), nullptr); - EditorSceneImporterMeshNode3D *mi = memnew(EditorSceneImporterMeshNode3D); + ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D); print_verbose("glTF: Creating mesh for: " + gltf_node->get_name()); Ref<GLTFMesh> mesh = state->meshes.write[gltf_node->mesh]; if (mesh.is_null()) { return mi; } - Ref<EditorSceneImporterMesh> import_mesh = mesh->get_mesh(); + Ref<ImporterMesh> import_mesh = mesh->get_mesh(); if (import_mesh.is_null()) { return mi; } mi->set_mesh(import_mesh); - for (int i = 0; i < mesh->get_blend_weights().size(); i++) { - mi->set("blend_shapes/" + mesh->get_mesh()->get_blend_shape_name(i), mesh->get_blend_weights()[i]); - } return mi; } @@ -5241,7 +5243,7 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, co return; } else if (cast_to<MultiMeshInstance3D>(p_current)) { MultiMeshInstance3D *multi = cast_to<MultiMeshInstance3D>(p_current); - _convert_mult_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, state); + _convert_multi_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, state); #ifdef MODULE_CSG_ENABLED } else if (cast_to<CSGShape3D>(p_current)) { CSGShape3D *shape = cast_to<CSGShape3D>(p_current); @@ -5292,13 +5294,8 @@ void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeInd } Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); - Ref<EditorSceneImporterMesh> import_mesh; - import_mesh.instantiate(); - Ref<ArrayMesh> array_mesh = csg->get_meshes()[1]; - for (int32_t surface_i = 0; surface_i < array_mesh->get_surface_count(); surface_i++) { - import_mesh->add_surface(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, array_mesh->surface_get_arrays(surface_i), Array(), Dictionary(), mat, array_mesh->surface_get_name(surface_i)); - } - gltf_mesh->set_mesh(import_mesh); + Ref<ImporterMesh> array_mesh = csg->get_meshes()[1]; + gltf_mesh->set_mesh(array_mesh); GLTFMeshIndex mesh_i = state->meshes.size(); state->meshes.push_back(gltf_mesh); gltf_node->mesh = mesh_i; @@ -5364,7 +5361,7 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex Vector3 cell_location = cells[k]; int32_t cell = p_grid_map->get_cell_item( Vector3(cell_location.x, cell_location.y, cell_location.z)); - EditorSceneImporterMeshNode3D *import_mesh_node = memnew(EditorSceneImporterMeshNode3D); + ImporterMeshInstance3D *import_mesh_node = memnew(ImporterMeshInstance3D); import_mesh_node->set_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)); Transform3D cell_xform; cell_xform.basis.set_orthogonal_index( @@ -5386,49 +5383,72 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex } #endif // MODULE_GRIDMAP_ENABLED -void GLTFDocument::_convert_mult_mesh_instance_to_gltf(MultiMeshInstance3D *p_multi_mesh_instance, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { +void GLTFDocument::_convert_multi_mesh_instance_to_gltf( + MultiMeshInstance3D *p_multi_mesh_instance, + GLTFNodeIndex p_parent_node_index, + GLTFNodeIndex p_root_node_index, + Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { + ERR_FAIL_COND(!p_multi_mesh_instance); Ref<MultiMesh> multi_mesh = p_multi_mesh_instance->get_multimesh(); - if (multi_mesh.is_valid()) { - for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count(); - instance_i++) { - GLTFNode *new_gltf_node = memnew(GLTFNode); - Transform3D transform; - if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) { - Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i); - transform.origin = - Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y); - real_t rotation = xform_2d.get_rotation(); - Quaternion quaternion(Vector3(0, 1, 0), rotation); - Size2 scale = xform_2d.get_scale(); - transform.basis.set_quaternion_scale(quaternion, - Vector3(scale.x, 0, scale.y)); - transform = - p_multi_mesh_instance->get_transform() * transform; - } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) { - transform = p_multi_mesh_instance->get_transform() * - multi_mesh->get_instance_transform(instance_i); - } - Ref<ArrayMesh> mm = multi_mesh->get_mesh(); - if (mm.is_valid()) { - Ref<EditorSceneImporterMesh> mesh; - mesh.instantiate(); - for (int32_t surface_i = 0; surface_i < mm->get_surface_count(); surface_i++) { - Array surface = mm->surface_get_arrays(surface_i); - mesh->add_surface(mm->surface_get_primitive_type(surface_i), surface, Array(), Dictionary(), - mm->surface_get_material(surface_i), mm->get_name()); - } - Ref<GLTFMesh> gltf_mesh; - gltf_mesh.instantiate(); - gltf_mesh->set_name(multi_mesh->get_name()); - gltf_mesh->set_mesh(mesh); - new_gltf_node->mesh = state->meshes.size(); - state->meshes.push_back(gltf_mesh); - } - new_gltf_node->xform = transform; - new_gltf_node->set_name(_gen_unique_name(state, p_multi_mesh_instance->get_name())); - gltf_node->children.push_back(state->nodes.size()); - state->nodes.push_back(new_gltf_node); + if (multi_mesh.is_null()) { + return; + } + Ref<GLTFMesh> gltf_mesh; + gltf_mesh.instantiate(); + Ref<Mesh> mesh = multi_mesh->get_mesh(); + if (mesh.is_null()) { + return; + } + gltf_mesh->set_name(multi_mesh->get_name()); + Ref<ImporterMesh> importer_mesh; + importer_mesh.instantiate(); + Ref<ArrayMesh> array_mesh = multi_mesh->get_mesh(); + if (array_mesh.is_valid()) { + importer_mesh->set_blend_shape_mode(array_mesh->get_blend_shape_mode()); + for (int32_t blend_i = 0; blend_i < array_mesh->get_blend_shape_count(); blend_i++) { + importer_mesh->add_blend_shape(array_mesh->get_blend_shape_name(blend_i)); + } + } + for (int32_t surface_i = 0; surface_i < mesh->get_surface_count(); surface_i++) { + Ref<Material> mat = mesh->surface_get_material(surface_i); + String material_name; + if (mat.is_valid()) { + material_name = mat->get_name(); } + Array blend_arrays; + if (array_mesh.is_valid()) { + blend_arrays = array_mesh->surface_get_blend_shape_arrays(surface_i); + } + importer_mesh->add_surface(mesh->surface_get_primitive_type(surface_i), mesh->surface_get_arrays(surface_i), + blend_arrays, mesh->surface_get_lods(surface_i), mat, material_name, mesh->surface_get_format(surface_i)); + } + gltf_mesh->set_mesh(importer_mesh); + GLTFMeshIndex mesh_index = state->meshes.size(); + state->meshes.push_back(gltf_mesh); + for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count(); + instance_i++) { + Transform3D transform; + if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) { + Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i); + transform.origin = + Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y); + real_t rotation = xform_2d.get_rotation(); + Quaternion quaternion(Vector3(0, 1, 0), rotation); + Size2 scale = xform_2d.get_scale(); + transform.basis.set_quaternion_scale(quaternion, + Vector3(scale.x, 0, scale.y)); + transform = p_multi_mesh_instance->get_transform() * transform; + } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) { + transform = p_multi_mesh_instance->get_transform() * + multi_mesh->get_instance_transform(instance_i); + } + Ref<GLTFNode> new_gltf_node; + new_gltf_node.instantiate(); + new_gltf_node->mesh = mesh_index; + new_gltf_node->xform = transform; + new_gltf_node->set_name(_gen_unique_name(state, p_multi_mesh_instance->get_name())); + gltf_node->children.push_back(state->nodes.size()); + state->nodes.push_back(new_gltf_node); } } @@ -6106,8 +6126,8 @@ void GLTFDocument::_process_mesh_instances(Ref<GLTFState> state, Node *scene_roo Map<GLTFNodeIndex, Node *>::Element *mi_element = state->scene_nodes.find(node_i); ERR_CONTINUE_MSG(mi_element == nullptr, vformat("Unable to find node %d", node_i)); - EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(mi_element->get()); - ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to EditorSceneImporterMeshNode3D", node_i, mi_element->get()->get_class_name())); + ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(mi_element->get()); + ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to ImporterMeshInstance3D", node_i, mi_element->get()->get_class_name())); const GLTFSkeletonIndex skel_i = state->skins.write[node->skin]->skeleton; Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skel_i]; @@ -6748,10 +6768,25 @@ Error GLTFDocument::save_scene(Node *p_node, const String &p_path, Ref<GLTFDocument> gltf_document; gltf_document.instantiate(); + for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + Error err = ext->export_preflight(this, p_node); + ERR_FAIL_COND_V(err != OK, err); + } + if (r_state == Ref<GLTFState>()) { r_state.instantiate(); } - return gltf_document->serialize(r_state, p_node, p_path); + Error err = gltf_document->serialize(r_state, p_node, p_path); + ERR_FAIL_COND_V(err != OK, err); + for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + err = ext->export_post(this); + ERR_FAIL_COND_V(err != OK, err); + } + return OK; } Node *GLTFDocument::import_scene_gltf(const String &p_path, uint32_t p_flags, int32_t p_bake_fps, Ref<GLTFState> r_state, List<String> *r_missing_deps, Error *r_err) { @@ -6764,6 +6799,15 @@ Node *GLTFDocument::import_scene_gltf(const String &p_path, uint32_t p_flags, in Ref<GLTFDocument> gltf_document; gltf_document.instantiate(); + for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + Error err = ext->import_preflight(this); + if (r_err) { + *r_err = err; + } + ERR_FAIL_COND_V(err != OK, nullptr); + } Error err = gltf_document->parse(r_state, p_path); if (r_err) { *r_err = err; @@ -6783,7 +6827,15 @@ Node *GLTFDocument::import_scene_gltf(const String &p_path, uint32_t p_flags, in gltf_document->_import_animation(r_state, ap, i, p_bake_fps); } } - + for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + err = ext->import_post(this, root); + if (r_err) { + *r_err = err; + } + ERR_FAIL_COND_V(err != OK, nullptr); + } return root; } @@ -6792,6 +6844,14 @@ void GLTFDocument::_bind_methods() { &GLTFDocument::save_scene, DEFVAL(0), DEFVAL(30), DEFVAL(Ref<GLTFState>())); ClassDB::bind_method(D_METHOD("import_scene", "path", "flags", "bake_fps", "state"), &GLTFDocument::import_scene, DEFVAL(0), DEFVAL(30), DEFVAL(Ref<GLTFState>())); + ClassDB::bind_method(D_METHOD("set_extensions", "extensions"), + &GLTFDocument::set_extensions); + ClassDB::bind_method(D_METHOD("get_extensions"), + &GLTFDocument::get_extensions); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "extensions", PROPERTY_HINT_ARRAY_TYPE, + vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "GLTFDocumentExtension"), + PROPERTY_USAGE_DEFAULT), + "set_extensions", "get_extensions"); } void GLTFDocument::_build_parent_hierachy(Ref<GLTFState> state) { @@ -6817,3 +6877,21 @@ Node *GLTFDocument::import_scene(const String &p_path, uint32_t p_flags, int32_t } return node; } + +void GLTFDocument::set_extensions(TypedArray<GLTFDocumentExtension> p_extensions) { + document_extensions = p_extensions; +} + +TypedArray<GLTFDocumentExtension> GLTFDocument::get_extensions() const { + return document_extensions; +} + +GLTFDocument::GLTFDocument() { + bool is_editor = ::Engine::get_singleton()->is_editor_hint(); + if (is_editor) { + return; + } + Ref<GLTFDocumentExtensionConvertImporterMesh> extension_editor; + extension_editor.instantiate(); + document_extensions.push_back(extension_editor); +} diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index 18aeb81bc0..7317c6a9a3 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -33,8 +33,11 @@ #include "gltf_animation.h" -#include "editor/import/scene_importer_mesh_node_3d.h" +#include "core/variant/dictionary.h" +#include "core/variant/variant.h" +#include "gltf_document_extension_convert_importer_mesh.h" #include "scene/3d/bone_attachment_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/light_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/node_3d.h" @@ -54,6 +57,7 @@ class GLTFSkeleton; class CSGShape3D; class GridMap; class MultiMeshInstance3D; +class GLTFDocumentExtension; using GLTFAccessorIndex = int; using GLTFAnimationIndex = int; @@ -74,11 +78,13 @@ class GLTFDocument : public Resource { friend class GLTFState; friend class GLTFSkin; friend class GLTFSkeleton; + TypedArray<GLTFDocumentExtension> document_extensions; private: const float BAKE_FPS = 30.0f; public: + GLTFDocument(); const int32_t JOINT_GROUP_SIZE = 4; enum GLTFType { TYPE_SCALAR, @@ -118,6 +124,8 @@ public: Error save_scene(Node *p_node, const String &p_path, const String &p_src_path, uint32_t p_flags, float p_bake_fps, Ref<GLTFState> r_state); + void set_extensions(TypedArray<GLTFDocumentExtension> p_extensions); + TypedArray<GLTFDocumentExtension> get_extensions() const; private: template <class T> @@ -280,12 +288,10 @@ private: Skeleton3D *skeleton, const GLTFNodeIndex node_index, const GLTFNodeIndex bone_index); - EditorSceneImporterMeshNode3D *_generate_mesh_instance(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); - Camera3D *_generate_camera(Ref<GLTFState> state, Node *scene_parent, - const GLTFNodeIndex node_index); - Node3D *_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); - Node3D *_generate_spatial(Ref<GLTFState> state, Node *scene_parent, - const GLTFNodeIndex node_index); + ImporterMeshInstance3D *_generate_mesh_instance(Ref<GLTFState> state, Node *parent_node, const GLTFNodeIndex node_index); + Camera3D *_generate_camera(Ref<GLTFState> state, Node *parent_node, const GLTFNodeIndex node_index); + Node3D *_generate_light(Ref<GLTFState> state, Node *parent_node, const GLTFNodeIndex node_index); + Node3D *_generate_spatial(Ref<GLTFState> state, Node *parent_node, const GLTFNodeIndex node_index); void _assign_scene_names(Ref<GLTFState> state); template <class T> T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, @@ -420,8 +426,8 @@ public: GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state); #endif // MODULE_GRIDMAP_ENABLED - void _convert_mult_mesh_instance_to_gltf( - MultiMeshInstance3D *p_scene_parent, + void _convert_multi_mesh_instance_to_gltf( + MultiMeshInstance3D *p_multi_mesh_instance, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state); diff --git a/modules/gltf/gltf_document_extension.cpp b/modules/gltf/gltf_document_extension.cpp new file mode 100644 index 0000000000..a423059a9c --- /dev/null +++ b/modules/gltf/gltf_document_extension.cpp @@ -0,0 +1,88 @@ +/*************************************************************************/ +/* gltf_document_extension.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "gltf_document_extension.h" + +#include "gltf_document.h" + +void GLTFDocumentExtension::_bind_methods() { + // Import + ClassDB::bind_method(D_METHOD("get_import_setting_keys"), + &GLTFDocumentExtension::get_import_setting_keys); + ClassDB::bind_method(D_METHOD("import_preflight", "document"), + &GLTFDocumentExtension::import_preflight); + ClassDB::bind_method(D_METHOD("get_import_setting", "key"), + &GLTFDocumentExtension::get_import_setting); + ClassDB::bind_method(D_METHOD("set_import_setting", "key", "value"), + &GLTFDocumentExtension::set_import_setting); + ClassDB::bind_method(D_METHOD("import_post", "document", "node"), + &GLTFDocumentExtension::import_post); + // Export + ClassDB::bind_method(D_METHOD("get_export_setting_keys"), + &GLTFDocumentExtension::get_export_setting_keys); + ClassDB::bind_method(D_METHOD("get_export_setting", "key"), + &GLTFDocumentExtension::get_export_setting); + ClassDB::bind_method(D_METHOD("set_export_setting", "key", "value"), + &GLTFDocumentExtension::set_export_setting); + ClassDB::bind_method(D_METHOD("export_preflight", "document", "node"), + &GLTFDocumentExtension::export_preflight); + ClassDB::bind_method(D_METHOD("export_post", "document"), + &GLTFDocumentExtension::export_post); +} + +Array GLTFDocumentExtension::get_import_setting_keys() const { + return import_settings.keys(); +} + +Variant GLTFDocumentExtension::get_import_setting(const StringName &p_key) const { + if (!import_settings.has(p_key)) { + return Variant(); + } + return import_settings[p_key]; +} + +void GLTFDocumentExtension::set_import_setting(const StringName &p_key, Variant p_var) { + import_settings[p_key] = p_var; +} + +Array GLTFDocumentExtension::get_export_setting_keys() const { + return import_settings.keys(); +} + +Variant GLTFDocumentExtension::get_export_setting(const StringName &p_key) const { + if (!import_settings.has(p_key)) { + return Variant(); + } + return import_settings[p_key]; +} + +void GLTFDocumentExtension::set_export_setting(const StringName &p_key, Variant p_var) { + import_settings[p_key] = p_var; +} diff --git a/modules/gltf/gltf_document_extension.h b/modules/gltf/gltf_document_extension.h new file mode 100644 index 0000000000..622a65708c --- /dev/null +++ b/modules/gltf/gltf_document_extension.h @@ -0,0 +1,63 @@ +/*************************************************************************/ +/* gltf_document_extension.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GLTF_DOCUMENT_EXTENSION_H +#define GLTF_DOCUMENT_EXTENSION_H + +#include "core/io/resource.h" +#include "core/variant/dictionary.h" +#include "core/variant/typed_array.h" +#include "core/variant/variant.h" +class GLTFDocument; +class GLTFDocumentExtension : public Resource { + GDCLASS(GLTFDocumentExtension, Resource); + + Dictionary import_settings; + Dictionary export_settings; + +protected: + static void _bind_methods(); + +public: + virtual Array get_import_setting_keys() const; + virtual Variant get_import_setting(const StringName &p_key) const; + virtual void set_import_setting(const StringName &p_key, Variant p_var); + virtual Error import_preflight(Ref<GLTFDocument> p_document) { return OK; } + virtual Error import_post(Ref<GLTFDocument> p_document, Node *p_node) { return OK; } + +public: + virtual Array get_export_setting_keys() const; + virtual Variant get_export_setting(const StringName &p_key) const; + virtual void set_export_setting(const StringName &p_key, Variant p_var); + virtual Error export_preflight(Ref<GLTFDocument> p_document, Node *p_node) { return OK; } + virtual Error export_post(Ref<GLTFDocument> p_document) { return OK; } +}; + +#endif // GLTF_DOCUMENT_EXTENSION_H diff --git a/modules/gltf/gltf_document_extension_convert_importer_mesh.cpp b/modules/gltf/gltf_document_extension_convert_importer_mesh.cpp new file mode 100644 index 0000000000..78a98dfa3e --- /dev/null +++ b/modules/gltf/gltf_document_extension_convert_importer_mesh.cpp @@ -0,0 +1,79 @@ +/*************************************************************************/ +/* gltf_document_extension_convert_importer_mesh.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "gltf_document_extension_convert_importer_mesh.h" +#include "scene/3d/mesh_instance_3d.h" +#include "scene/resources/importer_mesh.h" + +#include <cstddef> + +void GLTFDocumentExtensionConvertImporterMesh::_bind_methods() { +} + +Error GLTFDocumentExtensionConvertImporterMesh::import_post(Ref<GLTFDocument> p_document, Node *p_node) { + List<Node *> queue; + queue.push_back(p_node); + List<Node *> delete_queue; + while (!queue.is_empty()) { + List<Node *>::Element *E = queue.front(); + Node *node = E->get(); + { + ImporterMeshInstance3D *mesh_3d = cast_to<ImporterMeshInstance3D>(node); + if (mesh_3d) { + MeshInstance3D *mesh_instance_node_3d = memnew(MeshInstance3D); + Ref<ImporterMesh> mesh = mesh_3d->get_mesh(); + if (mesh.is_valid()) { + Ref<ArrayMesh> array_mesh = mesh->get_mesh(); + mesh_instance_node_3d->set_name(node->get_name()); + mesh_instance_node_3d->set_transform(mesh_3d->get_transform()); + mesh_instance_node_3d->set_mesh(array_mesh); + mesh_instance_node_3d->set_skin(mesh_3d->get_skin()); + mesh_instance_node_3d->set_skeleton_path(mesh_3d->get_skeleton_path()); + node->replace_by(mesh_instance_node_3d); + delete_queue.push_back(node); + } else { + memdelete(mesh_instance_node_3d); + } + } + } + int child_count = node->get_child_count(); + for (int i = 0; i < child_count; i++) { + queue.push_back(node->get_child(i)); + } + queue.pop_front(); + } + while (!queue.is_empty()) { + List<Node *>::Element *E = delete_queue.front(); + Node *node = E->get(); + memdelete(node); + delete_queue.pop_front(); + } + return OK; +} diff --git a/modules/gltf/gltf_document_extension_convert_importer_mesh.h b/modules/gltf/gltf_document_extension_convert_importer_mesh.h new file mode 100644 index 0000000000..85ddb4d250 --- /dev/null +++ b/modules/gltf/gltf_document_extension_convert_importer_mesh.h @@ -0,0 +1,55 @@ +/*************************************************************************/ +/* gltf_document_extension_convert_importer_mesh.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GLTF_EXTENSION_EDITOR_H +#define GLTF_EXTENSION_EDITOR_H + +#include "core/io/resource.h" +#include "core/variant/dictionary.h" + +#include "gltf_document.h" +#include "gltf_document_extension.h" +#include "scene/3d/importer_mesh_instance_3d.h" +#include "scene/3d/mesh_instance_3d.h" +#include "scene/main/node.h" +#include "scene/resources/importer_mesh.h" + +class GLTFDocumentExtension; +class GLTFDocument; +class GLTFDocumentExtensionConvertImporterMesh : public GLTFDocumentExtension { + GDCLASS(GLTFDocumentExtensionConvertImporterMesh, GLTFDocumentExtension); + +protected: + static void _bind_methods(); + +public: + Error import_post(Ref<GLTFDocument> p_document, Node *p_node) override; +}; +#endif // GLTF_EXTENSION_EDITOR_H diff --git a/modules/gltf/gltf_mesh.cpp b/modules/gltf/gltf_mesh.cpp index 8c10e42c89..747820521a 100644 --- a/modules/gltf/gltf_mesh.cpp +++ b/modules/gltf/gltf_mesh.cpp @@ -29,7 +29,7 @@ /*************************************************************************/ #include "gltf_mesh.h" -#include "editor/import/scene_importer_mesh.h" +#include "scene/resources/importer_mesh.h" void GLTFMesh::_bind_methods() { ClassDB::bind_method(D_METHOD("get_mesh"), &GLTFMesh::get_mesh); @@ -41,11 +41,11 @@ void GLTFMesh::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT32_ARRAY, "blend_weights"), "set_blend_weights", "get_blend_weights"); // Vector<float> } -Ref<EditorSceneImporterMesh> GLTFMesh::get_mesh() { +Ref<ImporterMesh> GLTFMesh::get_mesh() { return mesh; } -void GLTFMesh::set_mesh(Ref<EditorSceneImporterMesh> p_mesh) { +void GLTFMesh::set_mesh(Ref<ImporterMesh> p_mesh) { mesh = p_mesh; } diff --git a/modules/gltf/gltf_mesh.h b/modules/gltf/gltf_mesh.h index 0fc750fc9f..3aba0ede32 100644 --- a/modules/gltf/gltf_mesh.h +++ b/modules/gltf/gltf_mesh.h @@ -33,22 +33,23 @@ #include "core/io/resource.h" #include "editor/import/resource_importer_scene.h" -#include "editor/import/scene_importer_mesh.h" +#include "scene/3d/importer_mesh_instance_3d.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/mesh.h" class GLTFMesh : public Resource { GDCLASS(GLTFMesh, Resource); private: - Ref<EditorSceneImporterMesh> mesh; + Ref<ImporterMesh> mesh; Vector<float> blend_weights; protected: static void _bind_methods(); public: - Ref<EditorSceneImporterMesh> get_mesh(); - void set_mesh(Ref<EditorSceneImporterMesh> p_mesh); + Ref<ImporterMesh> get_mesh(); + void set_mesh(Ref<ImporterMesh> p_mesh); Vector<float> get_blend_weights(); void set_blend_weights(Vector<float> p_blend_weights); }; diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index d6614da804..61faba0dc5 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -36,6 +36,7 @@ #include "gltf_buffer_view.h" #include "gltf_camera.h" #include "gltf_document.h" +#include "gltf_document_extension.h" #include "gltf_light.h" #include "gltf_mesh.h" #include "gltf_node.h" diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index d6020f50f0..0aceb838f7 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -38,6 +38,8 @@ #include "gltf_buffer_view.h" #include "gltf_camera.h" #include "gltf_document.h" +#include "gltf_document_extension.h" +#include "gltf_document_extension_convert_importer_mesh.h" #include "gltf_light.h" #include "gltf_mesh.h" #include "gltf_node.h" @@ -79,6 +81,8 @@ void register_gltf_types() { GDREGISTER_CLASS(GLTFCamera); GDREGISTER_CLASS(GLTFLight); GDREGISTER_CLASS(GLTFState); + GDREGISTER_CLASS(GLTFDocumentExtensionConvertImporterMesh); + GDREGISTER_CLASS(GLTFDocumentExtension); GDREGISTER_CLASS(GLTFDocument); #endif } diff --git a/modules/mono/doc_classes/CSharpScript.xml b/modules/mono/doc_classes/CSharpScript.xml index 45a6f991bf..abd860a55f 100644 --- a/modules/mono/doc_classes/CSharpScript.xml +++ b/modules/mono/doc_classes/CSharpScript.xml @@ -8,7 +8,7 @@ See also [GodotSharp]. </description> <tutorials> - <link title="C# tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/c_sharp/index.html</link> + <link title="C# documentation index">https://docs.godotengine.org/en/latest/tutorials/scripting/c_sharp/index.html</link> </tutorials> <methods> <method name="new" qualifiers="vararg"> diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs index 0f50c90531..1d7bfaf0a4 100644 --- a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs +++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs @@ -121,6 +121,7 @@ namespace GodotTools.IdeMessaging this.messageHandler = messageHandler; this.logger = logger; + // TODO: Need to fetch the project data dir name from ProjectSettings instead of defaulting to ".godot" string projectMetadataDir = Path.Combine(godotProjectDir, ".godot", "mono", "metadata"); MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs index 8fe08e7e1d..746612477d 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs @@ -117,7 +117,7 @@ namespace Godot /// { /// for (int i = 0; i < 100; i++) /// { - /// await ToSignal(GetTree(), "idle_frame"); + /// await ToSignal(GetTree(), "process_frame"); /// GD.Print($"Frame {i}"); /// } /// } diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 375ad413c4..24bd1ed492 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -122,7 +122,7 @@ public: private: _GodotSharpDirs() { - res_data_dir = "res://.godot/mono"; + res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().plus_file("mono"); res_metadata_dir = res_data_dir.plus_file("metadata"); res_assemblies_base_dir = res_data_dir.plus_file("assemblies"); res_assemblies_dir = res_assemblies_base_dir.plus_file(GDMono::get_expected_api_build_config()); diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp index 6b616dd52d..d0a27b27c1 100644 --- a/modules/mono/utils/mono_reg_utils.cpp +++ b/modules/mono/utils/mono_reg_utils.cpp @@ -35,7 +35,7 @@ #include "core/os/os.h" -// Here, after os/os.h +#define WIN32_LEAN_AND_MEAN #include <windows.h> namespace MonoRegUtils { diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index ec04d50704..64aec5d359 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -36,6 +36,7 @@ #include "core/os/os.h" #ifdef WINDOWS_ENABLED +#define WIN32_LEAN_AND_MEAN #include <windows.h> #define ENV_PATH_SEP ";" diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py index b15479797c..e8990c43c8 100644 --- a/modules/visual_script/config.py +++ b/modules/visual_script/config.py @@ -17,6 +17,7 @@ def get_doc_classes(): "VisualScriptConstant", "VisualScriptConstructor", "VisualScriptCustomNode", + "VisualScriptCustomNodes", "VisualScriptDeconstruct", "VisualScriptEditor", "VisualScriptEmitSignal", diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml index 372d46bc10..be6bf00e50 100644 --- a/modules/visual_script/doc_classes/VisualScript.xml +++ b/modules/visual_script/doc_classes/VisualScript.xml @@ -9,7 +9,7 @@ You are most likely to use this class via the Visual Script editor or when writing plugins for it. </description> <tutorials> - <link title="VisualScript tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/visual_script/index.html</link> + <link title="VisualScript documentation index">https://docs.godotengine.org/en/latest/tutorials/scripting/visual_script/index.html</link> </tutorials> <methods> <method name="add_custom_signal"> diff --git a/doc/classes/VisualScriptCustomNodes.xml b/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml index 1681da7653..1681da7653 100644 --- a/doc/classes/VisualScriptCustomNodes.xml +++ b/modules/visual_script/doc_classes/VisualScriptCustomNodes.xml diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index cded1e587c..c62de64a85 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -121,7 +121,7 @@ public: ret = STEP_EXIT_FUNCTION_BIT; break; //return the yield case VisualScriptYield::YIELD_FRAME: - state->connect_to_signal(tree, "idle_frame", Array()); + state->connect_to_signal(tree, "process_frame", Array()); break; case VisualScriptYield::YIELD_PHYSICS_FRAME: state->connect_to_signal(tree, "physics_frame", Array()); diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index f6f360503f..618fe14137 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -26,7 +26,8 @@ <method name="close"> <return type="void" /> <description> - Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize]. + Close the peer connection and all data channels associated with it. + [b]Note:[/b] You cannot reuse this object for a new connection unless you call [method initialize]. </description> </method> <method name="create_data_channel"> diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml index ab7ef6c4d0..2f455c32fd 100644 --- a/modules/websocket/doc_classes/WebSocketPeer.xml +++ b/modules/websocket/doc_classes/WebSocketPeer.xml @@ -4,7 +4,7 @@ A class representing a specific WebSocket connection. </brief_description> <description> - This class represent a specific WebSocket connection, you can do lower level operations with it. + This class represents a specific WebSocket connection, allowing you to do lower level operations with it. You can choose to write to the socket in binary or text mode, and you can recognize the mode used for writing by the other peer. </description> <tutorials> diff --git a/platform/javascript/.eslintrc.libs.js b/platform/javascript/.eslintrc.libs.js index 81b1b8c864..8e579fd462 100644 --- a/platform/javascript/.eslintrc.libs.js +++ b/platform/javascript/.eslintrc.libs.js @@ -15,6 +15,7 @@ module.exports = { "IDBFS": true, "GodotOS": true, "GodotConfig": true, + "GodotEventListeners": true, "GodotRuntime": true, "GodotFS": true, "IDHandler": true, diff --git a/platform/javascript/SCsub b/platform/javascript/SCsub index 62a8660ae4..fa9e6eed15 100644 --- a/platform/javascript/SCsub +++ b/platform/javascript/SCsub @@ -20,6 +20,7 @@ sys_env.AddJSLibraries( "js/libs/library_godot_fetch.js", "js/libs/library_godot_os.js", "js/libs/library_godot_runtime.js", + "js/libs/library_godot_input.js", ] ) diff --git a/platform/javascript/api/javascript_tools_editor_plugin.cpp b/platform/javascript/api/javascript_tools_editor_plugin.cpp index 45a2cd595a..df4c790755 100644 --- a/platform/javascript/api/javascript_tools_editor_plugin.cpp +++ b/platform/javascript/api/javascript_tools_editor_plugin.cpp @@ -131,9 +131,10 @@ void JavaScriptToolsEditorPlugin::_zip_recursive(String p_path, String p_base_pa } dir->list_dir_begin(); String cur = dir->get_next(); + String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name(); while (!cur.is_empty()) { String cs = p_path.plus_file(cur); - if (cur == "." || cur == ".." || cur == ".import") { + if (cur == "." || cur == ".." || cur == project_data_dir_name) { // Skip } else if (dir->current_is_dir()) { String path = cs.replace_first(p_base_path, "") + "/"; diff --git a/platform/javascript/display_server_javascript.cpp b/platform/javascript/display_server_javascript.cpp index 124b4ee1c8..c2eb826db9 100644 --- a/platform/javascript/display_server_javascript.cpp +++ b/platform/javascript/display_server_javascript.cpp @@ -62,26 +62,13 @@ bool DisplayServerJavaScript::check_size_force_redraw() { return godot_js_display_size_update() != 0; } -Point2 DisplayServerJavaScript::compute_position_in_canvas(int p_x, int p_y) { - int point[2]; - godot_js_display_compute_position(p_x, p_y, point, point + 1); - return Point2(point[0], point[1]); -} - -EM_BOOL DisplayServerJavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) { +void DisplayServerJavaScript::fullscreen_change_callback(int p_fullscreen) { DisplayServerJavaScript *display = get_singleton(); - // Empty ID is canvas. - String target_id = String::utf8(p_event->id); - if (target_id.is_empty() || target_id == String::utf8(&(display->canvas_id[1]))) { - // This event property is the only reliable data on - // browser fullscreen state. - if (p_event->isFullscreen) { - display->window_mode = WINDOW_MODE_FULLSCREEN; - } else { - display->window_mode = WINDOW_MODE_WINDOWED; - } + if (p_fullscreen) { + display->window_mode = WINDOW_MODE_FULLSCREEN; + } else { + display->window_mode = WINDOW_MODE_WINDOWED; } - return false; } // Drag and drop callback. @@ -118,88 +105,51 @@ void DisplayServerJavaScript::request_quit_callback() { // Keys -template <typename T> -void DisplayServerJavaScript::dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) { - godot_event->set_shift_pressed(emscripten_event_ptr->shiftKey); - godot_event->set_alt_pressed(emscripten_event_ptr->altKey); - godot_event->set_ctrl_pressed(emscripten_event_ptr->ctrlKey); - godot_event->set_meta_pressed(emscripten_event_ptr->metaKey); +void DisplayServerJavaScript::dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod) { + ev->set_shift_pressed(p_mod & 1); + ev->set_alt_pressed(p_mod & 2); + ev->set_ctrl_pressed(p_mod & 4); + ev->set_meta_pressed(p_mod & 8); } -Ref<InputEventKey> DisplayServerJavaScript::setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) { +void DisplayServerJavaScript::key_callback(int p_pressed, int p_repeat, int p_modifiers) { + DisplayServerJavaScript *ds = get_singleton(); + JSKeyEvent &key_event = ds->key_event; + // Resume audio context after input in case autoplay was denied. + OS_JavaScript::get_singleton()->resume_audio(); + Ref<InputEventKey> ev; ev.instantiate(); - ev->set_echo(emscripten_event->repeat); - dom2godot_mod(emscripten_event, ev); - ev->set_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, false)); - ev->set_physical_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, true)); - - String unicode = String::utf8(emscripten_event->key); - // Check if empty or multi-character (e.g. `CapsLock`). - if (unicode.length() != 1) { - // Might be empty as well, but better than nonsense. - unicode = String::utf8(emscripten_event->charValue); - } + ev->set_echo(p_repeat); + ev->set_keycode(dom_code2godot_scancode(key_event.code, key_event.key, false)); + ev->set_physical_keycode(dom_code2godot_scancode(key_event.code, key_event.key, true)); + ev->set_pressed(p_pressed); + dom2godot_mod(ev, p_modifiers); + + String unicode = String::utf8(key_event.key); if (unicode.length() == 1) { ev->set_unicode(unicode[0]); } - - return ev; -} - -EM_BOOL DisplayServerJavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *display = get_singleton(); - Ref<InputEventKey> ev = setup_key_event(p_event); - ev->set_pressed(true); - if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_keycode())) { - // Defer to keypress event for legacy unicode retrieval. - display->deferred_key_event = ev; - // Do not suppress keypress event. - return false; - } Input::get_singleton()->parse_input_event(ev); // Make sure to flush all events so we can call restricted APIs inside the event. Input::get_singleton()->flush_buffered_events(); - - return true; -} - -EM_BOOL DisplayServerJavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *display = get_singleton(); - display->deferred_key_event->set_unicode(p_event->charCode); - Input::get_singleton()->parse_input_event(display->deferred_key_event); - - // Make sure to flush all events so we can call restricted APIs inside the event. - Input::get_singleton()->flush_buffered_events(); - - return true; -} - -EM_BOOL DisplayServerJavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - Ref<InputEventKey> ev = setup_key_event(p_event); - ev->set_pressed(false); - Input::get_singleton()->parse_input_event(ev); - - // Make sure to flush all events so we can call restricted APIs inside the event. - Input::get_singleton()->flush_buffered_events(); - - return ev->get_keycode() != KEY_UNKNOWN && ev->get_keycode() != (Key)0; } // Mouse -EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *display = get_singleton(); +int DisplayServerJavaScript::mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers) { + DisplayServerJavaScript *ds = get_singleton(); Ref<InputEventMouseButton> ev; ev.instantiate(); - ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN); - ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY)); + ev->set_pressed(p_pressed); + ev->set_position(Point2(p_x, p_y)); ev->set_global_position(ev->get_position()); - dom2godot_mod(p_event, ev); + ev->set_pressed(p_pressed); + dom2godot_mod(ev, p_modifiers); - switch (p_event->button) { + switch (p_button) { case DOM_BUTTON_LEFT: ev->set_button_index(MOUSE_BUTTON_LEFT); break; @@ -219,34 +169,30 @@ EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const E return false; } - if (ev->is_pressed()) { - double diff = emscripten_get_now() - display->last_click_ms; + if (p_pressed) { + uint64_t diff = (OS::get_singleton()->get_ticks_usec() / 1000) - ds->last_click_ms; - if (ev->get_button_index() == display->last_click_button_index) { - if (diff < 400 && Point2(display->last_click_pos).distance_to(ev->get_position()) < 5) { - display->last_click_ms = 0; - display->last_click_pos = Point2(-100, -100); - display->last_click_button_index = -1; + if (ev->get_button_index() == ds->last_click_button_index) { + if (diff < 400 && Point2(ds->last_click_pos).distance_to(ev->get_position()) < 5) { + ds->last_click_ms = 0; + ds->last_click_pos = Point2(-100, -100); + ds->last_click_button_index = -1; ev->set_double_click(true); } } else { - display->last_click_button_index = ev->get_button_index(); + ds->last_click_button_index = ev->get_button_index(); } if (!ev->is_double_click()) { - display->last_click_ms += diff; - display->last_click_pos = ev->get_position(); + ds->last_click_ms += diff; + ds->last_click_pos = ev->get_position(); } } - Input *input = Input::get_singleton(); - int mask = input->get_mouse_button_mask(); - MouseButton button_flag = MouseButton(1 << (ev->get_button_index() - 1)); + int mask = Input::get_singleton()->get_mouse_button_mask(); + int button_flag = 1 << (ev->get_button_index() - 1); if (ev->is_pressed()) { - // Since the event is consumed, focus manually. The containing iframe, - // if exists, may not have focus yet, so focus even if already focused. - focus_canvas(); mask |= button_flag; } else if (mask & button_flag) { mask &= ~button_flag; @@ -256,7 +202,9 @@ EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const E } ev->set_button_mask(mask); - input->parse_input_event(ev); + Input::get_singleton()->parse_input_event(ev); + // Resume audio context after input in case autoplay was denied. + OS_JavaScript::get_singleton()->resume_audio(); // Make sure to flush all events so we can call restricted APIs inside the event. Input::get_singleton()->flush_buffered_events(); @@ -266,31 +214,26 @@ EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const E return true; } -EM_BOOL DisplayServerJavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *ds = get_singleton(); - Input *input = Input::get_singleton(); - int input_mask = input->get_mouse_button_mask(); - Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY); +void DisplayServerJavaScript::mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers) { + int input_mask = Input::get_singleton()->get_mouse_button_mask(); // For motion outside the canvas, only read mouse movement if dragging // started inside the canvas; imitating desktop app behaviour. - if (!ds->cursor_inside_canvas && !input_mask) - return false; + if (!get_singleton()->cursor_inside_canvas && !input_mask) + return; Ref<InputEventMouseMotion> ev; ev.instantiate(); - dom2godot_mod(p_event, ev); + dom2godot_mod(ev, p_modifiers); ev->set_button_mask(input_mask); - ev->set_position(pos); + ev->set_position(Point2(p_x, p_y)); ev->set_global_position(ev->get_position()); - ev->set_relative(Vector2(p_event->movementX, p_event->movementY)); - input->set_mouse_position(ev->get_position()); - ev->set_speed(input->get_last_mouse_speed()); + ev->set_relative(Vector2(p_rel_x, p_rel_y)); + Input::get_singleton()->set_mouse_position(ev->get_position()); + ev->set_speed(Input::get_singleton()->get_last_mouse_speed()); - input->parse_input_event(ev); - // Don't suppress mouseover/-leave events. - return false; + Input::get_singleton()->parse_input_event(ev); } // Cursor @@ -430,17 +373,15 @@ void DisplayServerJavaScript::mouse_set_mode(MouseMode p_mode) { if (p_mode == MOUSE_MODE_VISIBLE) { godot_js_display_cursor_set_visible(1); - emscripten_exit_pointerlock(); + godot_js_display_cursor_lock_set(0); } else if (p_mode == MOUSE_MODE_HIDDEN) { godot_js_display_cursor_set_visible(0); - emscripten_exit_pointerlock(); + godot_js_display_cursor_lock_set(0); } else if (p_mode == MOUSE_MODE_CAPTURED) { godot_js_display_cursor_set_visible(1); - EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false); - ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback."); - ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback."); + godot_js_display_cursor_lock_set(1); } } @@ -449,18 +390,17 @@ DisplayServer::MouseMode DisplayServerJavaScript::mouse_get_mode() const { return MOUSE_MODE_HIDDEN; } - EmscriptenPointerlockChangeEvent ev; - emscripten_get_pointerlock_status(&ev); - return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE; + if (godot_js_display_cursor_is_locked()) { + return MOUSE_MODE_CAPTURED; + } + return MOUSE_MODE_VISIBLE; } // Wheel -EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) { - ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false); - DisplayServerJavaScript *ds = get_singleton(); - if (!is_canvas_focused()) { - if (ds->cursor_inside_canvas) { - focus_canvas(); +int DisplayServerJavaScript::mouse_wheel_callback(double p_delta_x, double p_delta_y) { + if (!godot_js_display_canvas_is_focused()) { + if (get_singleton()->cursor_inside_canvas) { + godot_js_display_canvas_focus(); } else { return false; } @@ -477,16 +417,17 @@ EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const Emscript ev->set_ctrl_pressed(input->is_key_pressed(KEY_CTRL)); ev->set_meta_pressed(input->is_key_pressed(KEY_META)); - if (p_event->deltaY < 0) + if (p_delta_y < 0) { ev->set_button_index(MOUSE_BUTTON_WHEEL_UP); - else if (p_event->deltaY > 0) + } else if (p_delta_y > 0) { ev->set_button_index(MOUSE_BUTTON_WHEEL_DOWN); - else if (p_event->deltaX > 0) + } else if (p_delta_x > 0) { ev->set_button_index(MOUSE_BUTTON_WHEEL_LEFT); - else if (p_event->deltaX < 0) + } else if (p_delta_x < 0) { ev->set_button_index(MOUSE_BUTTON_WHEEL_RIGHT); - else + } else { return false; + } // Different browsers give wildly different delta values, and we can't // interpret deltaMode, so use default value for wheel events' factor. @@ -494,7 +435,7 @@ EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const Emscript int button_flag = 1 << (ev->get_button_index() - 1); ev->set_pressed(true); - ev->set_button_mask(MouseButton(input->get_mouse_button_mask() | button_flag)); + ev->set_button_mask(input->get_mouse_button_mask() | button_flag); input->parse_input_event(ev); Ref<InputEventMouseButton> release = ev->duplicate(); @@ -506,52 +447,43 @@ EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const Emscript } // Touch -EM_BOOL DisplayServerJavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *display = get_singleton(); - Ref<InputEventScreenTouch> ev; - int lowest_id_index = -1; - for (int i = 0; i < p_event->numTouches; ++i) { - const EmscriptenTouchPoint &touch = p_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev.instantiate(); - ev->set_index(touch.identifier); - ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY)); - display->touches[i] = ev->get_position(); - ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART); +void DisplayServerJavaScript::touch_callback(int p_type, int p_count) { + DisplayServerJavaScript *ds = get_singleton(); - Input::get_singleton()->parse_input_event(ev); - } + const JSTouchEvent &touch_event = ds->touch_event; + for (int i = 0; i < p_count; i++) { + Point2 point(touch_event.coords[i * 2], touch_event.coords[i * 2 + 1]); + if (p_type == 2) { + // touchmove + Ref<InputEventScreenDrag> ev; + ev.instantiate(); + ev->set_index(touch_event.identifier[i]); + ev->set_position(point); + + Point2 &prev = ds->touches[i]; + ev->set_relative(ev->get_position() - prev); + prev = ev->get_position(); + + Input::get_singleton()->parse_input_event(ev); + } else { + // touchstart/touchend + Ref<InputEventScreenTouch> ev; - // Make sure to flush all events so we can call restricted APIs inside the event. - Input::get_singleton()->flush_buffered_events(); + // Resume audio context after input in case autoplay was denied. + OS_JavaScript::get_singleton()->resume_audio(); - // Resume audio context after input in case autoplay was denied. - return true; -} + ev.instantiate(); + ev->set_index(touch_event.identifier[i]); + ev->set_position(point); + ev->set_pressed(p_type == 0); + ds->touches[i] = point; -EM_BOOL DisplayServerJavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - DisplayServerJavaScript *display = get_singleton(); - Ref<InputEventScreenDrag> ev; - int lowest_id_index = -1; - for (int i = 0; i < p_event->numTouches; ++i) { - const EmscriptenTouchPoint &touch = p_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev.instantiate(); - ev->set_index(touch.identifier); - ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY)); - Point2 &prev = display->touches[i]; - ev->set_relative(ev->get_position() - prev); - prev = ev->get_position(); - - Input::get_singleton()->parse_input_event(ev); + Input::get_singleton()->parse_input_event(ev); + + // Make sure to flush all events so we can call restricted APIs inside the event. + Input::get_singleton()->flush_buffered_events(); + } } - return true; } bool DisplayServerJavaScript::screen_is_touchscreen(int p_screen) const { @@ -595,10 +527,8 @@ void DisplayServerJavaScript::virtual_keyboard_hide() { godot_js_display_vk_hide(); } -// Window blur callback -EM_BOOL DisplayServerJavaScript::blur_callback(int p_event_type, const EmscriptenFocusEvent *p_event, void *p_user_data) { +void DisplayServerJavaScript::window_blur_callback() { Input::get_singleton()->release_pressed_events(); - return false; } // Gamepad @@ -613,14 +543,14 @@ void DisplayServerJavaScript::gamepad_callback(int p_index, int p_connected, con void DisplayServerJavaScript::process_joypads() { Input *input = Input::get_singleton(); - int32_t pads = godot_js_display_gamepad_sample_count(); + int32_t pads = godot_js_input_gamepad_sample_count(); int32_t s_btns_num = 0; int32_t s_axes_num = 0; int32_t s_standard = 0; float s_btns[16]; float s_axes[10]; for (int idx = 0; idx < pads; idx++) { - int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard); + int err = godot_js_input_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard); if (err) { continue; } @@ -718,11 +648,6 @@ void DisplayServerJavaScript::set_icon(const Ref<Image> &p_icon) { } void DisplayServerJavaScript::_dispatch_input_event(const Ref<InputEvent> &p_event) { - OS_JavaScript *os = OS_JavaScript::get_singleton(); - - // Resume audio context after input in case autoplay was denied. - os->resume_audio(); - Callable cb = get_singleton()->input_event_callback; if (!cb.is_null()) { Variant ev = p_event; @@ -788,44 +713,24 @@ DisplayServerJavaScript::DisplayServerJavaScript(const String &p_rendering_drive video_driver_index = p_video_driver; #endif - EMSCRIPTEN_RESULT result; -#define EM_CHECK(ev) \ - if (result != EMSCRIPTEN_RESULT_SUCCESS) \ - ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result)); -#define SET_EM_CALLBACK(target, ev, cb) \ - result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \ - EM_CHECK(ev) -#define SET_EM_WINDOW_CALLBACK(ev, cb) \ - result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, nullptr, false, &cb); \ - EM_CHECK(ev) - // These callbacks from Emscripten's html5.h suffice to access most - // JavaScript APIs. - SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback) - SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback) - SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback) - SET_EM_WINDOW_CALLBACK(blur, blur_callback) - SET_EM_CALLBACK(canvas_id, wheel, wheel_callback) - SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback) - SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback) - SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback) - SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback) - SET_EM_CALLBACK(canvas_id, keydown, keydown_callback) - SET_EM_CALLBACK(canvas_id, keypress, keypress_callback) - SET_EM_CALLBACK(canvas_id, keyup, keyup_callback) - SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback) -#undef SET_EM_CALLBACK -#undef EM_CHECK - - // For APIs that are not (sufficiently) exposed, a - // library is used below (implemented in library_godot_display.js). + // JS Input interface (js/libs/library_godot_input.js) + godot_js_input_mouse_button_cb(&DisplayServerJavaScript::mouse_button_callback); + godot_js_input_mouse_move_cb(&DisplayServerJavaScript::mouse_move_callback); + godot_js_input_mouse_wheel_cb(&DisplayServerJavaScript::mouse_wheel_callback); + godot_js_input_touch_cb(&DisplayServerJavaScript::touch_callback, touch_event.identifier, touch_event.coords); + godot_js_input_key_cb(&DisplayServerJavaScript::key_callback, key_event.code, key_event.key); + godot_js_input_paste_cb(update_clipboard_callback); + godot_js_input_drop_files_cb(drop_files_js_callback); + godot_js_input_gamepad_cb(&DisplayServerJavaScript::gamepad_callback); + + // JS Display interface (js/libs/library_godot_display.js) + godot_js_display_fullscreen_cb(&DisplayServerJavaScript::fullscreen_change_callback); + godot_js_display_window_blur_cb(&window_blur_callback); godot_js_display_notification_cb(&send_window_event_callback, WINDOW_EVENT_MOUSE_ENTER, WINDOW_EVENT_MOUSE_EXIT, WINDOW_EVENT_FOCUS_IN, WINDOW_EVENT_FOCUS_OUT); - godot_js_display_paste_cb(update_clipboard_callback); - godot_js_display_drop_files_cb(drop_files_js_callback); - godot_js_display_gamepad_cb(&DisplayServerJavaScript::gamepad_callback); godot_js_display_vk_cb(&vk_input_text_callback); Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event); @@ -1048,7 +953,7 @@ bool DisplayServerJavaScript::can_any_window_draw() const { void DisplayServerJavaScript::process_events() { Input::get_singleton()->flush_buffered_events(); - if (godot_js_display_gamepad_sample() == OK) { + if (godot_js_input_gamepad_sample() == OK) { process_joypads(); } } diff --git a/platform/javascript/display_server_javascript.h b/platform/javascript/display_server_javascript.h index 1863ddefeb..1aa600c421 100644 --- a/platform/javascript/display_server_javascript.h +++ b/platform/javascript/display_server_javascript.h @@ -38,6 +38,19 @@ class DisplayServerJavaScript : public DisplayServer { private: + struct JSTouchEvent { + uint32_t identifier[32] = { 0 }; + double coords[64] = { 0 }; + }; + JSTouchEvent touch_event; + + struct JSKeyEvent { + char code[32] = { 0 }; + char key[32] = { 0 }; + uint8_t modifiers[4] = { 0 }; + }; + JSKeyEvent key_event; + WindowMode window_mode = WINDOW_MODE_WINDOWED; ObjectID window_attached_instance_id = {}; @@ -47,46 +60,31 @@ private: Callable drop_files_callback; String clipboard; - Ref<InputEventKey> deferred_key_event; Point2 touches[32]; char canvas_id[256] = { 0 }; bool cursor_inside_canvas = true; CursorShape cursor_shape = CURSOR_ARROW; Point2i last_click_pos = Point2(-100, -100); // TODO check this again. - double last_click_ms = 0; + uint64_t last_click_ms = 0; int last_click_button_index = -1; bool swap_cancel_ok = false; // utilities - static Point2 compute_position_in_canvas(int p_x, int p_y); static void focus_canvas(); static bool is_canvas_focused(); - template <typename T> - static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event); - static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event); + static void dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod); static const char *godot2dom_cursor(DisplayServer::CursorShape p_shape); // events - static EM_BOOL fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data); - - static EM_BOOL keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); - static EM_BOOL keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); - static EM_BOOL keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); - + static void fullscreen_change_callback(int p_fullscreen); + static int mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers); + static void mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers); + static int mouse_wheel_callback(double p_delta_x, double p_delta_y); + static void touch_callback(int p_type, int p_count); + static void key_callback(int p_pressed, int p_repeat, int p_modifiers); static void vk_input_text_callback(const char *p_text, int p_cursor); - - static EM_BOOL mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); - static EM_BOOL mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); - - static EM_BOOL wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data); - - static EM_BOOL touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); - static EM_BOOL touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); - - static EM_BOOL blur_callback(int p_event_type, const EmscriptenFocusEvent *p_event, void *p_user_data); - static void gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid); void process_joypads(); @@ -96,6 +94,7 @@ private: static void _dispatch_input_event(const Ref<InputEvent> &p_event); static void request_quit_callback(); + static void window_blur_callback(); static void update_clipboard_callback(const char *p_text); static void send_window_event_callback(int p_notification); static void drop_files_js_callback(char **p_filev, int p_filec); diff --git a/platform/javascript/godot_js.h b/platform/javascript/godot_js.h index d332af2c31..8051b270e6 100644 --- a/platform/javascript/godot_js.h +++ b/platform/javascript/godot_js.h @@ -50,12 +50,28 @@ extern int godot_js_os_execute(const char *p_json); extern void godot_js_os_shell_open(const char *p_uri); extern int godot_js_os_hw_concurrency_get(); +// Input +extern void godot_js_input_mouse_button_cb(int (*p_callback)(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers)); +extern void godot_js_input_mouse_move_cb(void (*p_callback)(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers)); +extern void godot_js_input_mouse_wheel_cb(int (*p_callback)(double p_delta_x, double p_delta_y)); +extern void godot_js_input_touch_cb(void (*p_callback)(int p_type, int p_count), uint32_t *r_identifiers, double *r_coords); +extern void godot_js_input_key_cb(void (*p_callback)(int p_type, int p_repeat, int p_modifiers), char r_code[32], char r_key[32]); + +// Input gamepad +extern void godot_js_input_gamepad_cb(void (*p_on_change)(int p_index, int p_connected, const char *p_id, const char *p_guid)); +extern int godot_js_input_gamepad_sample(); +extern int godot_js_input_gamepad_sample_count(); +extern int godot_js_input_gamepad_sample_get(int p_idx, float r_btns[16], int32_t *r_btns_num, float r_axes[10], int32_t *r_axes_num, int32_t *r_standard); +extern void godot_js_input_paste_cb(void (*p_callback)(const char *p_text)); +extern void godot_js_input_drop_files_cb(void (*p_callback)(char **p_filev, int p_filec)); + // Display extern int godot_js_display_screen_dpi_get(); extern double godot_js_display_pixel_ratio_get(); extern void godot_js_display_alert(const char *p_text); extern int godot_js_display_touchscreen_is_available(); extern int godot_js_display_is_swap_ok_cancel(); +extern void godot_js_display_setup_canvas(int p_width, int p_height, int p_fullscreen, int p_hidpi); // Display canvas extern void godot_js_display_canvas_focus(); @@ -68,7 +84,6 @@ extern void godot_js_display_window_size_get(int32_t *p_x, int32_t *p_y); extern void godot_js_display_screen_size_get(int32_t *p_x, int32_t *p_y); extern int godot_js_display_fullscreen_request(); extern int godot_js_display_fullscreen_exit(); -extern void godot_js_display_compute_position(int p_x, int p_y, int32_t *r_x, int32_t *r_y); extern void godot_js_display_window_title_set(const char *p_text); extern void godot_js_display_window_icon_set(const uint8_t *p_ptr, int p_len); extern int godot_js_display_has_webgl(int p_version); @@ -82,18 +97,13 @@ extern void godot_js_display_cursor_set_shape(const char *p_cursor); extern int godot_js_display_cursor_is_hidden(); extern void godot_js_display_cursor_set_custom_shape(const char *p_shape, const uint8_t *p_ptr, int p_len, int p_hotspot_x, int p_hotspot_y); extern void godot_js_display_cursor_set_visible(int p_visible); - -// Display gamepad -extern void godot_js_display_gamepad_cb(void (*p_on_change)(int p_index, int p_connected, const char *p_id, const char *p_guid)); -extern int godot_js_display_gamepad_sample(); -extern int godot_js_display_gamepad_sample_count(); -extern int godot_js_display_gamepad_sample_get(int p_idx, float r_btns[16], int32_t *r_btns_num, float r_axes[10], int32_t *r_axes_num, int32_t *r_standard); +extern void godot_js_display_cursor_lock_set(int p_lock); +extern int godot_js_display_cursor_is_locked(); // Display listeners +extern void godot_js_display_fullscreen_cb(void (*p_callback)(int p_fullscreen)); +extern void godot_js_display_window_blur_cb(void (*p_callback)()); extern void godot_js_display_notification_cb(void (*p_callback)(int p_notification), int p_enter, int p_exit, int p_in, int p_out); -extern void godot_js_display_paste_cb(void (*p_callback)(const char *p_text)); -extern void godot_js_display_drop_files_cb(void (*p_callback)(char **p_filev, int p_filec)); -extern void godot_js_display_setup_canvas(int p_width, int p_height, int p_fullscreen, int p_hidpi); // Display Virtual Keyboard extern int godot_js_display_vk_available(); diff --git a/platform/javascript/js/libs/library_godot_display.js b/platform/javascript/js/libs/library_godot_display.js index affae90370..2689f1c22c 100644 --- a/platform/javascript/js/libs/library_godot_display.js +++ b/platform/javascript/js/libs/library_godot_display.js @@ -28,224 +28,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -/* - * Display Server listeners. - * Keeps track of registered event listeners so it can remove them on shutdown. - */ -const GodotDisplayListeners = { - $GodotDisplayListeners__deps: ['$GodotOS'], - $GodotDisplayListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayListeners.clear(); resolve(); });', - $GodotDisplayListeners: { - handlers: [], - - has: function (target, event, method, capture) { - return GodotDisplayListeners.handlers.findIndex(function (e) { - return e.target === target && e.event === event && e.method === method && e.capture === capture; - }) !== -1; - }, - - add: function (target, event, method, capture) { - if (GodotDisplayListeners.has(target, event, method, capture)) { - return; - } - function Handler(p_target, p_event, p_method, p_capture) { - this.target = p_target; - this.event = p_event; - this.method = p_method; - this.capture = p_capture; - } - GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture)); - target.addEventListener(event, method, capture); - }, - - clear: function () { - GodotDisplayListeners.handlers.forEach(function (h) { - h.target.removeEventListener(h.event, h.method, h.capture); - }); - GodotDisplayListeners.handlers.length = 0; - }, - }, -}; -mergeInto(LibraryManager.library, GodotDisplayListeners); - -/* - * Drag and drop handler. - * This is pretty big, but basically detect dropped files on GodotConfig.canvas, - * process them one by one (recursively for directories), and copies them to - * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot - * event (that requires a string array of paths). - * - * NOTE: The temporary files are removed after the callback. This means that - * deferred callbacks won't be able to access the files. - */ -const GodotDisplayDragDrop = { - $GodotDisplayDragDrop__deps: ['$FS', '$GodotFS'], - $GodotDisplayDragDrop: { - promises: [], - pending_files: [], - - add_entry: function (entry) { - if (entry.isDirectory) { - GodotDisplayDragDrop.add_dir(entry); - } else if (entry.isFile) { - GodotDisplayDragDrop.add_file(entry); - } else { - GodotRuntime.error('Unrecognized entry...', entry); - } - }, - - add_dir: function (entry) { - GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) { - const reader = entry.createReader(); - reader.readEntries(function (entries) { - for (let i = 0; i < entries.length; i++) { - GodotDisplayDragDrop.add_entry(entries[i]); - } - resolve(); - }); - })); - }, - - add_file: function (entry) { - GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) { - entry.file(function (file) { - const reader = new FileReader(); - reader.onload = function () { - const f = { - 'path': file.relativePath || file.webkitRelativePath, - 'name': file.name, - 'type': file.type, - 'size': file.size, - 'data': reader.result, - }; - if (!f['path']) { - f['path'] = f['name']; - } - GodotDisplayDragDrop.pending_files.push(f); - resolve(); - }; - reader.onerror = function () { - GodotRuntime.print('Error reading file'); - reject(); - }; - reader.readAsArrayBuffer(file); - }, function (err) { - GodotRuntime.print('Error!'); - reject(); - }); - })); - }, - - process: function (resolve, reject) { - if (GodotDisplayDragDrop.promises.length === 0) { - resolve(); - return; - } - GodotDisplayDragDrop.promises.pop().then(function () { - setTimeout(function () { - GodotDisplayDragDrop.process(resolve, reject); - }, 0); - }); - }, - - _process_event: function (ev, callback) { - ev.preventDefault(); - if (ev.dataTransfer.items) { - // Use DataTransferItemList interface to access the file(s) - for (let i = 0; i < ev.dataTransfer.items.length; i++) { - const item = ev.dataTransfer.items[i]; - let entry = null; - if ('getAsEntry' in item) { - entry = item.getAsEntry(); - } else if ('webkitGetAsEntry' in item) { - entry = item.webkitGetAsEntry(); - } - if (entry) { - GodotDisplayDragDrop.add_entry(entry); - } - } - } else { - GodotRuntime.error('File upload not supported'); - } - new Promise(GodotDisplayDragDrop.process).then(function () { - const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`; - const drops = []; - const files = []; - FS.mkdir(DROP); - GodotDisplayDragDrop.pending_files.forEach((elem) => { - const path = elem['path']; - GodotFS.copy_to_fs(DROP + path, elem['data']); - let idx = path.indexOf('/'); - if (idx === -1) { - // Root file - drops.push(DROP + path); - } else { - // Subdir - const sub = path.substr(0, idx); - idx = sub.indexOf('/'); - if (idx < 0 && drops.indexOf(DROP + sub) === -1) { - drops.push(DROP + sub); - } - } - files.push(DROP + path); - }); - GodotDisplayDragDrop.promises = []; - GodotDisplayDragDrop.pending_files = []; - callback(drops); - if (GodotConfig.persistent_drops) { - // Delay removal at exit. - GodotOS.atexit(function (resolve, reject) { - GodotDisplayDragDrop.remove_drop(files, DROP); - resolve(); - }); - } else { - GodotDisplayDragDrop.remove_drop(files, DROP); - } - }); - }, - - remove_drop: function (files, drop_path) { - const dirs = [drop_path.substr(0, drop_path.length - 1)]; - // Remove temporary files - files.forEach(function (file) { - FS.unlink(file); - let dir = file.replace(drop_path, ''); - let idx = dir.lastIndexOf('/'); - while (idx > 0) { - dir = dir.substr(0, idx); - if (dirs.indexOf(drop_path + dir) === -1) { - dirs.push(drop_path + dir); - } - idx = dir.lastIndexOf('/'); - } - }); - // Remove dirs. - dirs.sort(function (a, b) { - const al = (a.match(/\//g) || []).length; - const bl = (b.match(/\//g) || []).length; - if (al > bl) { - return -1; - } else if (al < bl) { - return 1; - } - return 0; - }).forEach(function (dir) { - FS.rmdir(dir); - }); - }, - - handler: function (callback) { - return function (ev) { - GodotDisplayDragDrop._process_event(ev, callback); - }; - }, - }, -}; -mergeInto(LibraryManager.library, GodotDisplayDragDrop); - const GodotDisplayVK = { - $GodotDisplayVK__deps: ['$GodotRuntime', '$GodotConfig', '$GodotDisplayListeners'], + $GodotDisplayVK__deps: ['$GodotRuntime', '$GodotConfig', '$GodotEventListeners'], $GodotDisplayVK__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayVK.clear(); resolve(); });', $GodotDisplayVK: { textinput: null, @@ -271,12 +56,12 @@ const GodotDisplayVK = { elem.style.outline = 'none'; elem.readonly = true; elem.disabled = true; - GodotDisplayListeners.add(elem, 'input', function (evt) { + GodotEventListeners.add(elem, 'input', function (evt) { const c_str = GodotRuntime.allocString(elem.value); input_cb(c_str, elem.selectionEnd); GodotRuntime.free(c_str); }, false); - GodotDisplayListeners.add(elem, 'blur', function (evt) { + GodotEventListeners.add(elem, 'blur', function (evt) { elem.style.display = 'none'; elem.readonly = true; elem.disabled = true; @@ -376,136 +161,23 @@ const GodotDisplayCursor = { delete GodotDisplayCursor.cursors[key]; }); }, - }, -}; -mergeInto(LibraryManager.library, GodotDisplayCursor); - -/* - * Display Gamepad API helper. - */ -const GodotDisplayGamepads = { - $GodotDisplayGamepads__deps: ['$GodotRuntime', '$GodotDisplayListeners'], - $GodotDisplayGamepads: { - samples: [], - - get_pads: function () { - try { - // Will throw in iframe when permission is denied. - // Will throw/warn in the future for insecure contexts. - // See https://github.com/w3c/gamepad/pull/120 - const pads = navigator.getGamepads(); - if (pads) { - return pads; - } - return []; - } catch (e) { - return []; - } - }, - - get_samples: function () { - return GodotDisplayGamepads.samples; - }, - - get_sample: function (index) { - const samples = GodotDisplayGamepads.samples; - return index < samples.length ? samples[index] : null; - }, - - sample: function () { - const pads = GodotDisplayGamepads.get_pads(); - const samples = []; - for (let i = 0; i < pads.length; i++) { - const pad = pads[i]; - if (!pad) { - samples.push(null); - continue; - } - const s = { - standard: pad.mapping === 'standard', - buttons: [], - axes: [], - connected: pad.connected, - }; - for (let b = 0; b < pad.buttons.length; b++) { - s.buttons.push(pad.buttons[b].value); - } - for (let a = 0; a < pad.axes.length; a++) { - s.axes.push(pad.axes[a]); - } - samples.push(s); + lockPointer: function () { + const canvas = GodotConfig.canvas; + if (canvas.requestPointerLock) { + canvas.requestPointerLock(); } - GodotDisplayGamepads.samples = samples; }, - - init: function (onchange) { - GodotDisplayListeners.samples = []; - function add(pad) { - const guid = GodotDisplayGamepads.get_guid(pad); - const c_id = GodotRuntime.allocString(pad.id); - const c_guid = GodotRuntime.allocString(guid); - onchange(pad.index, 1, c_id, c_guid); - GodotRuntime.free(c_id); - GodotRuntime.free(c_guid); + releasePointer: function () { + if (document.exitPointerLock) { + document.exitPointerLock(); } - const pads = GodotDisplayGamepads.get_pads(); - for (let i = 0; i < pads.length; i++) { - // Might be reserved space. - if (pads[i]) { - add(pads[i]); - } - } - GodotDisplayListeners.add(window, 'gamepadconnected', function (evt) { - add(evt.gamepad); - }, false); - GodotDisplayListeners.add(window, 'gamepaddisconnected', function (evt) { - onchange(evt.gamepad.index, 0); - }, false); }, - - get_guid: function (pad) { - if (pad.mapping) { - return pad.mapping; - } - const ua = navigator.userAgent; - let os = 'Unknown'; - if (ua.indexOf('Android') >= 0) { - os = 'Android'; - } else if (ua.indexOf('Linux') >= 0) { - os = 'Linux'; - } else if (ua.indexOf('iPhone') >= 0) { - os = 'iOS'; - } else if (ua.indexOf('Macintosh') >= 0) { - // Updated iPads will fall into this category. - os = 'MacOSX'; - } else if (ua.indexOf('Windows') >= 0) { - os = 'Windows'; - } - - const id = pad.id; - // Chrom* style: NAME (Vendor: xxxx Product: xxxx) - const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i; - // Firefox/Safari style (safari may remove leading zeores) - const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i; - let vendor = ''; - let product = ''; - if (exp1.test(id)) { - const match = exp1.exec(id); - vendor = match[1].padStart(4, '0'); - product = match[2].padStart(4, '0'); - } else if (exp2.test(id)) { - const match = exp2.exec(id); - vendor = match[1].padStart(4, '0'); - product = match[2].padStart(4, '0'); - } - if (!vendor || !product) { - return `${os}Unknown`; - } - return os + vendor + product; + isPointerLocked: function () { + return document.pointerLockElement === GodotConfig.canvas; }, }, }; -mergeInto(LibraryManager.library, GodotDisplayGamepads); +mergeInto(LibraryManager.library, GodotDisplayCursor); const GodotDisplayScreen = { $GodotDisplayScreen__deps: ['$GodotConfig', '$GodotOS', '$GL', 'emscripten_webgl_get_current_context'], @@ -622,7 +294,7 @@ mergeInto(LibraryManager.library, GodotDisplayScreen); * Exposes all the functions needed by DisplayServer implementation. */ const GodotDisplay = { - $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotDisplayListeners', '$GodotDisplayDragDrop', '$GodotDisplayGamepads', '$GodotDisplayScreen', '$GodotDisplayVK'], + $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotEventListeners', '$GodotDisplayScreen', '$GodotDisplayVK'], $GodotDisplay: { window_icon: '', findDPI: function () { @@ -710,15 +382,6 @@ const GodotDisplay = { GodotRuntime.setHeapValue(p_height, GodotConfig.canvas.height, 'i32'); }, - godot_js_display_compute_position: function (x, y, r_x, r_y) { - const canvas = GodotConfig.canvas; - const rect = canvas.getBoundingClientRect(); - const rw = canvas.width / rect.width; - const rh = canvas.height / rect.height; - GodotRuntime.setHeapValue(r_x, (x - rect.x) * rw, 'i32'); - GodotRuntime.setHeapValue(r_y, (y - rect.y) * rh, 'i32'); - }, - godot_js_display_has_webgl__sig: 'ii', godot_js_display_has_webgl: function (p_version) { if (p_version !== 1 && p_version !== 2) { @@ -859,60 +522,64 @@ const GodotDisplay = { } }, + godot_js_display_cursor_lock_set__sig: 'vi', + godot_js_display_cursor_lock_set: function (p_lock) { + if (p_lock) { + GodotDisplayCursor.lockPointer(); + } else { + GodotDisplayCursor.releasePointer(); + } + }, + + godot_js_display_cursor_is_locked__sig: 'i', + godot_js_display_cursor_is_locked: function () { + return GodotDisplayCursor.isPointerLocked() ? 1 : 0; + }, + /* * Listeners */ - godot_js_display_notification_cb__sig: 'viiiii', - godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) { + godot_js_display_fullscreen_cb__sig: 'vi', + godot_js_display_fullscreen_cb: function (callback) { const canvas = GodotConfig.canvas; const func = GodotRuntime.get_func(callback); - const notif = [p_enter, p_exit, p_in, p_out]; - ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) { - GodotDisplayListeners.add(canvas, evt_name, function () { - func(notif[idx]); - }, true); - }); + function change_cb(evt) { + if (evt.target === canvas) { + func(GodotDisplayScreen.isFullscreen()); + } + } + GodotEventListeners.add(document, 'fullscreenchange', change_cb, false); + GodotEventListeners.add(document, 'mozfullscreenchange', change_cb, false); + GodotEventListeners.add(document, 'webkitfullscreenchange', change_cb, false); }, - godot_js_display_paste_cb__sig: 'vi', - godot_js_display_paste_cb: function (callback) { + godot_js_display_window_blur_cb__sig: 'vi', + godot_js_display_window_blur_cb: function (callback) { const func = GodotRuntime.get_func(callback); - GodotDisplayListeners.add(window, 'paste', function (evt) { - const text = evt.clipboardData.getData('text'); - const ptr = GodotRuntime.allocString(text); - func(ptr); - GodotRuntime.free(ptr); + GodotEventListeners.add(window, 'blur', function () { + func(); }, false); }, - godot_js_display_drop_files_cb__sig: 'vi', - godot_js_display_drop_files_cb: function (callback) { - const func = GodotRuntime.get_func(callback); - const dropFiles = function (files) { - const args = files || []; - if (!args.length) { - return; - } - const argc = args.length; - const argv = GodotRuntime.allocStringArray(args); - func(argv, argc); - GodotRuntime.freeStringArray(argv, argc); - }; + godot_js_display_notification_cb__sig: 'viiiii', + godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) { const canvas = GodotConfig.canvas; - GodotDisplayListeners.add(canvas, 'dragover', function (ev) { - // Prevent default behavior (which would try to open the file(s)) - ev.preventDefault(); - }, false); - GodotDisplayListeners.add(canvas, 'drop', GodotDisplayDragDrop.handler(dropFiles)); + const func = GodotRuntime.get_func(callback); + const notif = [p_enter, p_exit, p_in, p_out]; + ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) { + GodotEventListeners.add(canvas, evt_name, function () { + func(notif[idx]); + }, true); + }); }, godot_js_display_setup_canvas__sig: 'viiii', godot_js_display_setup_canvas: function (p_width, p_height, p_fullscreen, p_hidpi) { const canvas = GodotConfig.canvas; - GodotDisplayListeners.add(canvas, 'contextmenu', function (ev) { + GodotEventListeners.add(canvas, 'contextmenu', function (ev) { ev.preventDefault(); }, false); - GodotDisplayListeners.add(canvas, 'webglcontextlost', function (ev) { + GodotEventListeners.add(canvas, 'webglcontextlost', function (ev) { alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert ev.preventDefault(); }, false); @@ -965,49 +632,6 @@ const GodotDisplay = { GodotDisplayVK.init(input_cb); } }, - - /* - * Gamepads - */ - godot_js_display_gamepad_cb__sig: 'vi', - godot_js_display_gamepad_cb: function (change_cb) { - const onchange = GodotRuntime.get_func(change_cb); - GodotDisplayGamepads.init(onchange); - }, - - godot_js_display_gamepad_sample_count__sig: 'i', - godot_js_display_gamepad_sample_count: function () { - return GodotDisplayGamepads.get_samples().length; - }, - - godot_js_display_gamepad_sample__sig: 'i', - godot_js_display_gamepad_sample: function () { - GodotDisplayGamepads.sample(); - return 0; - }, - - godot_js_display_gamepad_sample_get__sig: 'iiiiiii', - godot_js_display_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) { - const sample = GodotDisplayGamepads.get_sample(p_index); - if (!sample || !sample.connected) { - return 1; - } - const btns = sample.buttons; - const btns_len = btns.length < 16 ? btns.length : 16; - for (let i = 0; i < btns_len; i++) { - GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float'); - } - GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32'); - const axes = sample.axes; - const axes_len = axes.length < 10 ? axes.length : 10; - for (let i = 0; i < axes_len; i++) { - GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float'); - } - GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32'); - const is_standard = sample.standard ? 1 : 0; - GodotRuntime.setHeapValue(r_standard, is_standard, 'i32'); - return 0; - }, }; autoAddDeps(GodotDisplay, '$GodotDisplay'); diff --git a/platform/javascript/js/libs/library_godot_input.js b/platform/javascript/js/libs/library_godot_input.js new file mode 100644 index 0000000000..587c320f35 --- /dev/null +++ b/platform/javascript/js/libs/library_godot_input.js @@ -0,0 +1,526 @@ +/*************************************************************************/ +/* library_godot_input.js */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +/* + * Gamepad API helper. + */ +const GodotInputGamepads = { + $GodotInputGamepads__deps: ['$GodotRuntime', '$GodotEventListeners'], + $GodotInputGamepads: { + samples: [], + + get_pads: function () { + try { + // Will throw in iframe when permission is denied. + // Will throw/warn in the future for insecure contexts. + // See https://github.com/w3c/gamepad/pull/120 + const pads = navigator.getGamepads(); + if (pads) { + return pads; + } + return []; + } catch (e) { + return []; + } + }, + + get_samples: function () { + return GodotInputGamepads.samples; + }, + + get_sample: function (index) { + const samples = GodotInputGamepads.samples; + return index < samples.length ? samples[index] : null; + }, + + sample: function () { + const pads = GodotInputGamepads.get_pads(); + const samples = []; + for (let i = 0; i < pads.length; i++) { + const pad = pads[i]; + if (!pad) { + samples.push(null); + continue; + } + const s = { + standard: pad.mapping === 'standard', + buttons: [], + axes: [], + connected: pad.connected, + }; + for (let b = 0; b < pad.buttons.length; b++) { + s.buttons.push(pad.buttons[b].value); + } + for (let a = 0; a < pad.axes.length; a++) { + s.axes.push(pad.axes[a]); + } + samples.push(s); + } + GodotInputGamepads.samples = samples; + }, + + init: function (onchange) { + GodotEventListeners.samples = []; + function add(pad) { + const guid = GodotInputGamepads.get_guid(pad); + const c_id = GodotRuntime.allocString(pad.id); + const c_guid = GodotRuntime.allocString(guid); + onchange(pad.index, 1, c_id, c_guid); + GodotRuntime.free(c_id); + GodotRuntime.free(c_guid); + } + const pads = GodotInputGamepads.get_pads(); + for (let i = 0; i < pads.length; i++) { + // Might be reserved space. + if (pads[i]) { + add(pads[i]); + } + } + GodotEventListeners.add(window, 'gamepadconnected', function (evt) { + add(evt.gamepad); + }, false); + GodotEventListeners.add(window, 'gamepaddisconnected', function (evt) { + onchange(evt.gamepad.index, 0); + }, false); + }, + + get_guid: function (pad) { + if (pad.mapping) { + return pad.mapping; + } + const ua = navigator.userAgent; + let os = 'Unknown'; + if (ua.indexOf('Android') >= 0) { + os = 'Android'; + } else if (ua.indexOf('Linux') >= 0) { + os = 'Linux'; + } else if (ua.indexOf('iPhone') >= 0) { + os = 'iOS'; + } else if (ua.indexOf('Macintosh') >= 0) { + // Updated iPads will fall into this category. + os = 'MacOSX'; + } else if (ua.indexOf('Windows') >= 0) { + os = 'Windows'; + } + + const id = pad.id; + // Chrom* style: NAME (Vendor: xxxx Product: xxxx) + const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i; + // Firefox/Safari style (safari may remove leading zeores) + const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i; + let vendor = ''; + let product = ''; + if (exp1.test(id)) { + const match = exp1.exec(id); + vendor = match[1].padStart(4, '0'); + product = match[2].padStart(4, '0'); + } else if (exp2.test(id)) { + const match = exp2.exec(id); + vendor = match[1].padStart(4, '0'); + product = match[2].padStart(4, '0'); + } + if (!vendor || !product) { + return `${os}Unknown`; + } + return os + vendor + product; + }, + }, +}; +mergeInto(LibraryManager.library, GodotInputGamepads); + +/* + * Drag and drop helper. + * This is pretty big, but basically detect dropped files on GodotConfig.canvas, + * process them one by one (recursively for directories), and copies them to + * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot + * event (that requires a string array of paths). + * + * NOTE: The temporary files are removed after the callback. This means that + * deferred callbacks won't be able to access the files. + */ +const GodotInputDragDrop = { + $GodotInputDragDrop__deps: ['$FS', '$GodotFS'], + $GodotInputDragDrop: { + promises: [], + pending_files: [], + + add_entry: function (entry) { + if (entry.isDirectory) { + GodotInputDragDrop.add_dir(entry); + } else if (entry.isFile) { + GodotInputDragDrop.add_file(entry); + } else { + GodotRuntime.error('Unrecognized entry...', entry); + } + }, + + add_dir: function (entry) { + GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) { + const reader = entry.createReader(); + reader.readEntries(function (entries) { + for (let i = 0; i < entries.length; i++) { + GodotInputDragDrop.add_entry(entries[i]); + } + resolve(); + }); + })); + }, + + add_file: function (entry) { + GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) { + entry.file(function (file) { + const reader = new FileReader(); + reader.onload = function () { + const f = { + 'path': file.relativePath || file.webkitRelativePath, + 'name': file.name, + 'type': file.type, + 'size': file.size, + 'data': reader.result, + }; + if (!f['path']) { + f['path'] = f['name']; + } + GodotInputDragDrop.pending_files.push(f); + resolve(); + }; + reader.onerror = function () { + GodotRuntime.print('Error reading file'); + reject(); + }; + reader.readAsArrayBuffer(file); + }, function (err) { + GodotRuntime.print('Error!'); + reject(); + }); + })); + }, + + process: function (resolve, reject) { + if (GodotInputDragDrop.promises.length === 0) { + resolve(); + return; + } + GodotInputDragDrop.promises.pop().then(function () { + setTimeout(function () { + GodotInputDragDrop.process(resolve, reject); + }, 0); + }); + }, + + _process_event: function (ev, callback) { + ev.preventDefault(); + if (ev.dataTransfer.items) { + // Use DataTransferItemList interface to access the file(s) + for (let i = 0; i < ev.dataTransfer.items.length; i++) { + const item = ev.dataTransfer.items[i]; + let entry = null; + if ('getAsEntry' in item) { + entry = item.getAsEntry(); + } else if ('webkitGetAsEntry' in item) { + entry = item.webkitGetAsEntry(); + } + if (entry) { + GodotInputDragDrop.add_entry(entry); + } + } + } else { + GodotRuntime.error('File upload not supported'); + } + new Promise(GodotInputDragDrop.process).then(function () { + const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`; + const drops = []; + const files = []; + FS.mkdir(DROP); + GodotInputDragDrop.pending_files.forEach((elem) => { + const path = elem['path']; + GodotFS.copy_to_fs(DROP + path, elem['data']); + let idx = path.indexOf('/'); + if (idx === -1) { + // Root file + drops.push(DROP + path); + } else { + // Subdir + const sub = path.substr(0, idx); + idx = sub.indexOf('/'); + if (idx < 0 && drops.indexOf(DROP + sub) === -1) { + drops.push(DROP + sub); + } + } + files.push(DROP + path); + }); + GodotInputDragDrop.promises = []; + GodotInputDragDrop.pending_files = []; + callback(drops); + if (GodotConfig.persistent_drops) { + // Delay removal at exit. + GodotOS.atexit(function (resolve, reject) { + GodotInputDragDrop.remove_drop(files, DROP); + resolve(); + }); + } else { + GodotInputDragDrop.remove_drop(files, DROP); + } + }); + }, + + remove_drop: function (files, drop_path) { + const dirs = [drop_path.substr(0, drop_path.length - 1)]; + // Remove temporary files + files.forEach(function (file) { + FS.unlink(file); + let dir = file.replace(drop_path, ''); + let idx = dir.lastIndexOf('/'); + while (idx > 0) { + dir = dir.substr(0, idx); + if (dirs.indexOf(drop_path + dir) === -1) { + dirs.push(drop_path + dir); + } + idx = dir.lastIndexOf('/'); + } + }); + // Remove dirs. + dirs.sort(function (a, b) { + const al = (a.match(/\//g) || []).length; + const bl = (b.match(/\//g) || []).length; + if (al > bl) { + return -1; + } else if (al < bl) { + return 1; + } + return 0; + }).forEach(function (dir) { + FS.rmdir(dir); + }); + }, + + handler: function (callback) { + return function (ev) { + GodotInputDragDrop._process_event(ev, callback); + }; + }, + }, +}; +mergeInto(LibraryManager.library, GodotInputDragDrop); + +/* + * Godot exposed input functions. + */ +const GodotInput = { + $GodotInput__deps: ['$GodotRuntime', '$GodotConfig', '$GodotEventListeners', '$GodotInputGamepads', '$GodotInputDragDrop'], + $GodotInput: { + getModifiers: function (evt) { + return (evt.shiftKey + 0) + ((evt.altKey + 0) << 1) + ((evt.ctrlKey + 0) << 2) + ((evt.metaKey + 0) << 3); + }, + computePosition: function (evt, rect) { + const canvas = GodotConfig.canvas; + const rw = canvas.width / rect.width; + const rh = canvas.height / rect.height; + const x = (evt.clientX - rect.x) * rw; + const y = (evt.clientY - rect.y) * rh; + return [x, y]; + }, + }, + + /* + * Mouse API + */ + godot_js_input_mouse_move_cb__sig: 'vi', + godot_js_input_mouse_move_cb: function (callback) { + const func = GodotRuntime.get_func(callback); + const canvas = GodotConfig.canvas; + function move_cb(evt) { + const rect = canvas.getBoundingClientRect(); + const pos = GodotInput.computePosition(evt, rect); + // Scale movement + const rw = canvas.width / rect.width; + const rh = canvas.height / rect.height; + const rel_pos_x = evt.movementX * rw; + const rel_pos_y = evt.movementY * rh; + const modifiers = GodotInput.getModifiers(evt); + func(pos[0], pos[1], rel_pos_x, rel_pos_y, modifiers); + } + GodotEventListeners.add(window, 'mousemove', move_cb, false); + }, + + godot_js_input_mouse_wheel_cb__sig: 'vi', + godot_js_input_mouse_wheel_cb: function (callback) { + const func = GodotRuntime.get_func(callback); + function wheel_cb(evt) { + if (func(evt['deltaX'] || 0, evt['deltaY'] || 0)) { + evt.preventDefault(); + } + } + GodotEventListeners.add(GodotConfig.canvas, 'wheel', wheel_cb, false); + }, + + godot_js_input_mouse_button_cb__sig: 'vi', + godot_js_input_mouse_button_cb: function (callback) { + const func = GodotRuntime.get_func(callback); + const canvas = GodotConfig.canvas; + function button_cb(p_pressed, evt) { + const rect = canvas.getBoundingClientRect(); + const pos = GodotInput.computePosition(evt, rect); + const modifiers = GodotInput.getModifiers(evt); + if (func(p_pressed, evt.button, pos[0], pos[1], modifiers)) { + evt.preventDefault(); + } + } + GodotEventListeners.add(canvas, 'mousedown', button_cb.bind(null, 1), false); + GodotEventListeners.add(window, 'mouseup', button_cb.bind(null, 0), false); + }, + + /* + * Touch API + */ + godot_js_input_touch_cb__sig: 'viii', + godot_js_input_touch_cb: function (callback, ids, coords) { + const func = GodotRuntime.get_func(callback); + const canvas = GodotConfig.canvas; + function touch_cb(type, evt) { + const rect = canvas.getBoundingClientRect(); + const touches = evt.changedTouches; + for (let i = 0; i < touches.length; i++) { + const touch = touches[i]; + const pos = GodotInput.computePosition(touch, rect); + GodotRuntime.setHeapValue(coords + (i * 2), pos[0], 'double'); + GodotRuntime.setHeapValue(coords + (i * 2 + 8), pos[1], 'double'); + GodotRuntime.setHeapValue(ids + i, touch.identifier, 'i32'); + } + func(type, touches.length); + if (evt.cancelable) { + evt.preventDefault(); + } + } + GodotEventListeners.add(canvas, 'touchstart', touch_cb.bind(null, 0), false); + GodotEventListeners.add(canvas, 'touchend', touch_cb.bind(null, 1), false); + GodotEventListeners.add(canvas, 'touchcancel', touch_cb.bind(null, 1), false); + GodotEventListeners.add(canvas, 'touchmove', touch_cb.bind(null, 2), false); + }, + + /* + * Key API + */ + godot_js_input_key_cb__sig: 'viii', + godot_js_input_key_cb: function (callback, code, key) { + const func = GodotRuntime.get_func(callback); + function key_cb(pressed, evt) { + const modifiers = GodotInput.getModifiers(evt); + GodotRuntime.stringToHeap(evt.code, code, 32); + GodotRuntime.stringToHeap(evt.key, key, 32); + func(pressed, evt.repeat, modifiers); + evt.preventDefault(); + } + GodotEventListeners.add(GodotConfig.canvas, 'keydown', key_cb.bind(null, 1), false); + GodotEventListeners.add(GodotConfig.canvas, 'keyup', key_cb.bind(null, 0), false); + }, + + /* + * Gamepad API + */ + godot_js_input_gamepad_cb__sig: 'vi', + godot_js_input_gamepad_cb: function (change_cb) { + const onchange = GodotRuntime.get_func(change_cb); + GodotInputGamepads.init(onchange); + }, + + godot_js_input_gamepad_sample_count__sig: 'i', + godot_js_input_gamepad_sample_count: function () { + return GodotInputGamepads.get_samples().length; + }, + + godot_js_input_gamepad_sample__sig: 'i', + godot_js_input_gamepad_sample: function () { + GodotInputGamepads.sample(); + return 0; + }, + + godot_js_input_gamepad_sample_get__sig: 'iiiiiii', + godot_js_input_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) { + const sample = GodotInputGamepads.get_sample(p_index); + if (!sample || !sample.connected) { + return 1; + } + const btns = sample.buttons; + const btns_len = btns.length < 16 ? btns.length : 16; + for (let i = 0; i < btns_len; i++) { + GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float'); + } + GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32'); + const axes = sample.axes; + const axes_len = axes.length < 10 ? axes.length : 10; + for (let i = 0; i < axes_len; i++) { + GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float'); + } + GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32'); + const is_standard = sample.standard ? 1 : 0; + GodotRuntime.setHeapValue(r_standard, is_standard, 'i32'); + return 0; + }, + + /* + * Drag/Drop API + */ + godot_js_input_drop_files_cb__sig: 'vi', + godot_js_input_drop_files_cb: function (callback) { + const func = GodotRuntime.get_func(callback); + const dropFiles = function (files) { + const args = files || []; + if (!args.length) { + return; + } + const argc = args.length; + const argv = GodotRuntime.allocStringArray(args); + func(argv, argc); + GodotRuntime.freeStringArray(argv, argc); + }; + const canvas = GodotConfig.canvas; + GodotEventListeners.add(canvas, 'dragover', function (ev) { + // Prevent default behavior (which would try to open the file(s)) + ev.preventDefault(); + }, false); + GodotEventListeners.add(canvas, 'drop', GodotInputDragDrop.handler(dropFiles)); + }, + + /* Paste API */ + godot_js_input_paste_cb__sig: 'vi', + godot_js_input_paste_cb: function (callback) { + const func = GodotRuntime.get_func(callback); + GodotEventListeners.add(window, 'paste', function (evt) { + const text = evt.clipboardData.getData('text'); + const ptr = GodotRuntime.allocString(text); + func(ptr); + GodotRuntime.free(ptr); + }, false); + }, +}; + +autoAddDeps(GodotInput, '$GodotInput'); +mergeInto(LibraryManager.library, GodotInput); diff --git a/platform/javascript/js/libs/library_godot_os.js b/platform/javascript/js/libs/library_godot_os.js index 99e7ee8b5f..c552e99415 100644 --- a/platform/javascript/js/libs/library_godot_os.js +++ b/platform/javascript/js/libs/library_godot_os.js @@ -328,3 +328,43 @@ const GodotOS = { autoAddDeps(GodotOS, '$GodotOS'); mergeInto(LibraryManager.library, GodotOS); + +/* + * Godot event listeners. + * Keeps track of registered event listeners so it can remove them on shutdown. + */ +const GodotEventListeners = { + $GodotEventListeners__deps: ['$GodotOS'], + $GodotEventListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotEventListeners.clear(); resolve(); });', + $GodotEventListeners: { + handlers: [], + + has: function (target, event, method, capture) { + return GodotEventListeners.handlers.findIndex(function (e) { + return e.target === target && e.event === event && e.method === method && e.capture === capture; + }) !== -1; + }, + + add: function (target, event, method, capture) { + if (GodotEventListeners.has(target, event, method, capture)) { + return; + } + function Handler(p_target, p_event, p_method, p_capture) { + this.target = p_target; + this.event = p_event; + this.method = p_method; + this.capture = p_capture; + } + GodotEventListeners.handlers.push(new Handler(target, event, method, capture)); + target.addEventListener(event, method, capture); + }, + + clear: function () { + GodotEventListeners.handlers.forEach(function (h) { + h.target.removeEventListener(h.event, h.method, h.capture); + }); + GodotEventListeners.handlers.length = 0; + }, + }, +}; +mergeInto(LibraryManager.library, GodotEventListeners); diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 6ac5b55156..daf3c14f3b 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -28,14 +28,12 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -// Must include Winsock before windows.h (included by os_uwp.h) -#include "drivers/unix/net_socket_posix.h" - #include "os_uwp.h" #include "core/config/project_settings.h" #include "core/io/marshalls.h" #include "drivers/unix/ip_unix.h" +#include "drivers/unix/net_socket_posix.h" #include "drivers/windows/dir_access_windows.h" #include "drivers/windows/file_access_windows.h" #include "drivers/windows/mutex_windows.h" diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index c9b2600c8e..7945f409a1 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -45,6 +45,7 @@ #include <fcntl.h> #include <io.h> #include <stdio.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> class OS_UWP : public OS { diff --git a/platform/windows/context_gl_windows.h b/platform/windows/context_gl_windows.h index c8e8a0891d..feff1d825b 100644 --- a/platform/windows/context_gl_windows.h +++ b/platform/windows/context_gl_windows.h @@ -38,6 +38,7 @@ #include "core/error/error_list.h" #include "core/os/os.h" +#define WIN32_LEAN_AND_MEAN #include <windows.h> typedef bool(APIENTRY *PFNWGLSWAPINTERVALEXTPROC)(int interval); diff --git a/platform/windows/crash_handler_windows.h b/platform/windows/crash_handler_windows.h index e1ec8e6787..5cdc6d3e05 100644 --- a/platform/windows/crash_handler_windows.h +++ b/platform/windows/crash_handler_windows.h @@ -31,6 +31,7 @@ #ifndef CRASH_HANDLER_WINDOWS_H #define CRASH_HANDLER_WINDOWS_H +#define WIN32_LEAN_AND_MEAN #include <windows.h> // Crash handler exception only enabled with MSVC diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 3100c0bd27..905c4142a8 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -38,7 +38,6 @@ #include <avrt.h> -#ifdef DEBUG_ENABLED static String format_error_message(DWORD id) { LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, @@ -50,7 +49,6 @@ static String format_error_message(DWORD id) { return msg; } -#endif // DEBUG_ENABLED bool DisplayServerWindows::has_feature(Feature p_feature) const { switch (p_feature) { @@ -1210,7 +1208,7 @@ void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) { IDC_CROSS, IDC_WAIT, IDC_APPSTARTING, - IDC_ARROW, + IDC_SIZEALL, IDC_ARROW, IDC_NO, IDC_SIZENS, diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 8b82288a40..6a90b28579 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -63,6 +63,7 @@ #include <fcntl.h> #include <io.h> #include <stdio.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <windowsx.h> diff --git a/platform/windows/key_mapping_windows.h b/platform/windows/key_mapping_windows.h index f260666a3e..d056e88f06 100644 --- a/platform/windows/key_mapping_windows.h +++ b/platform/windows/key_mapping_windows.h @@ -33,8 +33,8 @@ #include "core/os/keyboard.h" +#define WIN32_LEAN_AND_MEAN #include <windows.h> - #include <winuser.h> class KeyMappingWindows { diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index 78b7be8a30..c03b600f2e 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -28,15 +28,13 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -// Must include Winsock before windows.h (included by os_windows.h) -#include "drivers/unix/net_socket_posix.h" - #include "os_windows.h" #include "core/debugger/engine_debugger.h" #include "core/debugger/script_debugger.h" #include "core/io/marshalls.h" #include "core/version_generated.gen.h" +#include "drivers/unix/net_socket_posix.h" #include "drivers/windows/dir_access_windows.h" #include "drivers/windows/file_access_windows.h" #include "joypad_windows.h" @@ -75,7 +73,6 @@ __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; #define GetProcAddress (void *)GetProcAddress #endif -#ifdef DEBUG_ENABLED static String format_error_message(DWORD id) { LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, @@ -87,7 +84,6 @@ static String format_error_message(DWORD id) { return msg; } -#endif // DEBUG_ENABLED void RedirectIOToConsole() { int hConHandle; diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index c4a2eda8f4..d24afa91eb 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -57,7 +57,9 @@ #include <fcntl.h> #include <io.h> +#include <shellapi.h> #include <stdio.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <windowsx.h> diff --git a/platform/windows/vulkan_context_win.h b/platform/windows/vulkan_context_win.h index 39dd2641fd..61e66b8ae0 100644 --- a/platform/windows/vulkan_context_win.h +++ b/platform/windows/vulkan_context_win.h @@ -32,6 +32,8 @@ #define VULKAN_DEVICE_WIN_H #include "drivers/vulkan/vulkan_context.h" + +#define WIN32_LEAN_AND_MEAN #include <windows.h> class VulkanContextWindows : public VulkanContext { diff --git a/platform/windows/windows_terminal_logger.cpp b/platform/windows/windows_terminal_logger.cpp index 8cab7ca521..e54a61fdfd 100644 --- a/platform/windows/windows_terminal_logger.cpp +++ b/platform/windows/windows_terminal_logger.cpp @@ -33,6 +33,7 @@ #ifdef WINDOWS_ENABLED #include <stdio.h> +#define WIN32_LEAN_AND_MEAN #include <windows.h> void WindowsTerminalLogger::logv(const char *p_format, va_list p_list, bool p_err) { diff --git a/scene/2d/animated_sprite_2d.cpp b/scene/2d/animated_sprite_2d.cpp index 96a3134691..fad4784d51 100644 --- a/scene/2d/animated_sprite_2d.cpp +++ b/scene/2d/animated_sprite_2d.cpp @@ -94,7 +94,7 @@ Rect2 AnimatedSprite2D::_get_rect() const { Point2 ofs = offset; if (centered) { - ofs -= Size2(s) / 2; + ofs -= s / 2; } if (s == Size2(0, 0)) { @@ -228,8 +228,7 @@ void AnimatedSprite2D::_notification(int p_what) { RID ci = get_canvas_item(); - Size2i s; - s = texture->get_size(); + Size2 s = texture->get_size(); Point2 ofs = offset; if (centered) { ofs -= s / 2; diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index 5f56f86029..f493d97ceb 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -54,13 +54,14 @@ PhysicsBody2D::~PhysicsBody2D() { } } -Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_motion, bool p_test_only, real_t p_margin) { - PhysicsServer2D::MotionResult result; - +Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_linear_velocity, bool p_test_only, real_t p_margin) { // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky. double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time(); - if (move_and_collide(p_motion * delta, result, p_margin, p_test_only)) { + PhysicsServer2D::MotionParameters parameters(get_global_transform(), p_linear_velocity * delta, p_margin); + + PhysicsServer2D::MotionResult result; + if (move_and_collide(parameters, result, p_test_only)) { // Create a new instance when the cached reference is invalid or still in use in script. if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) { motion_cache.instantiate(); @@ -74,18 +75,18 @@ Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_motion, bool p_t return Ref<KinematicCollision2D>(); } -bool PhysicsBody2D::move_and_collide(const Vector2 &p_motion, PhysicsServer2D::MotionResult &r_result, real_t p_margin, bool p_test_only, bool p_cancel_sliding, bool p_collide_separation_ray, const Set<RID> &p_exclude) { +bool PhysicsBody2D::move_and_collide(const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult &r_result, bool p_test_only, bool p_cancel_sliding) { if (is_only_update_transform_changes_enabled()) { ERR_PRINT("Move functions do not work together with 'sync to physics' option. Please read the documentation."); } - Transform2D gt = get_global_transform(); - bool colliding = PhysicsServer2D::get_singleton()->body_test_motion(get_rid(), gt, p_motion, p_margin, &r_result, p_collide_separation_ray, p_exclude); + + bool colliding = PhysicsServer2D::get_singleton()->body_test_motion(get_rid(), p_parameters, &r_result); // Restore direction of motion to be along original motion, // in order to avoid sliding due to recovery, // but only if collision depth is low enough to avoid tunneling. if (p_cancel_sliding) { - real_t motion_length = p_motion.length(); + real_t motion_length = p_parameters.motion.length(); real_t precision = 0.001; if (colliding) { @@ -93,7 +94,7 @@ bool PhysicsBody2D::move_and_collide(const Vector2 &p_motion, PhysicsServer2D::M // so even in normal resting cases the depth can be a bit more than the margin. precision += motion_length * (r_result.collision_unsafe_fraction - r_result.collision_safe_fraction); - if (r_result.collision_depth > (real_t)p_margin + precision) { + if (r_result.collision_depth > p_parameters.margin + precision) { p_cancel_sliding = false; } } @@ -102,7 +103,7 @@ bool PhysicsBody2D::move_and_collide(const Vector2 &p_motion, PhysicsServer2D::M // When motion is null, recovery is the resulting motion. Vector2 motion_normal; if (motion_length > CMP_EPSILON) { - motion_normal = p_motion / motion_length; + motion_normal = p_parameters.motion / motion_length; } // Check depth of recovery. @@ -111,15 +112,16 @@ bool PhysicsBody2D::move_and_collide(const Vector2 &p_motion, PhysicsServer2D::M real_t recovery_length = recovery.length(); // Fixes cases where canceling slide causes the motion to go too deep into the ground, // because we're only taking rest information into account and not general recovery. - if (recovery_length < (real_t)p_margin + precision) { + if (recovery_length < p_parameters.margin + precision) { // Apply adjustment to motion. r_result.travel = motion_normal * projected_length; - r_result.remainder = p_motion - r_result.travel; + r_result.remainder = p_parameters.motion - r_result.travel; } } } if (!p_test_only) { + Transform2D gt = p_parameters.from; gt.elements[2] += r_result.travel; set_global_transform(gt); } @@ -127,7 +129,7 @@ bool PhysicsBody2D::move_and_collide(const Vector2 &p_motion, PhysicsServer2D::M return colliding; } -bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion, const Ref<KinematicCollision2D> &r_collision, real_t p_margin) { +bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_linear_velocity, const Ref<KinematicCollision2D> &r_collision, real_t p_margin) { ERR_FAIL_COND_V(!is_inside_tree(), false); PhysicsServer2D::MotionResult *r = nullptr; @@ -139,7 +141,9 @@ bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky. double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time(); - return PhysicsServer2D::get_singleton()->body_test_motion(get_rid(), p_from, p_motion * delta, p_margin, r); + PhysicsServer2D::MotionParameters parameters(p_from, p_linear_velocity * delta, p_margin); + + return PhysicsServer2D::get_singleton()->body_test_motion(get_rid(), parameters, r); } TypedArray<PhysicsBody2D> PhysicsBody2D::get_collision_exceptions() { @@ -1083,10 +1087,14 @@ bool CharacterBody2D::move_and_slide() { on_wall = false; if (!current_platform_velocity.is_equal_approx(Vector2())) { + PhysicsServer2D::MotionParameters parameters(get_global_transform(), current_platform_velocity * delta, margin); + parameters.exclude_bodies.insert(platform_rid); + if (platform_object_id.is_valid()) { + parameters.exclude_objects.insert(platform_object_id); + } + PhysicsServer2D::MotionResult floor_result; - Set<RID> exclude; - exclude.insert(platform_rid); - if (move_and_collide(current_platform_velocity * delta, floor_result, margin, false, false, false, exclude)) { + if (move_and_collide(parameters, floor_result, false, false)) { motion_results.push_back(floor_result); _set_collision_direction(floor_result); } @@ -1120,9 +1128,11 @@ void CharacterBody2D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo Vector2 prev_floor_normal = floor_normal; RID prev_platform_rid = platform_rid; + ObjectID prev_platform_object_id = platform_object_id; int prev_platform_layer = platform_layer; platform_rid = RID(); + platform_object_id = ObjectID(); floor_normal = Vector2(); platform_velocity = Vector2(); @@ -1138,11 +1148,13 @@ void CharacterBody2D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo Vector2 last_travel; for (int iteration = 0; iteration < max_slides; ++iteration) { - PhysicsServer2D::MotionResult result; + PhysicsServer2D::MotionParameters parameters(get_global_transform(), motion, margin); - Vector2 prev_position = get_global_transform().elements[2]; + Vector2 prev_position = parameters.from.elements[2]; + + PhysicsServer2D::MotionResult result; + bool collided = move_and_collide(parameters, result, false, !sliding_enabled); - bool collided = move_and_collide(motion, result, margin, false, !sliding_enabled); last_motion = result.travel; if (collided) { @@ -1192,6 +1204,7 @@ void CharacterBody2D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo } on_floor = true; platform_rid = prev_platform_rid; + platform_object_id = prev_platform_object_id; platform_layer = prev_platform_layer; platform_velocity = p_prev_platform_velocity; floor_normal = prev_floor_normal; @@ -1278,14 +1291,17 @@ void CharacterBody2D::_move_and_slide_free(double p_delta) { Vector2 motion = motion_velocity * p_delta; platform_rid = RID(); + platform_object_id = ObjectID(); floor_normal = Vector2(); platform_velocity = Vector2(); bool first_slide = true; for (int iteration = 0; iteration < max_slides; ++iteration) { + PhysicsServer2D::MotionParameters parameters(get_global_transform(), motion, margin); + PhysicsServer2D::MotionResult result; + bool collided = move_and_collide(parameters, result, false, false); - bool collided = move_and_collide(motion, result, margin, false, false); last_motion = result.travel; if (collided) { @@ -1327,10 +1343,11 @@ void CharacterBody2D::_snap_on_floor(bool was_on_floor, bool vel_dir_facing_up) // Snap by at least collision margin to keep floor state consistent. real_t length = MAX(floor_snap_length, margin); - Transform2D gt = get_global_transform(); + PhysicsServer2D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin); + parameters.collide_separation_ray = true; + PhysicsServer2D::MotionResult result; - if (move_and_collide(-up_direction * length, result, margin, true, false, true)) { - bool apply = true; + if (move_and_collide(parameters, result, true, false)) { if (result.get_angle(up_direction) <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) { on_floor = true; floor_normal = result.collision_normal; @@ -1345,13 +1362,9 @@ void CharacterBody2D::_snap_on_floor(bool was_on_floor, bool vel_dir_facing_up) result.travel = Vector2(); } } - } else { - apply = false; - } - if (apply) { - gt.elements[2] += result.travel; - set_global_transform(gt); + parameters.from.elements[2] += result.travel; + set_global_transform(parameters.from); } } } @@ -1364,8 +1377,11 @@ bool CharacterBody2D::_on_floor_if_snapped(bool was_on_floor, bool vel_dir_facin // Snap by at least collision margin to keep floor state consistent. real_t length = MAX(floor_snap_length, margin); + PhysicsServer2D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin); + parameters.collide_separation_ray = true; + PhysicsServer2D::MotionResult result; - if (move_and_collide(-up_direction * length, result, margin, true, false, true)) { + if (move_and_collide(parameters, result, true, false)) { if (result.get_angle(up_direction) <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) { return true; } @@ -1393,6 +1409,7 @@ void CharacterBody2D::_set_collision_direction(const PhysicsServer2D::MotionResu void CharacterBody2D::_set_platform_data(const PhysicsServer2D::MotionResult &p_result) { platform_rid = p_result.collider; + platform_object_id = p_result.collider_id; platform_velocity = p_result.collider_velocity; platform_layer = PhysicsServer2D::get_singleton()->body_get_collision_layer(platform_rid); } @@ -1611,6 +1628,7 @@ void CharacterBody2D::_notification(int p_what) { // Reset move_and_slide() data. on_floor = false; platform_rid = RID(); + platform_object_id = ObjectID(); on_ceiling = false; on_wall = false; motion_results.clear(); @@ -1806,16 +1824,4 @@ void KinematicCollision2D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicCollision2D::get_collider_shape); ClassDB::bind_method(D_METHOD("get_collider_shape_index"), &KinematicCollision2D::get_collider_shape_index); ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicCollision2D::get_collider_velocity); - - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "position"), "", "get_position"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "normal"), "", "get_normal"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "travel"), "", "get_travel"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "remainder"), "", "get_remainder"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "local_shape"), "", "get_local_shape"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_collider"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id"), "", "get_collider_id"); - ADD_PROPERTY(PropertyInfo(Variant::RID, "collider_rid"), "", "get_collider_rid"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider_shape"), "", "get_collider_shape"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape_index"), "", "get_collider_shape_index"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "collider_velocity"), "", "get_collider_velocity"); } diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h index 70cc5cd9bf..d1f52b33f2 100644 --- a/scene/2d/physics_body_2d.h +++ b/scene/2d/physics_body_2d.h @@ -47,11 +47,11 @@ protected: Ref<KinematicCollision2D> motion_cache; - Ref<KinematicCollision2D> _move(const Vector2 &p_motion, bool p_test_only = false, real_t p_margin = 0.08); + Ref<KinematicCollision2D> _move(const Vector2 &p_linear_velocity, bool p_test_only = false, real_t p_margin = 0.08); public: - bool move_and_collide(const Vector2 &p_motion, PhysicsServer2D::MotionResult &r_result, real_t p_margin, bool p_test_only = false, bool p_cancel_sliding = true, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()); - bool test_move(const Transform2D &p_from, const Vector2 &p_motion, const Ref<KinematicCollision2D> &r_collision = Ref<KinematicCollision2D>(), real_t p_margin = 0.08); + bool move_and_collide(const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult &r_result, bool p_test_only = false, bool p_cancel_sliding = true); + bool test_move(const Transform2D &p_from, const Vector2 &p_linear_velocity, const Ref<KinematicCollision2D> &r_collision = Ref<KinematicCollision2D>(), real_t p_margin = 0.08); TypedArray<PhysicsBody2D> get_collision_exceptions(); void add_collision_exception_with(Node *p_node); //must be physicsbody @@ -368,6 +368,7 @@ private: Vector2 real_velocity; RID platform_rid; + ObjectID platform_object_id; bool on_floor = false; bool on_ceiling = false; bool on_wall = false; diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp index 9aad338d15..61d73ff1e2 100644 --- a/scene/3d/camera_3d.cpp +++ b/scene/3d/camera_3d.cpp @@ -492,6 +492,7 @@ void Camera3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_frustum"), &Camera3D::get_frustum); ClassDB::bind_method(D_METHOD("is_position_in_frustum", "world_point"), &Camera3D::is_position_in_frustum); ClassDB::bind_method(D_METHOD("get_camera_rid"), &Camera3D::get_camera); + ClassDB::bind_method(D_METHOD("get_pyramid_shape_rid"), &Camera3D::get_pyramid_shape_rid); ClassDB::bind_method(D_METHOD("set_cull_mask_value", "layer_number", "value"), &Camera3D::set_cull_mask_value); ClassDB::bind_method(D_METHOD("get_cull_mask_value", "layer_number"), &Camera3D::get_cull_mask_value); @@ -654,233 +655,46 @@ Vector3 Camera3D::get_doppler_tracked_velocity() const { } } -Camera3D::Camera3D() { - camera = RenderingServer::get_singleton()->camera_create(); - set_perspective(75.0, 0.05, 4000.0); - RenderingServer::get_singleton()->camera_set_cull_mask(camera, layers); - //active=false; - velocity_tracker.instantiate(); - set_notify_transform(true); - set_disable_scale(true); -} - -Camera3D::~Camera3D() { - RenderingServer::get_singleton()->free(camera); -} +RID Camera3D::get_pyramid_shape_rid() { + if (pyramid_shape == RID()) { + pyramid_shape_points = get_near_plane_points(); + pyramid_shape = PhysicsServer3D::get_singleton()->convex_polygon_shape_create(); + PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, pyramid_shape_points); -//////////////////////////////////////// + } else { //check if points changed + Vector<Vector3> local_points = get_near_plane_points(); -void ClippedCamera3D::set_margin(real_t p_margin) { - margin = p_margin; -} - -real_t ClippedCamera3D::get_margin() const { - return margin; -} - -void ClippedCamera3D::set_process_callback(ClipProcessCallback p_mode) { - if (process_callback == p_mode) { - return; - } - process_callback = p_mode; - set_process_internal(process_callback == CLIP_PROCESS_IDLE); - set_physics_process_internal(process_callback == CLIP_PROCESS_PHYSICS); -} - -ClippedCamera3D::ClipProcessCallback ClippedCamera3D::get_process_callback() const { - return process_callback; -} - -Transform3D ClippedCamera3D::get_camera_transform() const { - Transform3D t = Camera3D::get_camera_transform(); - t.origin += -t.basis.get_axis(Vector3::AXIS_Z).normalized() * clip_offset; - return t; -} - -void ClippedCamera3D::_notification(int p_what) { - if (p_what == NOTIFICATION_INTERNAL_PROCESS || p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) { - Node3D *parent = Object::cast_to<Node3D>(get_parent()); - if (!parent) { - return; - } + bool all_equal = true; - PhysicsDirectSpaceState3D *dspace = get_world_3d()->get_direct_space_state(); - ERR_FAIL_COND(!dspace); // most likely physics set to threads - - Vector3 cam_fw = -get_global_transform().basis.get_axis(Vector3::AXIS_Z).normalized(); - Vector3 cam_pos = get_global_transform().origin; - Vector3 parent_pos = parent->get_global_transform().origin; - - Plane parent_plane(parent_pos, cam_fw); - - if (parent_plane.is_point_over(cam_pos)) { - //cam is beyond parent plane - return; - } - - Vector3 ray_from = parent_plane.project(cam_pos); - - clip_offset = 0; //reset by default - - { //check if points changed - Vector<Vector3> local_points = get_near_plane_points(); - - bool all_equal = true; - - for (int i = 0; i < 5; i++) { - if (points[i] != local_points[i]) { - all_equal = false; - break; - } - } - - if (!all_equal) { - PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, local_points); - points = local_points; + for (int i = 0; i < 5; i++) { + if (local_points[i] != pyramid_shape_points[i]) { + all_equal = false; + break; } } - Transform3D xf = get_global_transform(); - xf.origin = ray_from; - xf.orthonormalize(); - - real_t closest_safe = 1.0f, closest_unsafe = 1.0f; - if (dspace->cast_motion(pyramid_shape, xf, cam_pos - ray_from, margin, closest_safe, closest_unsafe, exclude, collision_mask, clip_to_bodies, clip_to_areas)) { - clip_offset = cam_pos.distance_to(ray_from + (cam_pos - ray_from) * closest_safe); + if (!all_equal) { + PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, local_points); + pyramid_shape_points = local_points; } - - _update_camera(); - } - - if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) { - update_gizmos(); } -} - -void ClippedCamera3D::set_collision_mask(uint32_t p_mask) { - collision_mask = p_mask; -} -uint32_t ClippedCamera3D::get_collision_mask() const { - return collision_mask; + return pyramid_shape; } -void ClippedCamera3D::set_collision_mask_value(int p_layer_number, bool p_value) { - ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive."); - ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive."); - uint32_t mask = get_collision_mask(); - if (p_value) { - mask |= 1 << (p_layer_number - 1); - } else { - mask &= ~(1 << (p_layer_number - 1)); - } - set_collision_mask(mask); -} - -bool ClippedCamera3D::get_collision_mask_value(int p_layer_number) const { - ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive."); - ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive."); - return get_collision_mask() & (1 << (p_layer_number - 1)); -} - -void ClippedCamera3D::add_exception_rid(const RID &p_rid) { - exclude.insert(p_rid); -} - -void ClippedCamera3D::add_exception(const Object *p_object) { - ERR_FAIL_NULL(p_object); - const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object); - if (!co) { - return; - } - add_exception_rid(co->get_rid()); -} - -void ClippedCamera3D::remove_exception_rid(const RID &p_rid) { - exclude.erase(p_rid); +Camera3D::Camera3D() { + camera = RenderingServer::get_singleton()->camera_create(); + set_perspective(75.0, 0.05, 4000.0); + RenderingServer::get_singleton()->camera_set_cull_mask(camera, layers); + //active=false; + velocity_tracker.instantiate(); + set_notify_transform(true); + set_disable_scale(true); } -void ClippedCamera3D::remove_exception(const Object *p_object) { - ERR_FAIL_NULL(p_object); - const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object); - if (!co) { - return; +Camera3D::~Camera3D() { + RenderingServer::get_singleton()->free(camera); + if (pyramid_shape.is_valid()) { + PhysicsServer3D::get_singleton()->free(pyramid_shape); } - remove_exception_rid(co->get_rid()); -} - -void ClippedCamera3D::clear_exceptions() { - exclude.clear(); -} - -real_t ClippedCamera3D::get_clip_offset() const { - return clip_offset; -} - -void ClippedCamera3D::set_clip_to_areas(bool p_clip) { - clip_to_areas = p_clip; -} - -bool ClippedCamera3D::is_clip_to_areas_enabled() const { - return clip_to_areas; -} - -void ClippedCamera3D::set_clip_to_bodies(bool p_clip) { - clip_to_bodies = p_clip; -} - -bool ClippedCamera3D::is_clip_to_bodies_enabled() const { - return clip_to_bodies; -} - -void ClippedCamera3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_margin", "margin"), &ClippedCamera3D::set_margin); - ClassDB::bind_method(D_METHOD("get_margin"), &ClippedCamera3D::get_margin); - - ClassDB::bind_method(D_METHOD("set_process_callback", "process_callback"), &ClippedCamera3D::set_process_callback); - ClassDB::bind_method(D_METHOD("get_process_callback"), &ClippedCamera3D::get_process_callback); - - ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &ClippedCamera3D::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"), &ClippedCamera3D::get_collision_mask); - - ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &ClippedCamera3D::set_collision_mask_value); - ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &ClippedCamera3D::get_collision_mask_value); - - ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &ClippedCamera3D::add_exception_rid); - ClassDB::bind_method(D_METHOD("add_exception", "node"), &ClippedCamera3D::add_exception); - - ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &ClippedCamera3D::remove_exception_rid); - ClassDB::bind_method(D_METHOD("remove_exception", "node"), &ClippedCamera3D::remove_exception); - - ClassDB::bind_method(D_METHOD("set_clip_to_areas", "enable"), &ClippedCamera3D::set_clip_to_areas); - ClassDB::bind_method(D_METHOD("is_clip_to_areas_enabled"), &ClippedCamera3D::is_clip_to_areas_enabled); - - ClassDB::bind_method(D_METHOD("get_clip_offset"), &ClippedCamera3D::get_clip_offset); - - ClassDB::bind_method(D_METHOD("set_clip_to_bodies", "enable"), &ClippedCamera3D::set_clip_to_bodies); - ClassDB::bind_method(D_METHOD("is_clip_to_bodies_enabled"), &ClippedCamera3D::is_clip_to_bodies_enabled); - - ClassDB::bind_method(D_METHOD("clear_exceptions"), &ClippedCamera3D::clear_exceptions); - - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin", PROPERTY_HINT_RANGE, "0,32,0.01"), "set_margin", "get_margin"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "process_callback", PROPERTY_HINT_ENUM, "Physics,Idle"), "set_process_callback", "get_process_callback"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask"); - - ADD_GROUP("Clip To", "clip_to"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_to_areas", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_clip_to_areas", "is_clip_to_areas_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_to_bodies", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_clip_to_bodies", "is_clip_to_bodies_enabled"); - - BIND_ENUM_CONSTANT(CLIP_PROCESS_PHYSICS); - BIND_ENUM_CONSTANT(CLIP_PROCESS_IDLE); -} - -ClippedCamera3D::ClippedCamera3D() { - set_physics_process_internal(true); - set_notify_local_transform(Engine::get_singleton()->is_editor_hint()); - points.resize(5); - pyramid_shape = PhysicsServer3D::get_singleton()->shape_create(PhysicsServer3D::SHAPE_CONVEX_POLYGON); -} - -ClippedCamera3D::~ClippedCamera3D() { - PhysicsServer3D::get_singleton()->free(pyramid_shape); } diff --git a/scene/3d/camera_3d.h b/scene/3d/camera_3d.h index c1af7fa4f7..6006a2ea3f 100644 --- a/scene/3d/camera_3d.h +++ b/scene/3d/camera_3d.h @@ -86,6 +86,9 @@ private: DopplerTracking doppler_tracking = DOPPLER_TRACKING_DISABLED; Ref<VelocityTracker3D> velocity_tracker; + RID pyramid_shape; + Vector<Vector3> pyramid_shape_points; + protected: void _update_camera(); virtual void _request_camera_update(); @@ -168,6 +171,8 @@ public: Vector3 get_doppler_tracked_velocity() const; + RID get_pyramid_shape_rid(); + Camera3D(); ~Camera3D(); }; @@ -176,63 +181,4 @@ VARIANT_ENUM_CAST(Camera3D::Projection); VARIANT_ENUM_CAST(Camera3D::KeepAspect); VARIANT_ENUM_CAST(Camera3D::DopplerTracking); -class ClippedCamera3D : public Camera3D { - GDCLASS(ClippedCamera3D, Camera3D); - -public: - enum ClipProcessCallback { - CLIP_PROCESS_PHYSICS, - CLIP_PROCESS_IDLE, - }; - -private: - ClipProcessCallback process_callback = CLIP_PROCESS_PHYSICS; - RID pyramid_shape; - real_t margin = 0.0; - real_t clip_offset = 0.0; - uint32_t collision_mask = 1; - bool clip_to_areas = false; - bool clip_to_bodies = true; - - Set<RID> exclude; - - Vector<Vector3> points; - -protected: - void _notification(int p_what); - static void _bind_methods(); - virtual Transform3D get_camera_transform() const override; - -public: - void set_clip_to_areas(bool p_clip); - bool is_clip_to_areas_enabled() const; - - void set_clip_to_bodies(bool p_clip); - bool is_clip_to_bodies_enabled() const; - - void set_margin(real_t p_margin); - real_t get_margin() const; - - void set_process_callback(ClipProcessCallback p_mode); - ClipProcessCallback get_process_callback() const; - - void set_collision_mask(uint32_t p_mask); - uint32_t get_collision_mask() const; - - void set_collision_mask_value(int p_layer_number, bool p_value); - bool get_collision_mask_value(int p_layer_number) const; - - void add_exception_rid(const RID &p_rid); - void add_exception(const Object *p_object); - void remove_exception_rid(const RID &p_rid); - void remove_exception(const Object *p_object); - void clear_exceptions(); - - real_t get_clip_offset() const; - - ClippedCamera3D(); - ~ClippedCamera3D(); -}; - -VARIANT_ENUM_CAST(ClippedCamera3D::ClipProcessCallback); #endif diff --git a/editor/import/scene_importer_mesh_node_3d.cpp b/scene/3d/importer_mesh_instance_3d.cpp index 3c201cf674..748a2e5092 100644 --- a/editor/import/scene_importer_mesh_node_3d.cpp +++ b/scene/3d/importer_mesh_instance_3d.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* scene_importer_mesh_node_3d.cpp */ +/* importer_mesh_instance_3d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,23 +28,25 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "scene_importer_mesh_node_3d.h" +#include "importer_mesh_instance_3d.h" -void EditorSceneImporterMeshNode3D::set_mesh(const Ref<EditorSceneImporterMesh> &p_mesh) { +#include "scene/resources/importer_mesh.h" + +void ImporterMeshInstance3D::set_mesh(const Ref<ImporterMesh> &p_mesh) { mesh = p_mesh; } -Ref<EditorSceneImporterMesh> EditorSceneImporterMeshNode3D::get_mesh() const { +Ref<ImporterMesh> ImporterMeshInstance3D::get_mesh() const { return mesh; } -void EditorSceneImporterMeshNode3D::set_skin(const Ref<Skin> &p_skin) { +void ImporterMeshInstance3D::set_skin(const Ref<Skin> &p_skin) { skin = p_skin; } -Ref<Skin> EditorSceneImporterMeshNode3D::get_skin() const { +Ref<Skin> ImporterMeshInstance3D::get_skin() const { return skin; } -void EditorSceneImporterMeshNode3D::set_surface_material(int p_idx, const Ref<Material> &p_material) { +void ImporterMeshInstance3D::set_surface_material(int p_idx, const Ref<Material> &p_material) { ERR_FAIL_COND(p_idx < 0); if (p_idx >= surface_materials.size()) { surface_materials.resize(p_idx + 1); @@ -52,7 +54,7 @@ void EditorSceneImporterMeshNode3D::set_surface_material(int p_idx, const Ref<Ma surface_materials.write[p_idx] = p_material; } -Ref<Material> EditorSceneImporterMeshNode3D::get_surface_material(int p_idx) const { +Ref<Material> ImporterMeshInstance3D::get_surface_material(int p_idx) const { ERR_FAIL_COND_V(p_idx < 0, Ref<Material>()); if (p_idx >= surface_materials.size()) { return Ref<Material>(); @@ -60,24 +62,24 @@ Ref<Material> EditorSceneImporterMeshNode3D::get_surface_material(int p_idx) con return surface_materials[p_idx]; } -void EditorSceneImporterMeshNode3D::set_skeleton_path(const NodePath &p_path) { +void ImporterMeshInstance3D::set_skeleton_path(const NodePath &p_path) { skeleton_path = p_path; } -NodePath EditorSceneImporterMeshNode3D::get_skeleton_path() const { +NodePath ImporterMeshInstance3D::get_skeleton_path() const { return skeleton_path; } -void EditorSceneImporterMeshNode3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &EditorSceneImporterMeshNode3D::set_mesh); - ClassDB::bind_method(D_METHOD("get_mesh"), &EditorSceneImporterMeshNode3D::get_mesh); +void ImporterMeshInstance3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &ImporterMeshInstance3D::set_mesh); + ClassDB::bind_method(D_METHOD("get_mesh"), &ImporterMeshInstance3D::get_mesh); - ClassDB::bind_method(D_METHOD("set_skin", "skin"), &EditorSceneImporterMeshNode3D::set_skin); - ClassDB::bind_method(D_METHOD("get_skin"), &EditorSceneImporterMeshNode3D::get_skin); + ClassDB::bind_method(D_METHOD("set_skin", "skin"), &ImporterMeshInstance3D::set_skin); + ClassDB::bind_method(D_METHOD("get_skin"), &ImporterMeshInstance3D::get_skin); - ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path"), &EditorSceneImporterMeshNode3D::set_skeleton_path); - ClassDB::bind_method(D_METHOD("get_skeleton_path"), &EditorSceneImporterMeshNode3D::get_skeleton_path); + ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path"), &ImporterMeshInstance3D::set_skeleton_path); + ClassDB::bind_method(D_METHOD("get_skeleton_path"), &ImporterMeshInstance3D::get_skeleton_path); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "EditorSceneImporterMesh"), "set_mesh", "get_mesh"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "ImporterMesh"), "set_mesh", "get_mesh"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "skin", PROPERTY_HINT_RESOURCE_TYPE, "Skin"), "set_skin", "get_skin"); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton"), "set_skeleton_path", "get_skeleton_path"); } diff --git a/editor/import/scene_importer_mesh_node_3d.h b/scene/3d/importer_mesh_instance_3d.h index dec1717c99..0cf7dbe86b 100644 --- a/editor/import/scene_importer_mesh_node_3d.h +++ b/scene/3d/importer_mesh_instance_3d.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* scene_importer_mesh_node_3d.h */ +/* importer_mesh_instance_3d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,19 +28,19 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef EDITOR_SCENE_IMPORTER_MESH_NODE_3D_H -#define EDITOR_SCENE_IMPORTER_MESH_NODE_3D_H +#ifndef SCENE_IMPORTER_MESH_INSTANCE_3D_H +#define SCENE_IMPORTER_MESH_INSTANCE_3D_H -#include "editor/import/scene_importer_mesh.h" #include "scene/3d/node_3d.h" +#include "scene/resources/immediate_mesh.h" #include "scene/resources/skin.h" -class EditorSceneImporterMesh; +class ImporterMesh; -class EditorSceneImporterMeshNode3D : public Node3D { - GDCLASS(EditorSceneImporterMeshNode3D, Node3D) +class ImporterMeshInstance3D : public Node3D { + GDCLASS(ImporterMeshInstance3D, Node3D) - Ref<EditorSceneImporterMesh> mesh; + Ref<ImporterMesh> mesh; Ref<Skin> skin; NodePath skeleton_path; Vector<Ref<Material>> surface_materials; @@ -49,8 +49,8 @@ protected: static void _bind_methods(); public: - void set_mesh(const Ref<EditorSceneImporterMesh> &p_mesh); - Ref<EditorSceneImporterMesh> get_mesh() const; + void set_mesh(const Ref<ImporterMesh> &p_mesh); + Ref<ImporterMesh> get_mesh() const; void set_skin(const Ref<Skin> &p_skin); Ref<Skin> get_skin() const; diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp index fc0df3650f..976bff4fbc 100644 --- a/scene/3d/physics_body_3d.cpp +++ b/scene/3d/physics_body_3d.cpp @@ -91,12 +91,15 @@ void PhysicsBody3D::remove_collision_exception_with(Node *p_node) { PhysicsServer3D::get_singleton()->body_remove_collision_exception(get_rid(), collision_object->get_rid()); } -Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_motion, bool p_test_only, real_t p_margin, int p_max_collisions) { - PhysicsServer3D::MotionResult result; +Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_linear_velocity, bool p_test_only, real_t p_margin, int p_max_collisions) { // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time(); - if (move_and_collide(p_motion * delta, result, p_margin, p_test_only, p_max_collisions)) { + PhysicsServer3D::MotionParameters parameters(get_global_transform(), p_linear_velocity * delta, p_margin); + parameters.max_collisions = p_max_collisions; + + PhysicsServer3D::MotionResult result; + if (move_and_collide(parameters, result, p_test_only)) { // Create a new instance when the cached reference is invalid or still in use in script. if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) { motion_cache.instantiate(); @@ -111,23 +114,22 @@ Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_motion, bool p_t return Ref<KinematicCollision3D>(); } -bool PhysicsBody3D::move_and_collide(const Vector3 &p_motion, PhysicsServer3D::MotionResult &r_result, real_t p_margin, bool p_test_only, int p_max_collisions, bool p_cancel_sliding, bool p_collide_separation_ray, const Set<RID> &p_exclude) { - Transform3D gt = get_global_transform(); - bool colliding = PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), gt, p_motion, p_margin, &r_result, p_max_collisions, p_collide_separation_ray, p_exclude); +bool PhysicsBody3D::move_and_collide(const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult &r_result, bool p_test_only, bool p_cancel_sliding) { + bool colliding = PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), p_parameters, &r_result); // Restore direction of motion to be along original motion, // in order to avoid sliding due to recovery, // but only if collision depth is low enough to avoid tunneling. if (p_cancel_sliding) { - real_t motion_length = p_motion.length(); + real_t motion_length = p_parameters.motion.length(); real_t precision = 0.001; if (colliding) { // Can't just use margin as a threshold because collision depth is calculated on unsafe motion, // so even in normal resting cases the depth can be a bit more than the margin. - precision += motion_length * (r_result.unsafe_fraction - r_result.safe_fraction); + precision += motion_length * (r_result.collision_unsafe_fraction - r_result.collision_safe_fraction); - if (r_result.collisions[0].depth > (real_t)p_margin + precision) { + if (r_result.collisions[0].depth > p_parameters.margin + precision) { p_cancel_sliding = false; } } @@ -136,7 +138,7 @@ bool PhysicsBody3D::move_and_collide(const Vector3 &p_motion, PhysicsServer3D::M // When motion is null, recovery is the resulting motion. Vector3 motion_normal; if (motion_length > CMP_EPSILON) { - motion_normal = p_motion / motion_length; + motion_normal = p_parameters.motion / motion_length; } // Check depth of recovery. @@ -145,10 +147,10 @@ bool PhysicsBody3D::move_and_collide(const Vector3 &p_motion, PhysicsServer3D::M real_t recovery_length = recovery.length(); // Fixes cases where canceling slide causes the motion to go too deep into the ground, // because we're only taking rest information into account and not general recovery. - if (recovery_length < (real_t)p_margin + precision) { + if (recovery_length < p_parameters.margin + precision) { // Apply adjustment to motion. r_result.travel = motion_normal * projected_length; - r_result.remainder = p_motion - r_result.travel; + r_result.remainder = p_parameters.motion - r_result.travel; } } } @@ -160,6 +162,7 @@ bool PhysicsBody3D::move_and_collide(const Vector3 &p_motion, PhysicsServer3D::M } if (!p_test_only) { + Transform3D gt = p_parameters.from; gt.origin += r_result.travel; set_global_transform(gt); } @@ -167,7 +170,7 @@ bool PhysicsBody3D::move_and_collide(const Vector3 &p_motion, PhysicsServer3D::M return colliding; } -bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_motion, const Ref<KinematicCollision3D> &r_collision, real_t p_margin, int p_max_collisions) { +bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_linear_velocity, const Ref<KinematicCollision3D> &r_collision, real_t p_margin, int p_max_collisions) { ERR_FAIL_COND_V(!is_inside_tree(), false); PhysicsServer3D::MotionResult *r = nullptr; @@ -179,7 +182,9 @@ bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_motion // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time(); - return PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), p_from, p_motion * delta, p_margin, r, p_max_collisions); + PhysicsServer3D::MotionParameters parameters(p_from, p_linear_velocity * delta, p_margin); + + return PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), parameters, r); } void PhysicsBody3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock) { @@ -1124,10 +1129,14 @@ bool CharacterBody3D::move_and_slide() { last_motion = Vector3(); if (!current_platform_velocity.is_equal_approx(Vector3())) { + PhysicsServer3D::MotionParameters parameters(get_global_transform(), current_platform_velocity * delta, margin); + parameters.exclude_bodies.insert(platform_rid); + if (platform_object_id.is_valid()) { + parameters.exclude_objects.insert(platform_object_id); + } + PhysicsServer3D::MotionResult floor_result; - Set<RID> exclude; - exclude.insert(platform_rid); - if (move_and_collide(current_platform_velocity * delta, floor_result, margin, false, 1, false, false, exclude)) { + if (move_and_collide(parameters, floor_result, false, false)) { motion_results.push_back(floor_result); CollisionState result_state; @@ -1163,6 +1172,7 @@ void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo Vector3 prev_floor_normal = floor_normal; platform_rid = RID(); + platform_object_id = ObjectID(); platform_velocity = Vector3(); platform_ceiling_velocity = Vector3(); floor_normal = Vector3(); @@ -1181,8 +1191,12 @@ void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo Vector3 total_travel; for (int iteration = 0; iteration < max_slides; ++iteration) { + PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin); + parameters.max_collisions = 4; + PhysicsServer3D::MotionResult result; - bool collided = move_and_collide(motion, result, margin, false, 4, !sliding_enabled); + bool collided = move_and_collide(parameters, result, false, !sliding_enabled); + last_motion = result.travel; if (collided) { @@ -1406,14 +1420,17 @@ void CharacterBody3D::_move_and_slide_free(double p_delta) { Vector3 motion = motion_velocity * p_delta; platform_rid = RID(); + platform_object_id = ObjectID(); floor_normal = Vector3(); platform_velocity = Vector3(); bool first_slide = true; for (int iteration = 0; iteration < max_slides; ++iteration) { + PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin); + PhysicsServer3D::MotionResult result; + bool collided = move_and_collide(parameters, result, false, false); - bool collided = move_and_collide(motion, result, margin, false, 1, false); last_motion = result.travel; if (collided) { @@ -1462,9 +1479,12 @@ void CharacterBody3D::_snap_on_floor(bool was_on_floor, bool vel_dir_facing_up) // Snap by at least collision margin to keep floor state consistent. real_t length = MAX(floor_snap_length, margin); - Transform3D gt = get_global_transform(); + PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin); + parameters.max_collisions = 4; + parameters.collide_separation_ray = true; + PhysicsServer3D::MotionResult result; - if (move_and_collide(-up_direction * length, result, margin, true, 4, false, true)) { + if (move_and_collide(parameters, result, true, false)) { CollisionState result_state; // Apply direction for floor only. _set_collision_direction(result, result_state, CollisionState(true, false, false)); @@ -1480,8 +1500,8 @@ void CharacterBody3D::_snap_on_floor(bool was_on_floor, bool vel_dir_facing_up) } } - gt.origin += result.travel; - set_global_transform(gt); + parameters.from.origin += result.travel; + set_global_transform(parameters.from); } } } @@ -1494,8 +1514,12 @@ bool CharacterBody3D::_on_floor_if_snapped(bool was_on_floor, bool vel_dir_facin // Snap by at least collision margin to keep floor state consistent. real_t length = MAX(floor_snap_length, margin); + PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin); + parameters.max_collisions = 4; + parameters.collide_separation_ray = true; + PhysicsServer3D::MotionResult result; - if (move_and_collide(-up_direction * length, result, margin, true, 4, false, true)) { + if (move_and_collide(parameters, result, true, false)) { CollisionState result_state; // Don't apply direction for any type. _set_collision_direction(result, result_state, CollisionState()); @@ -1592,6 +1616,7 @@ void CharacterBody3D::_set_collision_direction(const PhysicsServer3D::MotionResu void CharacterBody3D::_set_platform_data(const PhysicsServer3D::MotionCollision &p_collision) { platform_rid = p_collision.collider; + platform_object_id = p_collision.collider_id; platform_velocity = p_collision.collider_velocity; platform_layer = PhysicsServer3D::get_singleton()->body_get_collision_layer(platform_rid); } @@ -1814,6 +1839,7 @@ void CharacterBody3D::_notification(int p_what) { // Reset move_and_slide() data. collision_state.state = 0; platform_rid = RID(); + platform_object_id = ObjectID(); motion_results.clear(); platform_velocity = Vector3(); } break; @@ -2002,42 +2028,6 @@ Vector3 KinematicCollision3D::get_collider_velocity(int p_collision_index) const return result.collisions[p_collision_index].collider_velocity; } -Vector3 KinematicCollision3D::get_best_position() const { - return result.collision_count ? get_position() : Vector3(); -} - -Vector3 KinematicCollision3D::get_best_normal() const { - return result.collision_count ? get_normal() : Vector3(); -} - -Object *KinematicCollision3D::get_best_local_shape() const { - return result.collision_count ? get_local_shape() : nullptr; -} - -Object *KinematicCollision3D::get_best_collider() const { - return result.collision_count ? get_collider() : nullptr; -} - -ObjectID KinematicCollision3D::get_best_collider_id() const { - return result.collision_count ? get_collider_id() : ObjectID(); -} - -RID KinematicCollision3D::get_best_collider_rid() const { - return result.collision_count ? get_collider_rid() : RID(); -} - -Object *KinematicCollision3D::get_best_collider_shape() const { - return result.collision_count ? get_collider_shape() : nullptr; -} - -int KinematicCollision3D::get_best_collider_shape_index() const { - return result.collision_count ? get_collider_shape_index() : 0; -} - -Vector3 KinematicCollision3D::get_best_collider_velocity() const { - return result.collision_count ? get_collider_velocity() : Vector3(); -} - void KinematicCollision3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_travel"), &KinematicCollision3D::get_travel); ClassDB::bind_method(D_METHOD("get_remainder"), &KinematicCollision3D::get_remainder); @@ -2052,29 +2042,6 @@ void KinematicCollision3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_collider_shape", "collision_index"), &KinematicCollision3D::get_collider_shape, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collider_shape_index", "collision_index"), &KinematicCollision3D::get_collider_shape_index, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collider_velocity", "collision_index"), &KinematicCollision3D::get_collider_velocity, DEFVAL(0)); - - ClassDB::bind_method(D_METHOD("get_best_position"), &KinematicCollision3D::get_best_position); - ClassDB::bind_method(D_METHOD("get_best_normal"), &KinematicCollision3D::get_best_normal); - ClassDB::bind_method(D_METHOD("get_best_local_shape"), &KinematicCollision3D::get_best_local_shape); - ClassDB::bind_method(D_METHOD("get_best_collider"), &KinematicCollision3D::get_best_collider); - ClassDB::bind_method(D_METHOD("get_best_collider_id"), &KinematicCollision3D::get_best_collider_id); - ClassDB::bind_method(D_METHOD("get_best_collider_rid"), &KinematicCollision3D::get_best_collider_rid); - ClassDB::bind_method(D_METHOD("get_best_collider_shape"), &KinematicCollision3D::get_best_collider_shape); - ClassDB::bind_method(D_METHOD("get_best_collider_shape_index"), &KinematicCollision3D::get_best_collider_shape_index); - ClassDB::bind_method(D_METHOD("get_best_collider_velocity"), &KinematicCollision3D::get_best_collider_velocity); - - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "travel"), "", "get_travel"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "remainder"), "", "get_remainder"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_count"), "", "get_collision_count"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position"), "", "get_best_position"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "normal"), "", "get_best_normal"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "local_shape"), "", "get_best_local_shape"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_best_collider"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id"), "", "get_best_collider_id"); - ADD_PROPERTY(PropertyInfo(Variant::RID, "collider_rid"), "", "get_best_collider_rid"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider_shape"), "", "get_best_collider_shape"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape_index"), "", "get_best_collider_shape_index"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collider_velocity"), "", "get_best_collider_velocity"); } /////////////////////////////////////// diff --git a/scene/3d/physics_body_3d.h b/scene/3d/physics_body_3d.h index fdda681350..5677df730c 100644 --- a/scene/3d/physics_body_3d.h +++ b/scene/3d/physics_body_3d.h @@ -50,11 +50,11 @@ protected: uint16_t locked_axis = 0; - Ref<KinematicCollision3D> _move(const Vector3 &p_motion, bool p_test_only = false, real_t p_margin = 0.001, int p_max_collisions = 1); + Ref<KinematicCollision3D> _move(const Vector3 &p_linear_velocity, bool p_test_only = false, real_t p_margin = 0.001, int p_max_collisions = 1); public: - bool move_and_collide(const Vector3 &p_motion, PhysicsServer3D::MotionResult &r_result, real_t p_margin, bool p_test_only = false, int p_max_collisions = 1, bool p_cancel_sliding = true, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()); - bool test_move(const Transform3D &p_from, const Vector3 &p_motion, const Ref<KinematicCollision3D> &r_collision = Ref<KinematicCollision3D>(), real_t p_margin = 0.001, int p_max_collisions = 1); + bool move_and_collide(const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult &r_result, bool p_test_only = false, bool p_cancel_sliding = true); + bool test_move(const Transform3D &p_from, const Vector3 &p_linear_velocity, const Ref<KinematicCollision3D> &r_collision = Ref<KinematicCollision3D>(), real_t p_margin = 0.001, int p_max_collisions = 1); void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock); bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const; @@ -383,6 +383,7 @@ private: int max_slides = 6; int platform_layer = 0; RID platform_rid; + ObjectID platform_object_id; uint32_t moving_platform_floor_layers = UINT32_MAX; uint32_t moving_platform_wall_layers = 0; real_t floor_snap_length = 0.1; @@ -487,16 +488,6 @@ public: Object *get_collider_shape(int p_collision_index = 0) const; int get_collider_shape_index(int p_collision_index = 0) const; Vector3 get_collider_velocity(int p_collision_index = 0) const; - - Vector3 get_best_position() const; - Vector3 get_best_normal() const; - Object *get_best_local_shape() const; - Object *get_best_collider() const; - ObjectID get_best_collider_id() const; - RID get_best_collider_rid() const; - Object *get_best_collider_shape() const; - int get_best_collider_shape_index() const; - Vector3 get_best_collider_velocity() const; }; class PhysicalBone3D : public PhysicsBody3D { diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp index 8d90aabfac..2e788051f4 100644 --- a/scene/3d/skeleton_ik_3d.cpp +++ b/scene/3d/skeleton_ik_3d.cpp @@ -291,14 +291,10 @@ void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool ove new_bone_pose.origin = ci->current_pos; if (!ci->children.is_empty()) { - /// Rotate basis - const Vector3 initial_ori((ci->children[0].initial_transform.origin - ci->initial_transform.origin).normalized()); - const Vector3 rot_axis(initial_ori.cross(ci->current_ori).normalized()); - - if (rot_axis[0] != 0 && rot_axis[1] != 0 && rot_axis[2] != 0) { - const real_t rot_angle(Math::acos(CLAMP(initial_ori.dot(ci->current_ori), -1, 1))); - new_bone_pose.basis.rotate(rot_axis, rot_angle); - } + p_task->skeleton->update_bone_rest_forward_vector(ci->bone); + Vector3 forward_vector = p_task->skeleton->get_bone_axis_forward_vector(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)); } else { // Set target orientation to tip diff --git a/scene/3d/spring_arm_3d.cpp b/scene/3d/spring_arm_3d.cpp index 4748a9d889..116cab19b1 100644 --- a/scene/3d/spring_arm_3d.cpp +++ b/scene/3d/spring_arm_3d.cpp @@ -29,6 +29,7 @@ /*************************************************************************/ #include "spring_arm_3d.h" +#include "scene/3d/camera_3d.h" void SpringArm3D::_notification(int p_what) { switch (p_what) { @@ -133,17 +134,32 @@ void SpringArm3D::process_spring() { Vector3 motion; const Vector3 cast_direction(get_global_transform().basis.xform(Vector3(0, 0, 1))); + motion = Vector3(cast_direction * (spring_length)); + if (shape.is_null()) { - motion = Vector3(cast_direction * (spring_length)); - PhysicsDirectSpaceState3D::RayResult r; - bool intersected = get_world_3d()->get_direct_space_state()->intersect_ray(get_global_transform().origin, get_global_transform().origin + motion, r, excluded_objects, mask); - if (intersected) { - real_t dist = get_global_transform().origin.distance_to(r.position); - dist -= margin; - motion_delta = dist / (spring_length); + Camera3D *camera = nullptr; + for (int i = get_child_count() - 1; 0 <= i; --i) { + camera = Object::cast_to<Camera3D>(get_child(i)); + if (camera) { + break; + } + } + + if (camera != nullptr) { + //use camera rotation, but spring arm position + Transform3D base_transform = camera->get_global_transform(); + base_transform.origin = get_global_transform().origin; + get_world_3d()->get_direct_space_state()->cast_motion(camera->get_pyramid_shape_rid(), base_transform, motion, 0, motion_delta, motion_delta_unsafe, excluded_objects, mask); + } else { + PhysicsDirectSpaceState3D::RayResult r; + bool intersected = get_world_3d()->get_direct_space_state()->intersect_ray(get_global_transform().origin, get_global_transform().origin + motion, r, excluded_objects, mask); + if (intersected) { + real_t dist = get_global_transform().origin.distance_to(r.position); + dist -= margin; + motion_delta = dist / (spring_length); + } } } else { - motion = Vector3(cast_direction * spring_length); get_world_3d()->get_direct_space_state()->cast_motion(shape->get_rid(), get_global_transform(), motion, 0, motion_delta, motion_delta_unsafe, excluded_objects, mask); } diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp index b9a2736918..349a534680 100644 --- a/scene/3d/sprite_3d.cpp +++ b/scene/3d/sprite_3d.cpp @@ -712,7 +712,7 @@ Rect2 Sprite3D::get_item_rect() const { return CanvasItem::get_item_rect(); */ - Size2i s; + Size2 s; if (region) { s = region_rect.size; @@ -807,22 +807,20 @@ void AnimatedSprite3D::_draw() { set_base(RID()); return; //no texuture no life } - Vector2 tsize = texture->get_size(); + Size2 tsize = texture->get_size(); if (tsize.x == 0 || tsize.y == 0) { return; } - Size2i s = tsize; Rect2 src_rect; - - src_rect.size = s; + src_rect.size = tsize; Point2 ofs = get_offset(); if (is_centered()) { - ofs -= s / 2; + ofs -= tsize / 2; } - Rect2 dst_rect(ofs, s); + Rect2 dst_rect(ofs, tsize); Rect2 final_rect; Rect2 final_src_rect; @@ -1133,7 +1131,7 @@ Rect2 AnimatedSprite3D::get_item_rect() const { if (t.is_null()) { return Rect2(0, 0, 1, 1); } - Size2i s = t->get_size(); + Size2 s = t->get_size(); Point2 ofs = get_offset(); if (centered) { diff --git a/scene/animation/animation_node_state_machine.cpp b/scene/animation/animation_node_state_machine.cpp index 984be04285..81ecb50ea0 100644 --- a/scene/animation/animation_node_state_machine.cpp +++ b/scene/animation/animation_node_state_machine.cpp @@ -329,11 +329,17 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s } } else { // teleport to start - path.clear(); - current = start_request; - playing = true; - play_start = true; - start_request = StringName(); //clear start request + if (p_state_machine->states.has(start_request)) { + path.clear(); + current = start_request; + playing = true; + play_start = true; + start_request = StringName(); //clear start request + } else { + StringName node = start_request; + start_request = StringName(); //clear start request + ERR_FAIL_V_MSG(0, "No such node: '" + node + "'"); + } } } diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index a8d46eac6e..2c8c4ee788 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -37,7 +37,6 @@ #ifdef TOOLS_ENABLED #include "editor/editor_node.h" -#include "editor/editor_settings.h" #include "scene/2d/skeleton_2d.h" void AnimatedValuesBackup::update_skeletons() { @@ -1493,18 +1492,12 @@ NodePath AnimationPlayer::get_root() const { } void AnimationPlayer::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { -#ifdef TOOLS_ENABLED - const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\""; -#else - const String quote_style = "\""; -#endif - String pf = p_function; if (p_idx == 0 && (p_function == "play" || p_function == "play_backwards" || p_function == "remove_animation" || p_function == "has_animation" || p_function == "queue")) { List<StringName> al; get_animation_list(&al); for (const StringName &name : al) { - r_options->push_back(String(name).quote(quote_style)); + r_options->push_back(String(name).quote()); } } Node::get_argument_options(p_function, p_idx, r_options); diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp index b816f12bc3..da54903871 100644 --- a/scene/gui/code_edit.cpp +++ b/scene/gui/code_edit.cpp @@ -433,7 +433,7 @@ void CodeEdit::gui_input(const Ref<InputEvent> &p_gui_input) { return; } if (k->is_action("ui_end", true)) { - code_completion_current_selected = MIN(code_completion_options.size() - 1, code_completion_current_selected + code_completion_max_lines); + code_completion_current_selected = code_completion_options.size() - 1; update(); accept_event(); return; @@ -2937,6 +2937,7 @@ void CodeEdit::_lines_edited_from(int p_from_line, int p_to_line) { return; } + lines_edited_changed += p_to_line - p_from_line; lines_edited_from = (lines_edited_from == -1) ? MIN(p_from_line, p_to_line) : MIN(lines_edited_from, MIN(p_from_line, p_to_line)); lines_edited_to = (lines_edited_to == -1) ? MAX(p_from_line, p_to_line) : MAX(lines_edited_from, MAX(p_from_line, p_to_line)); } @@ -2963,7 +2964,6 @@ void CodeEdit::_text_changed() { } lc = get_line_count(); - int line_change_size = (lines_edited_to - lines_edited_from); List<int> breakpoints; breakpointed_lines.get_key_list(&breakpoints); for (const int &line : breakpoints) { @@ -2974,8 +2974,8 @@ void CodeEdit::_text_changed() { breakpointed_lines.erase(line); emit_signal(SNAME("breakpoint_toggled"), line); - int next_line = line + line_change_size; - if (next_line < lc && is_line_breakpointed(next_line)) { + int next_line = line + lines_edited_changed; + if (next_line > -1 && next_line < lc && is_line_breakpointed(next_line)) { emit_signal(SNAME("breakpoint_toggled"), next_line); breakpointed_lines[next_line] = true; continue; @@ -2984,6 +2984,7 @@ void CodeEdit::_text_changed() { lines_edited_from = -1; lines_edited_to = -1; + lines_edited_changed = 0; } CodeEdit::CodeEdit() { diff --git a/scene/gui/code_edit.h b/scene/gui/code_edit.h index d8eccb7d32..f0d971dd35 100644 --- a/scene/gui/code_edit.h +++ b/scene/gui/code_edit.h @@ -240,6 +240,7 @@ private: int line_spacing = 1; /* Callbacks */ + int lines_edited_changed = 0; int lines_edited_from = -1; int lines_edited_to = -1; diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp index 611035fff9..54548e1941 100644 --- a/scene/gui/color_picker.cpp +++ b/scene/gui/color_picker.cpp @@ -35,7 +35,6 @@ #include "core/os/os.h" #ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" #include "editor/editor_settings.h" #endif #include "scene/main/window.h" @@ -44,17 +43,7 @@ List<Color> ColorPicker::preset_cache; void ColorPicker::_notification(int p_what) { switch (p_what) { - case NOTIFICATION_THEME_CHANGED: { - btn_pick->set_icon(get_theme_icon(SNAME("screen_picker"), SNAME("ColorPicker"))); - btn_add_preset->set_icon(get_theme_icon(SNAME("add_preset"))); - _update_presets(); - _update_controls(); - } break; case NOTIFICATION_ENTER_TREE: { - btn_pick->set_icon(get_theme_icon(SNAME("screen_picker"), SNAME("ColorPicker"))); - btn_add_preset->set_icon(get_theme_icon(SNAME("add_preset"))); - - _update_controls(); _update_color(); #ifdef TOOLS_ENABLED @@ -71,18 +60,39 @@ void ColorPicker::_notification(int p_what) { } } #endif - } break; - case NOTIFICATION_PARENTED: { + [[fallthrough]]; + } + case NOTIFICATION_THEME_CHANGED: { + btn_pick->set_icon(get_theme_icon(SNAME("screen_picker"), SNAME("ColorPicker"))); + btn_add_preset->set_icon(get_theme_icon(SNAME("add_preset"))); + + uv_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("sv_width")), get_theme_constant(SNAME("sv_height")))); + w_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("h_width")), 0)); + + wheel_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("sv_width")), get_theme_constant(SNAME("sv_height")))); + wheel_margin->add_theme_constant_override("margin_bottom", 8 * get_theme_default_base_scale()); + for (int i = 0; i < 4; i++) { + labels[i]->set_custom_minimum_size(Size2(get_theme_constant(SNAME("label_width")), 0)); set_offset((Side)i, get_offset((Side)i) + get_theme_constant(SNAME("margin"))); } + + if (Engine::get_singleton()->is_editor_hint()) { + // Adjust for the width of the "Script" icon. + text_type->set_custom_minimum_size(Size2(28 * get_theme_default_base_scale(), 0)); + } + + _update_presets(); + _update_controls(); } break; + case NOTIFICATION_VISIBILITY_CHANGED: { Popup *p = Object::cast_to<Popup>(get_parent()); if (p) { p->set_size(Size2(get_combined_minimum_size().width + get_theme_constant(SNAME("margin")) * 2, get_combined_minimum_size().height + get_theme_constant(SNAME("margin")) * 2)); } } break; + case NOTIFICATION_WM_CLOSE_REQUEST: { if (screen != nullptr && screen->is_visible()) { screen->hide(); @@ -762,11 +772,7 @@ void ColorPicker::_slider_draw(int p_which) { Size2 size = scroll[p_which]->get_size(); Color left_color; Color right_color; -#ifdef TOOLS_ENABLED - const real_t margin = 4 * EDSCALE; -#else - const real_t margin = 4; -#endif + const real_t margin = 4 * get_theme_default_base_scale(); if (p_which == 3) { scroll[p_which]->draw_texture_rect(get_theme_icon(SNAME("sample_bg"), SNAME("ColorPicker")), Rect2(Point2(0, margin), Size2(size.x, margin)), true); @@ -1147,7 +1153,6 @@ ColorPicker::ColorPicker() : uv_edit->set_mouse_filter(MOUSE_FILTER_PASS); uv_edit->set_h_size_flags(SIZE_EXPAND_FILL); uv_edit->set_v_size_flags(SIZE_EXPAND_FILL); - uv_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("sv_width")), get_theme_constant(SNAME("sv_height")))); uv_edit->connect("draw", callable_mp(this, &ColorPicker::_hsv_draw), make_binds(0, uv_edit)); HBoxContainer *hb_smpl = memnew(HBoxContainer); @@ -1219,9 +1224,6 @@ ColorPicker::ColorPicker() : text_type->set_text("#"); text_type->set_tooltip(TTR("Switch between hexadecimal and code values.")); if (Engine::get_singleton()->is_editor_hint()) { -#ifdef TOOLS_ENABLED - text_type->set_custom_minimum_size(Size2(28 * EDSCALE, 0)); // Adjust for the width of the "Script" icon. -#endif text_type->connect("pressed", callable_mp(this, &ColorPicker::_text_type_toggled)); } else { text_type->set_flat(true); @@ -1236,7 +1238,6 @@ ColorPicker::ColorPicker() : wheel_edit->set_h_size_flags(SIZE_EXPAND_FILL); wheel_edit->set_v_size_flags(SIZE_EXPAND_FILL); - wheel_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("sv_width")), get_theme_constant(SNAME("sv_height")))); hb_edit->add_child(wheel_edit); wheel_mat.instantiate(); @@ -1244,12 +1245,7 @@ ColorPicker::ColorPicker() : circle_mat.instantiate(); circle_mat->set_shader(circle_shader); - MarginContainer *wheel_margin(memnew(MarginContainer)); -#ifdef TOOLS_ENABLED - wheel_margin->add_theme_constant_override("margin_bottom", 8 * EDSCALE); -#else wheel_margin->add_theme_constant_override("margin_bottom", 8); -#endif wheel_edit->add_child(wheel_margin); wheel_margin->add_child(wheel); @@ -1261,7 +1257,6 @@ ColorPicker::ColorPicker() : wheel_uv->connect("draw", callable_mp(this, &ColorPicker::_hsv_draw), make_binds(0, wheel_uv)); hb_edit->add_child(w_edit); - w_edit->set_custom_minimum_size(Size2(get_theme_constant(SNAME("h_width")), 0)); w_edit->set_h_size_flags(SIZE_FILL); w_edit->set_v_size_flags(SIZE_EXPAND_FILL); w_edit->connect("gui_input", callable_mp(this, &ColorPicker::_w_input)); diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h index 67ca007eb5..ad4f5ad5b1 100644 --- a/scene/gui/color_picker.h +++ b/scene/gui/color_picker.h @@ -81,6 +81,7 @@ private: Control *uv_edit = memnew(Control); Control *w_edit = memnew(Control); AspectRatioContainer *wheel_edit = memnew(AspectRatioContainer); + MarginContainer *wheel_margin = memnew(MarginContainer); Ref<ShaderMaterial> wheel_mat; Ref<ShaderMaterial> circle_mat; Control *wheel = memnew(Control); diff --git a/scene/gui/container.cpp b/scene/gui/container.cpp index 11941529cd..a1bd82f6f7 100644 --- a/scene/gui/container.cpp +++ b/scene/gui/container.cpp @@ -87,6 +87,9 @@ void Container::_sort_children() { return; } + notification(NOTIFICATION_PRE_SORT_CHILDREN); + emit_signal(SceneStringNames::get_singleton()->pre_sort_children); + notification(NOTIFICATION_SORT_CHILDREN); emit_signal(SceneStringNames::get_singleton()->sort_children); pending_sort = false; @@ -174,7 +177,10 @@ void Container::_bind_methods() { ClassDB::bind_method(D_METHOD("queue_sort"), &Container::queue_sort); ClassDB::bind_method(D_METHOD("fit_child_in_rect", "child", "rect"), &Container::fit_child_in_rect); + BIND_CONSTANT(NOTIFICATION_PRE_SORT_CHILDREN); BIND_CONSTANT(NOTIFICATION_SORT_CHILDREN); + + ADD_SIGNAL(MethodInfo("pre_sort_children")); ADD_SIGNAL(MethodInfo("sort_children")); } diff --git a/scene/gui/container.h b/scene/gui/container.h index bce3085f0c..f3ae948556 100644 --- a/scene/gui/container.h +++ b/scene/gui/container.h @@ -51,7 +51,8 @@ protected: public: enum { - NOTIFICATION_SORT_CHILDREN = 50 + NOTIFICATION_PRE_SORT_CHILDREN = 50, + NOTIFICATION_SORT_CHILDREN = 51, }; void fit_child_in_rect(Control *p_child, const Rect2 &p_rect); diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp index 1b8b5e17ed..38da40a402 100644 --- a/scene/gui/control.cpp +++ b/scene/gui/control.cpp @@ -38,7 +38,6 @@ #include "core/os/os.h" #include "core/string/print_string.h" #include "core/string/translation.h" - #include "scene/gui/label.h" #include "scene/gui/panel.h" #include "scene/main/canvas_layer.h" @@ -48,7 +47,6 @@ #include "servers/text_server.h" #ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" #include "editor/plugins/canvas_item_editor_plugin.h" #endif @@ -833,11 +831,12 @@ T Control::get_theme_item_in_types(Control *p_theme_owner, Window *p_theme_owner ERR_FAIL_COND_V_MSG(p_theme_types.size() == 0, T(), "At least one theme type must be specified."); // First, look through each control or window node in the branch, until no valid parent can be found. - // For each control iterate through its inheritance chain and see if p_name exists in any of them. + // Only nodes with a theme resource attached are considered. Control *theme_owner = p_theme_owner; Window *theme_owner_window = p_theme_owner_window; while (theme_owner || theme_owner_window) { + // For each theme resource check the theme types provided and see if p_name exists with any of them. for (const StringName &E : p_theme_types) { if (theme_owner && theme_owner->data.theme->has_theme_item(p_data_type, p_name, E)) { return theme_owner->data.theme->get_theme_item(p_data_type, p_name, E); @@ -888,11 +887,12 @@ bool Control::has_theme_item_in_types(Control *p_theme_owner, Window *p_theme_ow ERR_FAIL_COND_V_MSG(p_theme_types.size() == 0, false, "At least one theme type must be specified."); // First, look through each control or window node in the branch, until no valid parent can be found. - // For each control iterate through its inheritance chain and see if p_name exists in any of them. + // Only nodes with a theme resource attached are considered. Control *theme_owner = p_theme_owner; Window *theme_owner_window = p_theme_owner_window; while (theme_owner || theme_owner_window) { + // For each theme resource check the theme types provided and see if p_name exists with any of them. for (const StringName &E : p_theme_types) { if (theme_owner && theme_owner->data.theme->has_theme_item(p_data_type, p_name, E)) { return true; @@ -1130,6 +1130,150 @@ bool Control::has_theme_constant(const StringName &p_name, const StringName &p_t return has_theme_item_in_types(data.theme_owner, data.theme_owner_window, Theme::DATA_TYPE_CONSTANT, p_name, theme_types); } +float Control::fetch_theme_default_base_scale(Control *p_theme_owner, Window *p_theme_owner_window) { + // First, look through each control or window node in the branch, until no valid parent can be found. + // Only nodes with a theme resource attached are considered. + // For each theme resource see if their assigned theme has the default value defined and valid. + Control *theme_owner = p_theme_owner; + Window *theme_owner_window = p_theme_owner_window; + + while (theme_owner || theme_owner_window) { + if (theme_owner && theme_owner->data.theme->has_default_theme_base_scale()) { + return theme_owner->data.theme->get_default_theme_base_scale(); + } + + if (theme_owner_window && theme_owner_window->theme->has_default_theme_base_scale()) { + return theme_owner_window->theme->get_default_theme_base_scale(); + } + + Node *parent = theme_owner ? theme_owner->get_parent() : theme_owner_window->get_parent(); + Control *parent_c = Object::cast_to<Control>(parent); + if (parent_c) { + theme_owner = parent_c->data.theme_owner; + theme_owner_window = parent_c->data.theme_owner_window; + } else { + Window *parent_w = Object::cast_to<Window>(parent); + if (parent_w) { + theme_owner = parent_w->theme_owner; + theme_owner_window = parent_w->theme_owner_window; + } else { + theme_owner = nullptr; + theme_owner_window = nullptr; + } + } + } + + // Secondly, check the project-defined Theme resource. + if (Theme::get_project_default().is_valid()) { + if (Theme::get_project_default()->has_default_theme_base_scale()) { + return Theme::get_project_default()->get_default_theme_base_scale(); + } + } + + // Lastly, fall back on the default Theme. + return Theme::get_default()->get_default_theme_base_scale(); +} + +float Control::get_theme_default_base_scale() const { + return fetch_theme_default_base_scale(data.theme_owner, data.theme_owner_window); +} + +Ref<Font> Control::fetch_theme_default_font(Control *p_theme_owner, Window *p_theme_owner_window) { + // First, look through each control or window node in the branch, until no valid parent can be found. + // Only nodes with a theme resource attached are considered. + // For each theme resource see if their assigned theme has the default value defined and valid. + Control *theme_owner = p_theme_owner; + Window *theme_owner_window = p_theme_owner_window; + + while (theme_owner || theme_owner_window) { + if (theme_owner && theme_owner->data.theme->has_default_theme_font()) { + return theme_owner->data.theme->get_default_theme_font(); + } + + if (theme_owner_window && theme_owner_window->theme->has_default_theme_font()) { + return theme_owner_window->theme->get_default_theme_font(); + } + + Node *parent = theme_owner ? theme_owner->get_parent() : theme_owner_window->get_parent(); + Control *parent_c = Object::cast_to<Control>(parent); + if (parent_c) { + theme_owner = parent_c->data.theme_owner; + theme_owner_window = parent_c->data.theme_owner_window; + } else { + Window *parent_w = Object::cast_to<Window>(parent); + if (parent_w) { + theme_owner = parent_w->theme_owner; + theme_owner_window = parent_w->theme_owner_window; + } else { + theme_owner = nullptr; + theme_owner_window = nullptr; + } + } + } + + // Secondly, check the project-defined Theme resource. + if (Theme::get_project_default().is_valid()) { + if (Theme::get_project_default()->has_default_theme_font()) { + return Theme::get_project_default()->get_default_theme_font(); + } + } + + // Lastly, fall back on the default Theme. + return Theme::get_default()->get_default_theme_font(); +} + +Ref<Font> Control::get_theme_default_font() const { + return fetch_theme_default_font(data.theme_owner, data.theme_owner_window); +} + +int Control::fetch_theme_default_font_size(Control *p_theme_owner, Window *p_theme_owner_window) { + // First, look through each control or window node in the branch, until no valid parent can be found. + // Only nodes with a theme resource attached are considered. + // For each theme resource see if their assigned theme has the default value defined and valid. + Control *theme_owner = p_theme_owner; + Window *theme_owner_window = p_theme_owner_window; + + while (theme_owner || theme_owner_window) { + if (theme_owner && theme_owner->data.theme->has_default_theme_font_size()) { + return theme_owner->data.theme->get_default_theme_font_size(); + } + + if (theme_owner_window && theme_owner_window->theme->has_default_theme_font_size()) { + return theme_owner_window->theme->get_default_theme_font_size(); + } + + Node *parent = theme_owner ? theme_owner->get_parent() : theme_owner_window->get_parent(); + Control *parent_c = Object::cast_to<Control>(parent); + if (parent_c) { + theme_owner = parent_c->data.theme_owner; + theme_owner_window = parent_c->data.theme_owner_window; + } else { + Window *parent_w = Object::cast_to<Window>(parent); + if (parent_w) { + theme_owner = parent_w->theme_owner; + theme_owner_window = parent_w->theme_owner_window; + } else { + theme_owner = nullptr; + theme_owner_window = nullptr; + } + } + } + + // Secondly, check the project-defined Theme resource. + if (Theme::get_project_default().is_valid()) { + if (Theme::get_project_default()->has_default_theme_font_size()) { + return Theme::get_project_default()->get_default_theme_font_size(); + } + } + + // Lastly, fall back on the default Theme. + return Theme::get_default()->get_default_theme_font_size(); +} + +int Control::get_theme_default_font_size() const { + return fetch_theme_default_font_size(data.theme_owner, data.theme_owner_window); +} + Rect2 Control::get_parent_anchorable_rect() const { if (!is_inside_tree()) { return Rect2(); @@ -2616,12 +2760,6 @@ bool Control::is_visibility_clip_disabled() const { } void Control::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { -#ifdef TOOLS_ENABLED - const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\""; -#else - const String quote_style = "\""; -#endif - Node::get_argument_options(p_function, p_idx, r_options); if (p_idx == 0) { @@ -2641,7 +2779,7 @@ void Control::get_argument_options(const StringName &p_function, int p_idx, List sn.sort_custom<StringName::AlphCompare>(); for (const StringName &name : sn) { - r_options->push_back(String(name).quote(quote_style)); + r_options->push_back(String(name).quote()); } } } @@ -2789,6 +2927,10 @@ void Control::_bind_methods() { ClassDB::bind_method(D_METHOD("has_theme_color", "name", "theme_type"), &Control::has_theme_color, DEFVAL("")); ClassDB::bind_method(D_METHOD("has_theme_constant", "name", "theme_type"), &Control::has_theme_constant, DEFVAL("")); + ClassDB::bind_method(D_METHOD("get_theme_default_base_scale"), &Control::get_theme_default_base_scale); + ClassDB::bind_method(D_METHOD("get_theme_default_font"), &Control::get_theme_default_font); + ClassDB::bind_method(D_METHOD("get_theme_default_font_size"), &Control::get_theme_default_font_size); + ClassDB::bind_method(D_METHOD("get_parent_control"), &Control::get_parent_control); ClassDB::bind_method(D_METHOD("set_h_grow_direction", "direction"), &Control::set_h_grow_direction); diff --git a/scene/gui/control.h b/scene/gui/control.h index 87ff3918cb..bdc06319ea 100644 --- a/scene/gui/control.h +++ b/scene/gui/control.h @@ -509,6 +509,14 @@ public: bool has_theme_color(const StringName &p_name, const StringName &p_theme_type = StringName()) const; bool has_theme_constant(const StringName &p_name, const StringName &p_theme_type = StringName()) const; + static float fetch_theme_default_base_scale(Control *p_theme_owner, Window *p_theme_owner_window); + static Ref<Font> fetch_theme_default_font(Control *p_theme_owner, Window *p_theme_owner_window); + static int fetch_theme_default_font_size(Control *p_theme_owner, Window *p_theme_owner_window); + + float get_theme_default_base_scale() const; + Ref<Font> get_theme_default_font() const; + int get_theme_default_font_size() const; + /* TOOLTIP */ void set_tooltip(const String &p_tooltip); diff --git a/scene/gui/dialogs.cpp b/scene/gui/dialogs.cpp index 5d98aaa698..71d2778cc3 100644 --- a/scene/gui/dialogs.cpp +++ b/scene/gui/dialogs.cpp @@ -37,7 +37,6 @@ #ifdef TOOLS_ENABLED #include "editor/editor_node.h" -#include "editor/editor_scale.h" #include "scene/main/window.h" // Only used to check for more modals when dimming the editor. #endif @@ -363,8 +362,7 @@ Button *ConfirmationDialog::get_cancel_button() { ConfirmationDialog::ConfirmationDialog() { set_title(TTRC("Please Confirm...")); -#ifdef TOOLS_ENABLED - set_min_size(Size2(200, 70) * EDSCALE); -#endif + set_min_size(Size2(200, 70)); + cancel = add_cancel_button(); } diff --git a/scene/gui/gradient_edit.cpp b/scene/gui/gradient_edit.cpp index 56b8a936e1..5d024d3be7 100644 --- a/scene/gui/gradient_edit.cpp +++ b/scene/gui/gradient_edit.cpp @@ -32,15 +32,6 @@ #include "core/os/keyboard.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" -#define SPACING (3 * EDSCALE) -#define POINT_WIDTH (8 * EDSCALE) -#else -#define SPACING 3 -#define POINT_WIDTH 8 -#endif - GradientEdit::GradientEdit() { set_focus_mode(FOCUS_ALL); @@ -53,12 +44,12 @@ GradientEdit::GradientEdit() { int GradientEdit::_get_point_from_pos(int x) { int result = -1; - int total_w = get_size().width - get_size().height - SPACING; + int total_w = get_size().width - get_size().height - draw_spacing; float min_distance = 1e20; for (int i = 0; i < points.size(); i++) { //Check if we clicked at point float distance = ABS(x - points[i].offset * total_w); - float min = (POINT_WIDTH / 2 * 1.7); //make it easier to grab + float min = (draw_point_width / 2 * 1.7); //make it easier to grab if (distance <= min && distance < min_distance) { result = i; min_distance = distance; @@ -129,7 +120,7 @@ void GradientEdit::gui_input(const Ref<InputEvent> &p_event) { grabbed = _get_point_from_pos(x); if (grabbed != -1) { - int total_w = get_size().width - get_size().height - SPACING; + int total_w = get_size().width - get_size().height - draw_spacing; Gradient::Point newPoint = points[grabbed]; newPoint.offset = CLAMP(x / float(total_w), 0, 1); @@ -151,10 +142,10 @@ void GradientEdit::gui_input(const Ref<InputEvent> &p_event) { if (mb.is_valid() && mb->get_button_index() == 1 && mb->is_pressed()) { update(); int x = mb->get_position().x; - int total_w = get_size().width - get_size().height - SPACING; + int total_w = get_size().width - get_size().height - draw_spacing; //Check if color selector was clicked. - if (x > total_w + SPACING) { + if (x > total_w + draw_spacing) { _show_color_picker(); return; } @@ -225,7 +216,7 @@ void GradientEdit::gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid() && grabbing) { - int total_w = get_size().width - get_size().height - SPACING; + int total_w = get_size().width - get_size().height - draw_spacing; int x = mm->get_position().x; @@ -297,6 +288,12 @@ void GradientEdit::_notification(int p_what) { picker->connect("color_changed", callable_mp(this, &GradientEdit::_color_changed)); } } + + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + draw_spacing = BASE_SPACING * get_theme_default_base_scale(); + draw_point_width = BASE_POINT_WIDTH * get_theme_default_base_scale(); + } + if (p_what == NOTIFICATION_DRAW) { int w = get_size().x; int h = get_size().y; @@ -305,7 +302,7 @@ void GradientEdit::_notification(int p_what) { return; //Safety check. We have division by 'h'. And in any case there is nothing to draw with such size } - int total_w = get_size().width - get_size().height - SPACING; + int total_w = get_size().width - get_size().height - draw_spacing; //Draw checker pattern for ramp draw_texture_rect(get_theme_icon(SNAME("GuiMiniCheckerboard"), SNAME("EditorIcons")), Rect2(0, 0, total_w, h), true); @@ -358,7 +355,7 @@ void GradientEdit::_notification(int p_what) { col.a = 0.9; draw_line(Vector2(points[i].offset * total_w, 0), Vector2(points[i].offset * total_w, h / 2), col); - Rect2 rect = Rect2(points[i].offset * total_w - POINT_WIDTH / 2, h / 2, POINT_WIDTH, h / 2); + Rect2 rect = Rect2(points[i].offset * total_w - draw_point_width / 2, h / 2, draw_point_width, h / 2); draw_rect(rect, points[i].color, true); draw_rect(rect, col, false); if (grabbed == i) { @@ -375,15 +372,15 @@ void GradientEdit::_notification(int p_what) { } //Draw "button" for color selector - draw_texture_rect(get_theme_icon(SNAME("GuiMiniCheckerboard"), SNAME("EditorIcons")), Rect2(total_w + SPACING, 0, h, h), true); + draw_texture_rect(get_theme_icon(SNAME("GuiMiniCheckerboard"), SNAME("EditorIcons")), Rect2(total_w + draw_spacing, 0, h, h), true); if (grabbed != -1) { //Draw with selection color - draw_rect(Rect2(total_w + SPACING, 0, h, h), points[grabbed].color); + draw_rect(Rect2(total_w + draw_spacing, 0, h, h), points[grabbed].color); } else { //if no color selected draw grey color with 'X' on top. - draw_rect(Rect2(total_w + SPACING, 0, h, h), Color(0.5, 0.5, 0.5, 1)); - draw_line(Vector2(total_w + SPACING, 0), Vector2(total_w + SPACING + h, h), Color(1, 1, 1, 0.6)); - draw_line(Vector2(total_w + SPACING, h), Vector2(total_w + SPACING + h, 0), Color(1, 1, 1, 0.6)); + draw_rect(Rect2(total_w + draw_spacing, 0, h, h), Color(0.5, 0.5, 0.5, 1)); + draw_line(Vector2(total_w + draw_spacing, 0), Vector2(total_w + draw_spacing + h, h), Color(1, 1, 1, 0.6)); + draw_line(Vector2(total_w + draw_spacing, h), Vector2(total_w + draw_spacing + h, 0), Color(1, 1, 1, 0.6)); } //Draw borders around color ramp if in focus diff --git a/scene/gui/gradient_edit.h b/scene/gui/gradient_edit.h index a173631963..f3a39daaf6 100644 --- a/scene/gui/gradient_edit.h +++ b/scene/gui/gradient_edit.h @@ -46,6 +46,13 @@ class GradientEdit : public Control { int grabbed = -1; Vector<Gradient::Point> points; + // Make sure to use the scaled value below. + const int BASE_SPACING = 3; + const int BASE_POINT_WIDTH = 8; + + int draw_spacing = BASE_SPACING; + int draw_point_width = BASE_POINT_WIDTH; + void _draw_checker(int x, int y, int w, int h); void _color_changed(const Color &p_color); int _get_point_from_pos(int x); diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp index d9c08ec272..35e31be9af 100644 --- a/scene/gui/graph_edit.cpp +++ b/scene/gui/graph_edit.cpp @@ -36,10 +36,6 @@ #include "scene/gui/box_container.h" #include "scene/gui/button.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" -#endif - constexpr int MINIMAP_OFFSET = 12; constexpr int MINIMAP_PADDING = 5; @@ -436,6 +432,8 @@ void GraphEdit::_notification(int p_what) { snap_button->set_icon(get_theme_icon(SNAME("snap"))); minimap_button->set_icon(get_theme_icon(SNAME("minimap"))); layout_button->set_icon(get_theme_icon(SNAME("layout"))); + + zoom_label->set_custom_minimum_size(Size2(48, 0) * get_theme_default_base_scale()); } if (p_what == NOTIFICATION_READY) { Size2 hmin = h_scroll->get_combined_minimum_size(); @@ -816,11 +814,7 @@ void GraphEdit::_draw_connection_line(CanvasItem *p_where, const Vector2 &p_from scaled_points.push_back(points[i] * p_zoom); } -#ifdef TOOLS_ENABLED - p_where->draw_polyline_colors(scaled_points, colors, Math::floor(p_width * EDSCALE), lines_antialiased); -#else - p_where->draw_polyline_colors(scaled_points, colors, p_width, lines_antialiased); -#endif + p_where->draw_polyline_colors(scaled_points, colors, Math::floor(p_width * get_theme_default_base_scale()), lines_antialiased); } void GraphEdit::_connections_layer_draw() { @@ -2272,11 +2266,7 @@ GraphEdit::GraphEdit() { zoom_label->set_visible(false); zoom_label->set_v_size_flags(Control::SIZE_SHRINK_CENTER); zoom_label->set_align(Label::ALIGN_CENTER); -#ifdef TOOLS_ENABLED - zoom_label->set_custom_minimum_size(Size2(48, 0) * EDSCALE); -#else zoom_label->set_custom_minimum_size(Size2(48, 0)); -#endif _update_zoom_label(); zoom_minus = memnew(Button); diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp index 2c1092d8f9..653885aa08 100644 --- a/scene/gui/line_edit.cpp +++ b/scene/gui/line_edit.cpp @@ -40,7 +40,6 @@ #include "servers/display_server.h" #include "servers/text_server.h" #ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" #include "editor/editor_settings.h" #endif #include "scene/main/window.h" @@ -713,11 +712,7 @@ void LineEdit::_notification(int p_what) { ofs_max -= r_icon->get_width(); } -#ifdef TOOLS_ENABLED - int caret_width = Math::round(EDSCALE); -#else - int caret_width = 1; -#endif + int caret_width = Math::round(1 * get_theme_default_base_scale()); // Draw selections rects. Vector2 ofs = Point2(x_ofs + scroll_offset, y_ofs); diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index bc25177275..4588966d88 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -41,10 +41,6 @@ #include "modules/regex/regex.h" #endif -#ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" -#endif - RichTextLabel::Item *RichTextLabel::_get_next_item(Item *p_item, bool p_free) const { if (p_free) { if (p_item->subitems.size()) { @@ -995,19 +991,13 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o Color uc = font_color; uc.a *= 0.5; float y_off = TS->shaped_text_get_underline_position(rid); - float underline_width = TS->shaped_text_get_underline_thickness(rid); -#ifdef TOOLS_ENABLED - underline_width *= EDSCALE; -#endif + float underline_width = TS->shaped_text_get_underline_thickness(rid) * get_theme_default_base_scale(); draw_line(p_ofs + Vector2(off.x, off.y + y_off), p_ofs + Vector2(off.x + glyphs[i].advance * glyphs[i].repeat, off.y + y_off), uc, underline_width); } else if (_find_strikethrough(it)) { Color uc = font_color; uc.a *= 0.5; float y_off = -TS->shaped_text_get_ascent(rid) + TS->shaped_text_get_size(rid).y / 2; - float underline_width = TS->shaped_text_get_underline_thickness(rid); -#ifdef TOOLS_ENABLED - underline_width *= EDSCALE; -#endif + float underline_width = TS->shaped_text_get_underline_thickness(rid) * get_theme_default_base_scale(); draw_line(p_ofs + Vector2(off.x, off.y + y_off), p_ofs + Vector2(off.x + glyphs[i].advance * glyphs[i].repeat, off.y + y_off), uc, underline_width); } diff --git a/scene/gui/tabs.cpp b/scene/gui/tabs.cpp index ba8dba847c..f305bf7013 100644 --- a/scene/gui/tabs.cpp +++ b/scene/gui/tabs.cpp @@ -156,6 +156,7 @@ void Tabs::gui_input(const Ref<InputEvent> &p_event) { if (scrolling_enabled && buttons_visible) { if (missing_right) { offset++; + _ensure_no_over_offset(); // Avoid overreaching when scrolling fast. update(); } } diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index e2ddc761b8..6370ea9c95 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -42,10 +42,6 @@ #include "scene/main/window.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" -#endif - static bool _is_text_char(char32_t c) { return !is_symbol(c); } @@ -1173,12 +1169,8 @@ void TextEdit::_notification(int p_what) { } } - // Carets -#ifdef TOOLS_ENABLED - int caret_width = Math::round(EDSCALE); -#else - int caret_width = 1; -#endif + // Carets. + int caret_width = Math::round(1 * get_theme_default_base_scale()); if (!clipped && caret.line == line && line_wrap_index == caret_wrap_index) { caret.draw_pos.y = ofs_y + ldata->get_line_descent(line_wrap_index); @@ -2407,6 +2399,7 @@ Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const { } String TextEdit::get_tooltip(const Point2 &p_pos) const { + Object *tooltip_obj = ObjectDB::get_instance(tooltip_obj_id); if (!tooltip_obj) { return Control::get_tooltip(p_pos); } @@ -2429,7 +2422,8 @@ String TextEdit::get_tooltip(const Point2 &p_pos) const { } void TextEdit::set_tooltip_request_func(Object *p_obj, const StringName &p_function, const Variant &p_udata) { - tooltip_obj = p_obj; + ERR_FAIL_NULL(p_obj); + tooltip_obj_id = p_obj->get_instance_id(); tooltip_func = p_function; tooltip_ud = p_udata; } @@ -5080,10 +5074,12 @@ void TextEdit::_cut_internal() { } int cl = get_caret_line(); + int cc = get_caret_column(); + int indent_level = get_indent_level(cl); + double hscroll = get_h_scroll(); String clipboard = text[cl]; DisplayServer::get_singleton()->clipboard_set(clipboard); - set_caret_line(cl); set_caret_column(0); if (cl == 0 && get_line_count() > 1) { @@ -5094,6 +5090,17 @@ void TextEdit::_cut_internal() { set_caret_line(get_caret_line() + 1); } + // Correct the visualy perceived caret column taking care of identation level of the lines. + int diff_indent = indent_level - get_indent_level(get_caret_line()); + cc += diff_indent; + if (diff_indent != 0) { + cc += diff_indent > 0 ? -1 : 1; + } + + // Restore horizontal scroll and caret column modified by the backspace() call. + set_h_scroll(hscroll); + set_caret_column(cc); + cut_copy_line = clipboard; } diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index 07e585847a..3230de776f 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -330,7 +330,7 @@ private: int _get_column_pos_of_word(const String &p_key, const String &p_search, uint32_t p_search_flags, int p_from_column) const; /* Tooltip. */ - Object *tooltip_obj = nullptr; + ObjectID tooltip_obj_id; StringName tooltip_func; Variant tooltip_ud; diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp index 7d7596635c..3f041bf65a 100644 --- a/scene/gui/tree.cpp +++ b/scene/gui/tree.cpp @@ -41,10 +41,6 @@ #include "box_container.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_scale.h" -#endif - #include <limits.h> Size2 TreeItem::Cell::get_icon_size() const { @@ -1377,6 +1373,8 @@ void Tree::update_cache() { cache.title_button_hover = get_theme_stylebox(SNAME("title_button_hover")); cache.title_button_color = get_theme_color(SNAME("title_button_color")); + cache.base_scale = get_theme_default_base_scale(); + v_scroll->set_custom_step(cache.font->get_height(cache.font_size)); } @@ -2046,15 +2044,9 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 root_pos -= Point2i(cache.arrow->get_width(), 0); } - float line_width = cache.relationship_line_width; - float parent_line_width = cache.parent_hl_line_width; - float children_line_width = cache.children_hl_line_width; - -#ifdef TOOLS_ENABLED - line_width *= Math::round(EDSCALE); - parent_line_width *= Math::round(EDSCALE); - children_line_width *= Math::round(EDSCALE); -#endif + float line_width = cache.relationship_line_width * Math::round(cache.base_scale); + float parent_line_width = cache.parent_hl_line_width * Math::round(cache.base_scale); + float children_line_width = cache.children_hl_line_width * Math::round(cache.base_scale); Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; diff --git a/scene/gui/tree.h b/scene/gui/tree.h index c4a6b6b058..6ca9458e9b 100644 --- a/scene/gui/tree.h +++ b/scene/gui/tree.h @@ -516,6 +516,8 @@ private: Color custom_button_font_highlight; Color font_outline_color; + float base_scale = 1.0; + int hseparation = 0; int vseparation = 0; int item_margin = 0; diff --git a/scene/main/node.cpp b/scene/main/node.cpp index b1ba9de85c..0876c30dd1 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -41,10 +41,6 @@ #include "scene/scene_string_names.h" #include "viewport.h" -#ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" -#endif - #include <stdint.h> VARIANT_ENUM_CAST(Node::ProcessMode); @@ -2536,17 +2532,11 @@ NodePath Node::get_import_path() const { } static void _add_nodes_to_options(const Node *p_base, const Node *p_node, List<String> *r_options) { -#ifdef TOOLS_ENABLED - const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\""; -#else - const String quote_style = "\""; -#endif - if (p_node != p_base && !p_node->get_owner()) { return; } String n = p_base->get_path_to(p_node); - r_options->push_back(n.quote(quote_style)); + r_options->push_back(n.quote()); for (int i = 0; i < p_node->get_child_count(); i++) { _add_nodes_to_options(p_base, p_node->get_child(i), r_options); } diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index b3b743370b..e88bb3b952 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -57,17 +57,17 @@ #include "servers/audio_server.h" void ViewportTexture::setup_local_to_scene() { + Node *local_scene = get_local_scene(); + if (!local_scene) { + return; + } + if (vp) { vp->viewport_textures.erase(this); } vp = nullptr; - Node *local_scene = get_local_scene(); - if (!local_scene) { - return; - } - Node *vpn = local_scene->get_node(path); ERR_FAIL_COND_MSG(!vpn, "ViewportTexture: Path to node is invalid."); diff --git a/scene/main/window.cpp b/scene/main/window.cpp index ca5a3915d0..a0f62c853f 100644 --- a/scene/main/window.cpp +++ b/scene/main/window.cpp @@ -1266,6 +1266,18 @@ bool Window::has_theme_constant(const StringName &p_name, const StringName &p_th return Control::has_theme_item_in_types(theme_owner, theme_owner_window, Theme::DATA_TYPE_CONSTANT, p_name, theme_types); } +float Window::get_theme_default_base_scale() const { + return Control::fetch_theme_default_base_scale(theme_owner, theme_owner_window); +} + +Ref<Font> Window::get_theme_default_font() const { + return Control::fetch_theme_default_font(theme_owner, theme_owner_window); +} + +int Window::get_theme_default_font_size() const { + return Control::fetch_theme_default_font_size(theme_owner, theme_owner_window); +} + Rect2i Window::get_parent_rect() const { ERR_FAIL_COND_V(!is_inside_tree(), Rect2i()); if (is_embedded()) { @@ -1480,6 +1492,10 @@ void Window::_bind_methods() { ClassDB::bind_method(D_METHOD("has_theme_color", "name", "theme_type"), &Window::has_theme_color, DEFVAL("")); ClassDB::bind_method(D_METHOD("has_theme_constant", "name", "theme_type"), &Window::has_theme_constant, DEFVAL("")); + ClassDB::bind_method(D_METHOD("get_theme_default_base_scale"), &Window::get_theme_default_base_scale); + ClassDB::bind_method(D_METHOD("get_theme_default_font"), &Window::get_theme_default_font); + ClassDB::bind_method(D_METHOD("get_theme_default_font_size"), &Window::get_theme_default_font_size); + ClassDB::bind_method(D_METHOD("set_layout_direction", "direction"), &Window::set_layout_direction); ClassDB::bind_method(D_METHOD("get_layout_direction"), &Window::get_layout_direction); ClassDB::bind_method(D_METHOD("is_layout_rtl"), &Window::is_layout_rtl); diff --git a/scene/main/window.h b/scene/main/window.h index 4f31d9cd1f..def6eab7b8 100644 --- a/scene/main/window.h +++ b/scene/main/window.h @@ -280,6 +280,10 @@ public: bool has_theme_color(const StringName &p_name, const StringName &p_theme_type = StringName()) const; bool has_theme_constant(const StringName &p_name, const StringName &p_theme_type = StringName()) const; + float get_theme_default_base_scale() const; + Ref<Font> get_theme_default_font() const; + int get_theme_default_font_size() const; + Rect2i get_parent_rect() const; virtual DisplayServer::WindowID get_window_id() const override; diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 56dd9c6b06..bf8f7291be 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -215,6 +215,7 @@ #include "scene/3d/decal.h" #include "scene/3d/gpu_particles_3d.h" #include "scene/3d/gpu_particles_collision_3d.h" +#include "scene/3d/importer_mesh_instance_3d.h" #include "scene/3d/joint_3d.h" #include "scene/3d/light_3d.h" #include "scene/3d/lightmap_gi.h" @@ -244,6 +245,7 @@ #include "scene/3d/world_environment.h" #include "scene/3d/xr_nodes.h" #include "scene/resources/environment.h" +#include "scene/resources/importer_mesh.h" #include "scene/resources/mesh_library.h" #endif @@ -441,10 +443,11 @@ void register_scene_types() { GDREGISTER_CLASS(Skin); GDREGISTER_VIRTUAL_CLASS(SkinReference); GDREGISTER_CLASS(Skeleton3D); + GDREGISTER_CLASS(ImporterMesh); + GDREGISTER_CLASS(ImporterMeshInstance3D); GDREGISTER_VIRTUAL_CLASS(VisualInstance3D); GDREGISTER_VIRTUAL_CLASS(GeometryInstance3D); GDREGISTER_CLASS(Camera3D); - GDREGISTER_CLASS(ClippedCamera3D); GDREGISTER_CLASS(AudioListener3D); GDREGISTER_CLASS(XRCamera3D); GDREGISTER_CLASS(XRController3D); diff --git a/scene/resources/canvas_item_material.cpp b/scene/resources/canvas_item_material.cpp index fa95ab0e79..b291724c4c 100644 --- a/scene/resources/canvas_item_material.cpp +++ b/scene/resources/canvas_item_material.cpp @@ -135,7 +135,7 @@ void CanvasItemMaterial::_update_shader() { code += " particle_frame = mod(particle_frame, particle_total_frames);\n"; code += " }"; code += " UV /= vec2(h_frames, v_frames);\n"; - code += " UV += vec2(mod(particle_frame, h_frames) / h_frames, floor(particle_frame / h_frames) / v_frames);\n"; + code += " UV += vec2(mod(particle_frame, h_frames) / h_frames, floor((particle_frame + 0.5) / h_frames) / v_frames);\n"; code += "}\n"; } diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp index 94cf826477..54bb7a82cf 100644 --- a/scene/resources/default_theme/default_theme.cpp +++ b/scene/resources/default_theme/default_theme.cpp @@ -1036,9 +1036,16 @@ void make_default_theme(bool p_hidpi, Ref<Font> p_font) { } Ref<Font> large_font = default_font; - fill_default_theme(t, default_font, large_font, default_icon, default_style, p_hidpi ? 2.0 : 1.0); + + float default_scale = 1.0; + if (p_hidpi) { + default_scale = 2.0; + } + + fill_default_theme(t, default_font, large_font, default_icon, default_style, default_scale); Theme::set_default(t); + Theme::set_default_base_scale(default_scale); Theme::set_default_icon(default_icon); Theme::set_default_style(default_style); Theme::set_default_font(default_font); diff --git a/editor/import/scene_importer_mesh.cpp b/scene/resources/importer_mesh.cpp index 370394b475..af69b799cc 100644 --- a/editor/import/scene_importer_mesh.cpp +++ b/scene/resources/importer_mesh.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* scene_importer_mesh.cpp */ +/* importer_mesh.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "scene_importer_mesh.h" +#include "importer_mesh.h" #include "core/math/random_pcg.h" #include "core/math/static_raycaster.h" @@ -36,7 +36,7 @@ #include <cstdint> -void EditorSceneImporterMesh::Surface::split_normals(const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) { +void ImporterMesh::Surface::split_normals(const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) { ERR_FAIL_COND(arrays.size() != RS::ARRAY_MAX); const PackedVector3Array &vertices = arrays[RS::ARRAY_VERTEX]; @@ -115,37 +115,38 @@ void EditorSceneImporterMesh::Surface::split_normals(const LocalVector<int> &p_i for (int j = 0; j < new_vertex_count; j++) { data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]]; } + arrays[i] = data; } break; default: { - ERR_FAIL_MSG("Uhandled array type."); + ERR_FAIL_MSG("Unhandled array type."); } break; } } } -void EditorSceneImporterMesh::add_blend_shape(const String &p_name) { +void ImporterMesh::add_blend_shape(const String &p_name) { ERR_FAIL_COND(surfaces.size() > 0); blend_shapes.push_back(p_name); } -int EditorSceneImporterMesh::get_blend_shape_count() const { +int ImporterMesh::get_blend_shape_count() const { return blend_shapes.size(); } -String EditorSceneImporterMesh::get_blend_shape_name(int p_blend_shape) const { +String ImporterMesh::get_blend_shape_name(int p_blend_shape) const { ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String()); return blend_shapes[p_blend_shape]; } -void EditorSceneImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) { +void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) { blend_shape_mode = p_blend_shape_mode; } -Mesh::BlendShapeMode EditorSceneImporterMesh::get_blend_shape_mode() const { +Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const { return blend_shape_mode; } -void EditorSceneImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name, const uint32_t p_flags) { +void ImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name, const uint32_t p_flags) { ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size()); ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX); Surface s; @@ -185,67 +186,67 @@ void EditorSceneImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const mesh.unref(); } -int EditorSceneImporterMesh::get_surface_count() const { +int ImporterMesh::get_surface_count() const { return surfaces.size(); } -Mesh::PrimitiveType EditorSceneImporterMesh::get_surface_primitive_type(int p_surface) { +Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX); return surfaces[p_surface].primitive; } -Array EditorSceneImporterMesh::get_surface_arrays(int p_surface) const { +Array ImporterMesh::get_surface_arrays(int p_surface) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array()); return surfaces[p_surface].arrays; } -String EditorSceneImporterMesh::get_surface_name(int p_surface) const { +String ImporterMesh::get_surface_name(int p_surface) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String()); return surfaces[p_surface].name; } -void EditorSceneImporterMesh::set_surface_name(int p_surface, const String &p_name) { +void ImporterMesh::set_surface_name(int p_surface, const String &p_name) { ERR_FAIL_INDEX(p_surface, surfaces.size()); surfaces.write[p_surface].name = p_name; mesh.unref(); } -Array EditorSceneImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const { +Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array()); ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array()); return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays; } -int EditorSceneImporterMesh::get_surface_lod_count(int p_surface) const { +int ImporterMesh::get_surface_lod_count(int p_surface) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0); return surfaces[p_surface].lods.size(); } -Vector<int> EditorSceneImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const { +Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>()); ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>()); return surfaces[p_surface].lods[p_lod].indices; } -float EditorSceneImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const { +float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0); ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0); return surfaces[p_surface].lods[p_lod].distance; } -uint32_t EditorSceneImporterMesh::get_surface_format(int p_surface) const { +uint32_t ImporterMesh::get_surface_format(int p_surface) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0); return surfaces[p_surface].flags; } -Ref<Material> EditorSceneImporterMesh::get_surface_material(int p_surface) const { +Ref<Material> ImporterMesh::get_surface_material(int p_surface) const { ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>()); return surfaces[p_surface].material; } -void EditorSceneImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) { +void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) { ERR_FAIL_INDEX(p_surface, surfaces.size()); surfaces.write[p_surface].material = p_material; mesh.unref(); } -void EditorSceneImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_split_angle) { +void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_split_angle) { if (!SurfaceTool::simplify_scale_func) { return; } @@ -260,6 +261,9 @@ void EditorSceneImporterMesh::generate_lods(float p_normal_merge_angle, float p_ if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) { continue; } + if (get_blend_shape_count()) { + continue; + } surfaces.write[i].lods.clear(); Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX]; @@ -604,11 +608,11 @@ void EditorSceneImporterMesh::generate_lods(float p_normal_merge_angle, float p_ } } -bool EditorSceneImporterMesh::has_mesh() const { +bool ImporterMesh::has_mesh() const { return mesh.is_valid(); } -Ref<ArrayMesh> EditorSceneImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) { +Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) { ERR_FAIL_COND_V(surfaces.size() == 0, Ref<ArrayMesh>()); if (mesh.is_null()) { @@ -660,13 +664,13 @@ Ref<ArrayMesh> EditorSceneImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) { return mesh; } -void EditorSceneImporterMesh::clear() { +void ImporterMesh::clear() { surfaces.clear(); blend_shapes.clear(); mesh.unref(); } -void EditorSceneImporterMesh::create_shadow_mesh() { +void ImporterMesh::create_shadow_mesh() { if (shadow_mesh.is_valid()) { shadow_mesh.unref(); } @@ -759,11 +763,11 @@ void EditorSceneImporterMesh::create_shadow_mesh() { } } -Ref<EditorSceneImporterMesh> EditorSceneImporterMesh::get_shadow_mesh() const { +Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const { return shadow_mesh; } -void EditorSceneImporterMesh::_set_data(const Dictionary &p_data) { +void ImporterMesh::_set_data(const Dictionary &p_data) { clear(); if (p_data.has("blend_shape_names")) { blend_shapes = p_data["blend_shape_names"]; @@ -801,7 +805,7 @@ void EditorSceneImporterMesh::_set_data(const Dictionary &p_data) { } } } -Dictionary EditorSceneImporterMesh::_get_data() const { +Dictionary ImporterMesh::_get_data() const { Dictionary data; if (blend_shapes.size()) { data["blend_shape_names"] = blend_shapes; @@ -844,7 +848,7 @@ Dictionary EditorSceneImporterMesh::_get_data() const { return data; } -Vector<Face3> EditorSceneImporterMesh::get_faces() const { +Vector<Face3> ImporterMesh::get_faces() const { Vector<Face3> faces; for (int i = 0; i < surfaces.size(); i++) { if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) { @@ -873,7 +877,7 @@ Vector<Face3> EditorSceneImporterMesh::get_faces() const { return faces; } -Vector<Ref<Shape3D>> EditorSceneImporterMesh::convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const { +Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const { ERR_FAIL_COND_V(!Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>()); const Vector<Face3> faces = get_faces(); @@ -920,7 +924,7 @@ Vector<Ref<Shape3D>> EditorSceneImporterMesh::convex_decompose(const Mesh::Conve return ret; } -Ref<Shape3D> EditorSceneImporterMesh::create_trimesh_shape() const { +Ref<Shape3D> ImporterMesh::create_trimesh_shape() const { Vector<Face3> faces = get_faces(); if (faces.size() == 0) { return Ref<Shape3D>(); @@ -941,7 +945,7 @@ Ref<Shape3D> EditorSceneImporterMesh::create_trimesh_shape() const { return shape; } -Ref<NavigationMesh> EditorSceneImporterMesh::create_navigation_mesh() { +Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() { Vector<Face3> faces = get_faces(); if (faces.size() == 0) { return Ref<NavigationMesh>(); @@ -996,7 +1000,7 @@ struct EditorSceneImporterMeshLightmapSurface { String name; }; -Error EditorSceneImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache) { +Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache) { ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED); ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes."); @@ -1193,46 +1197,46 @@ Error EditorSceneImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_ return OK; } -void EditorSceneImporterMesh::set_lightmap_size_hint(const Size2i &p_size) { +void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) { lightmap_size_hint = p_size; } -Size2i EditorSceneImporterMesh::get_lightmap_size_hint() const { +Size2i ImporterMesh::get_lightmap_size_hint() const { return lightmap_size_hint; } -void EditorSceneImporterMesh::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &EditorSceneImporterMesh::add_blend_shape); - ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &EditorSceneImporterMesh::get_blend_shape_count); - ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &EditorSceneImporterMesh::get_blend_shape_name); +void ImporterMesh::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape); + ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count); + ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name); - ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &EditorSceneImporterMesh::set_blend_shape_mode); - ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &EditorSceneImporterMesh::get_blend_shape_mode); + ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode); + ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode); - ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &EditorSceneImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &ImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_surface_count"), &EditorSceneImporterMesh::get_surface_count); - ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &EditorSceneImporterMesh::get_surface_primitive_type); - ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &EditorSceneImporterMesh::get_surface_name); - ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &EditorSceneImporterMesh::get_surface_arrays); - ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &EditorSceneImporterMesh::get_surface_blend_shape_arrays); - ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &EditorSceneImporterMesh::get_surface_lod_count); - ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_size); - ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_indices); - ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &EditorSceneImporterMesh::get_surface_material); - ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &EditorSceneImporterMesh::get_surface_format); + ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count); + ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type); + ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name); + ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays); + ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays); + ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count); + ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size); + ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices); + ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material); + ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format); - ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &EditorSceneImporterMesh::set_surface_name); - ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &EditorSceneImporterMesh::set_surface_material); + ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name); + ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material); - ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &EditorSceneImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>())); - ClassDB::bind_method(D_METHOD("clear"), &EditorSceneImporterMesh::clear); + ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>())); + ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear); - ClassDB::bind_method(D_METHOD("_set_data", "data"), &EditorSceneImporterMesh::_set_data); - ClassDB::bind_method(D_METHOD("_get_data"), &EditorSceneImporterMesh::_get_data); + ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data); - ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &EditorSceneImporterMesh::set_lightmap_size_hint); - ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &EditorSceneImporterMesh::get_lightmap_size_hint); + ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint); + ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); } diff --git a/editor/import/scene_importer_mesh.h b/scene/resources/importer_mesh.h index 111b191cae..89909f17f0 100644 --- a/editor/import/scene_importer_mesh.h +++ b/scene/resources/importer_mesh.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* scene_importer_mesh.h */ +/* importer_mesh.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef EDITOR_SCENE_IMPORTER_MESH_H -#define EDITOR_SCENE_IMPORTER_MESH_H +#ifndef SCENE_IMPORTER_MESH_H +#define SCENE_IMPORTER_MESH_H #include "core/io/resource.h" #include "core/templates/local_vector.h" @@ -44,8 +44,8 @@ // so the data is not registered (hence, quality loss), importing happens faster and // its easier to modify before saving -class EditorSceneImporterMesh : public Resource { - GDCLASS(EditorSceneImporterMesh, Resource) +class ImporterMesh : public Resource { + GDCLASS(ImporterMesh, Resource) struct Surface { Mesh::PrimitiveType primitive; @@ -77,7 +77,7 @@ class EditorSceneImporterMesh : public Resource { Ref<ArrayMesh> mesh; - Ref<EditorSceneImporterMesh> shadow_mesh; + Ref<ImporterMesh> shadow_mesh; Size2i lightmap_size_hint; @@ -114,7 +114,7 @@ public: void generate_lods(float p_normal_merge_angle, float p_normal_split_angle); void create_shadow_mesh(); - Ref<EditorSceneImporterMesh> get_shadow_mesh() const; + Ref<ImporterMesh> get_shadow_mesh() const; Vector<Face3> get_faces() const; Vector<Ref<Shape3D>> convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const; @@ -129,4 +129,4 @@ public: Ref<ArrayMesh> get_mesh(const Ref<ArrayMesh> &p_base = Ref<ArrayMesh>()); void clear(); }; -#endif // EDITOR_SCENE_IMPORTER_MESH_H +#endif // SCENE_IMPORTER_MESH_H diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index 3a6af3afb0..abb3381c4e 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -32,11 +32,6 @@ #include "core/config/engine.h" #include "core/version.h" - -#ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" -#endif - #include "scene/main/scene_tree.h" #include "scene/scene_string_names.h" @@ -80,6 +75,9 @@ void Material::_validate_property(PropertyInfo &property) const { if (!_can_do_next_pass() && property.name == "next_pass") { property.usage = PROPERTY_USAGE_NONE; } + if (!_can_use_render_priority() && property.name == "render_priority") { + property.usage = PROPERTY_USAGE_NONE; + } } void Material::inspect_native_shader_code() { @@ -268,19 +266,13 @@ void ShaderMaterial::_bind_methods() { } void ShaderMaterial::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { -#ifdef TOOLS_ENABLED - const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\""; -#else - const String quote_style = "\""; -#endif - String f = p_function.operator String(); if ((f == "get_shader_param" || f == "set_shader_param") && p_idx == 0) { if (shader.is_valid()) { List<PropertyInfo> pl; shader->get_param_list(&pl); for (const PropertyInfo &E : pl) { - r_options->push_back(E.name.replace_first("shader_param/", "").quote(quote_style)); + r_options->push_back(E.name.replace_first("shader_param/", "").quote()); } } } @@ -291,6 +283,10 @@ bool ShaderMaterial::_can_do_next_pass() const { return shader.is_valid() && shader->get_mode() == Shader::MODE_SPATIAL; } +bool ShaderMaterial::_can_use_render_priority() const { + return shader.is_valid() && shader->get_mode() == Shader::MODE_SPATIAL; +} + Shader::Mode ShaderMaterial::get_shader_mode() const { if (shader.is_valid()) { return shader->get_mode(); @@ -815,7 +811,7 @@ void BaseMaterial3D::_update_shader() { code += " particle_frame = mod(particle_frame, particle_total_frames);\n"; code += " }"; code += " UV /= vec2(h_frames, v_frames);\n"; - code += " UV += vec2(mod(particle_frame, h_frames) / h_frames, floor(particle_frame / h_frames) / v_frames);\n"; + code += " UV += vec2(mod(particle_frame, h_frames) / h_frames, floor((particle_frame + 0.5) / h_frames) / v_frames);\n"; } break; case BILLBOARD_MAX: break; // Internal value, skip. diff --git a/scene/resources/material.h b/scene/resources/material.h index 5d7a5324ca..798f7568df 100644 --- a/scene/resources/material.h +++ b/scene/resources/material.h @@ -53,6 +53,7 @@ protected: _FORCE_INLINE_ RID _get_material() const { return material; } static void _bind_methods(); virtual bool _can_do_next_pass() const { return false; } + virtual bool _can_use_render_priority() const { return false; } void _validate_property(PropertyInfo &property) const override; @@ -93,6 +94,7 @@ protected: void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const override; virtual bool _can_do_next_pass() const override; + virtual bool _can_use_render_priority() const override; void _shader_changed(); @@ -535,6 +537,7 @@ protected: static void _bind_methods(); void _validate_property(PropertyInfo &property) const override; virtual bool _can_do_next_pass() const override { return true; } + virtual bool _can_use_render_priority() const override { return true; } public: void set_albedo(const Color &p_albedo); diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp index c8d3ea5e37..60cda637ca 100644 --- a/scene/resources/packed_scene.cpp +++ b/scene/resources/packed_scene.cpp @@ -388,7 +388,7 @@ Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map editable_instances.push_back(p_owner->get_path_to(p_node)); // Node is the root of an editable instance. is_editable_instance = true; - } else if (p_node->get_owner() && p_node->get_owner() != p_owner && p_owner->is_editable_instance(p_node->get_owner())) { + } else if (p_node->get_owner() && p_owner->is_ancestor_of(p_node->get_owner()) && p_owner->is_editable_instance(p_node->get_owner())) { // Node is part of an editable instance. is_editable_instance = true; } diff --git a/scene/resources/sky_material.cpp b/scene/resources/sky_material.cpp index 39082b6f7a..b6d3c96cb7 100644 --- a/scene/resources/sky_material.cpp +++ b/scene/resources/sky_material.cpp @@ -125,10 +125,6 @@ float ProceduralSkyMaterial::get_sun_curve() const { return sun_curve; } -bool ProceduralSkyMaterial::_can_do_next_pass() const { - return false; -} - Shader::Mode ProceduralSkyMaterial::get_shader_mode() const { return Shader::MODE_SKY; } @@ -312,10 +308,6 @@ Ref<Texture2D> PanoramaSkyMaterial::get_panorama() const { return panorama; } -bool PanoramaSkyMaterial::_can_do_next_pass() const { - return false; -} - Shader::Mode PanoramaSkyMaterial::get_shader_mode() const { return Shader::MODE_SKY; } @@ -482,10 +474,6 @@ Ref<Texture2D> PhysicalSkyMaterial::get_night_sky() const { return night_sky; } -bool PhysicalSkyMaterial::_can_do_next_pass() const { - return false; -} - Shader::Mode PhysicalSkyMaterial::get_shader_mode() const { return Shader::MODE_SKY; } diff --git a/scene/resources/sky_material.h b/scene/resources/sky_material.h index 63e730617b..daeda212d4 100644 --- a/scene/resources/sky_material.h +++ b/scene/resources/sky_material.h @@ -58,7 +58,6 @@ private: protected: static void _bind_methods(); - virtual bool _can_do_next_pass() const override; public: void set_sky_top_color(const Color &p_sky_top); @@ -117,7 +116,6 @@ private: protected: static void _bind_methods(); - virtual bool _can_do_next_pass() const override; public: void set_panorama(const Ref<Texture2D> &p_panorama); @@ -159,7 +157,6 @@ private: protected: static void _bind_methods(); - virtual bool _can_do_next_pass() const override; public: void set_rayleigh_coefficient(float p_rayleigh); diff --git a/scene/resources/theme.cpp b/scene/resources/theme.cpp index e49d883ba4..65cdc1e24e 100644 --- a/scene/resources/theme.cpp +++ b/scene/resources/theme.cpp @@ -29,270 +29,20 @@ /*************************************************************************/ #include "theme.h" -#include "core/io/file_access.h" #include "core/string/print_string.h" -void Theme::_emit_theme_changed() { - if (no_change_propagation) { - return; - } - - notify_property_list_changed(); - emit_changed(); -} - -Vector<String> Theme::_get_icon_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_icon_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_icon_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_icon_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_stylebox_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_stylebox_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_stylebox_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_stylebox_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_font_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_font_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_font_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_font_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_font_size_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_font_size_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_font_size_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_font_size_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_color_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_color_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_color_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_color_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_constant_list(const String &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_constant_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_constant_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_constant_type_list(&il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_theme_item_list(DataType p_data_type, const String &p_theme_type) const { - switch (p_data_type) { - case DATA_TYPE_COLOR: - return _get_color_list(p_theme_type); - case DATA_TYPE_CONSTANT: - return _get_constant_list(p_theme_type); - case DATA_TYPE_FONT: - return _get_font_list(p_theme_type); - case DATA_TYPE_FONT_SIZE: - return _get_font_size_list(p_theme_type); - case DATA_TYPE_ICON: - return _get_icon_list(p_theme_type); - case DATA_TYPE_STYLEBOX: - return _get_stylebox_list(p_theme_type); - case DATA_TYPE_MAX: - break; // Can't happen, but silences warning. - } - - return Vector<String>(); -} - -Vector<String> Theme::_get_theme_item_type_list(DataType p_data_type) const { - switch (p_data_type) { - case DATA_TYPE_COLOR: - return _get_color_type_list(); - case DATA_TYPE_CONSTANT: - return _get_constant_type_list(); - case DATA_TYPE_FONT: - return _get_font_type_list(); - case DATA_TYPE_FONT_SIZE: - return _get_font_size_type_list(); - case DATA_TYPE_ICON: - return _get_icon_type_list(); - case DATA_TYPE_STYLEBOX: - return _get_stylebox_type_list(); - case DATA_TYPE_MAX: - break; // Can't happen, but silences warning. - } - - return Vector<String>(); -} - -Vector<String> Theme::_get_type_variation_list(const StringName &p_theme_type) const { - Vector<String> ilret; - List<StringName> il; - - get_type_variation_list(p_theme_type, &il); - ilret.resize(il.size()); - - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} - -Vector<String> Theme::_get_type_list() const { - Vector<String> ilret; - List<StringName> il; - - get_type_list(&il); - ilret.resize(il.size()); +// Universal Theme resources used when no other theme has the item. +Ref<Theme> Theme::default_theme; +Ref<Theme> Theme::project_default_theme; - int i = 0; - String *w = ilret.ptrw(); - for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { - w[i] = E->get(); - } - return ilret; -} +// Universal default values, final fallback for every theme. +float Theme::default_base_scale = 1.0; +Ref<Texture2D> Theme::default_icon; +Ref<StyleBox> Theme::default_style; +Ref<Font> Theme::default_font; +int Theme::default_font_size = 16; +// Dynamic properties. bool Theme::_set(const StringName &p_name, const Variant &p_value) { String sname = p_name; @@ -452,6 +202,63 @@ void Theme::_get_property_list(List<PropertyInfo> *p_list) const { } } +// Universal fallback Theme resources. +Ref<Theme> Theme::get_default() { + return default_theme; +} + +void Theme::set_default(const Ref<Theme> &p_default) { + default_theme = p_default; +} + +Ref<Theme> Theme::get_project_default() { + return project_default_theme; +} + +void Theme::set_project_default(const Ref<Theme> &p_project_default) { + project_default_theme = p_project_default; +} + +// Universal fallback values for theme item types. +void Theme::set_default_base_scale(float p_base_scale) { + default_base_scale = p_base_scale; +} + +void Theme::set_default_icon(const Ref<Texture2D> &p_icon) { + default_icon = p_icon; +} + +void Theme::set_default_style(const Ref<StyleBox> &p_style) { + default_style = p_style; +} + +void Theme::set_default_font(const Ref<Font> &p_font) { + default_font = p_font; +} + +void Theme::set_default_font_size(int p_font_size) { + default_font_size = p_font_size; +} + +// Fallback values for theme item types, configurable per theme. +void Theme::set_default_theme_base_scale(float p_base_scale) { + if (default_theme_base_scale == p_base_scale) { + return; + } + + default_theme_base_scale = p_base_scale; + + _emit_theme_changed(); +} + +float Theme::get_default_theme_base_scale() const { + return default_theme_base_scale; +} + +bool Theme::has_default_theme_base_scale() const { + return default_theme_base_scale > 0.0; +} + void Theme::set_default_theme_font(const Ref<Font> &p_default_font) { if (default_theme_font == p_default_font) { return; @@ -464,7 +271,7 @@ void Theme::set_default_theme_font(const Ref<Font> &p_default_font) { default_theme_font = p_default_font; if (default_theme_font.is_valid()) { - default_theme_font->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(), CONNECT_REFERENCE_COUNTED); + default_theme_font->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(false), CONNECT_REFERENCE_COUNTED); } _emit_theme_changed(); @@ -474,6 +281,10 @@ Ref<Font> Theme::get_default_theme_font() const { return default_theme_font; } +bool Theme::has_default_theme_font() const { + return default_theme_font.is_valid(); +} + void Theme::set_default_theme_font_size(int p_font_size) { if (default_theme_font_size == p_font_size) { return; @@ -488,57 +299,25 @@ int Theme::get_default_theme_font_size() const { return default_theme_font_size; } -Ref<Theme> Theme::project_default_theme; -Ref<Theme> Theme::default_theme; -Ref<Texture2D> Theme::default_icon; -Ref<StyleBox> Theme::default_style; -Ref<Font> Theme::default_font; -int Theme::default_font_size = 16; - -Ref<Theme> Theme::get_default() { - return default_theme; -} - -void Theme::set_default(const Ref<Theme> &p_default) { - default_theme = p_default; -} - -Ref<Theme> Theme::get_project_default() { - return project_default_theme; -} - -void Theme::set_project_default(const Ref<Theme> &p_project_default) { - project_default_theme = p_project_default; -} - -void Theme::set_default_icon(const Ref<Texture2D> &p_icon) { - default_icon = p_icon; -} - -void Theme::set_default_style(const Ref<StyleBox> &p_style) { - default_style = p_style; -} - -void Theme::set_default_font(const Ref<Font> &p_font) { - default_font = p_font; -} - -void Theme::set_default_font_size(int p_font_size) { - default_font_size = p_font_size; +bool Theme::has_default_theme_font_size() const { + return default_theme_font_size > 0; } +// Icons. void Theme::set_icon(const StringName &p_name, const StringName &p_theme_type, const Ref<Texture2D> &p_icon) { + bool existing = false; if (icon_map[p_theme_type].has(p_name) && icon_map[p_theme_type][p_name].is_valid()) { + existing = true; icon_map[p_theme_type][p_name]->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); } icon_map[p_theme_type][p_name] = p_icon; if (p_icon.is_valid()) { - icon_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(), CONNECT_REFERENCE_COUNTED); + icon_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(false), CONNECT_REFERENCE_COUNTED); } - _emit_theme_changed(); + _emit_theme_changed(!existing); } Ref<Texture2D> Theme::get_icon(const StringName &p_name, const StringName &p_theme_type) const { @@ -565,7 +344,7 @@ void Theme::rename_icon(const StringName &p_old_name, const StringName &p_name, icon_map[p_theme_type][p_name] = icon_map[p_theme_type][p_old_name]; icon_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_icon(const StringName &p_name, const StringName &p_theme_type) { @@ -578,7 +357,7 @@ void Theme::clear_icon(const StringName &p_name, const StringName &p_theme_type) icon_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_icon_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -611,18 +390,21 @@ void Theme::get_icon_type_list(List<StringName> *p_list) const { } } +// Styleboxes. void Theme::set_stylebox(const StringName &p_name, const StringName &p_theme_type, const Ref<StyleBox> &p_style) { + bool existing = false; if (style_map[p_theme_type].has(p_name) && style_map[p_theme_type][p_name].is_valid()) { + existing = true; style_map[p_theme_type][p_name]->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); } style_map[p_theme_type][p_name] = p_style; if (p_style.is_valid()) { - style_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(), CONNECT_REFERENCE_COUNTED); + style_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(false), CONNECT_REFERENCE_COUNTED); } - _emit_theme_changed(); + _emit_theme_changed(!existing); } Ref<StyleBox> Theme::get_stylebox(const StringName &p_name, const StringName &p_theme_type) const { @@ -649,7 +431,7 @@ void Theme::rename_stylebox(const StringName &p_old_name, const StringName &p_na style_map[p_theme_type][p_name] = style_map[p_theme_type][p_old_name]; style_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_stylebox(const StringName &p_name, const StringName &p_theme_type) { @@ -662,7 +444,7 @@ void Theme::clear_stylebox(const StringName &p_name, const StringName &p_theme_t style_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_stylebox_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -695,24 +477,27 @@ void Theme::get_stylebox_type_list(List<StringName> *p_list) const { } } +// Fonts. void Theme::set_font(const StringName &p_name, const StringName &p_theme_type, const Ref<Font> &p_font) { + bool existing = false; if (font_map[p_theme_type][p_name].is_valid()) { + existing = true; font_map[p_theme_type][p_name]->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); } font_map[p_theme_type][p_name] = p_font; if (p_font.is_valid()) { - font_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(), CONNECT_REFERENCE_COUNTED); + font_map[p_theme_type][p_name]->connect("changed", callable_mp(this, &Theme::_emit_theme_changed), varray(false), CONNECT_REFERENCE_COUNTED); } - _emit_theme_changed(); + _emit_theme_changed(!existing); } Ref<Font> Theme::get_font(const StringName &p_name, const StringName &p_theme_type) const { if (font_map.has(p_theme_type) && font_map[p_theme_type].has(p_name) && font_map[p_theme_type][p_name].is_valid()) { return font_map[p_theme_type][p_name]; - } else if (default_theme_font.is_valid()) { + } else if (has_default_theme_font()) { return default_theme_font; } else { return default_font; @@ -720,7 +505,7 @@ Ref<Font> Theme::get_font(const StringName &p_name, const StringName &p_theme_ty } bool Theme::has_font(const StringName &p_name, const StringName &p_theme_type) const { - return ((font_map.has(p_theme_type) && font_map[p_theme_type].has(p_name) && font_map[p_theme_type][p_name].is_valid()) || default_theme_font.is_valid()); + return ((font_map.has(p_theme_type) && font_map[p_theme_type].has(p_name) && font_map[p_theme_type][p_name].is_valid()) || has_default_theme_font()); } bool Theme::has_font_nocheck(const StringName &p_name, const StringName &p_theme_type) const { @@ -735,7 +520,7 @@ void Theme::rename_font(const StringName &p_old_name, const StringName &p_name, font_map[p_theme_type][p_name] = font_map[p_theme_type][p_old_name]; font_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_font(const StringName &p_name, const StringName &p_theme_type) { @@ -748,7 +533,7 @@ void Theme::clear_font(const StringName &p_name, const StringName &p_theme_type) font_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_font_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -781,16 +566,18 @@ void Theme::get_font_type_list(List<StringName> *p_list) const { } } +// Font sizes. void Theme::set_font_size(const StringName &p_name, const StringName &p_theme_type, int p_font_size) { + bool existing = has_font_size_nocheck(p_name, p_theme_type); font_size_map[p_theme_type][p_name] = p_font_size; - _emit_theme_changed(); + _emit_theme_changed(!existing); } int Theme::get_font_size(const StringName &p_name, const StringName &p_theme_type) const { if (font_size_map.has(p_theme_type) && font_size_map[p_theme_type].has(p_name) && (font_size_map[p_theme_type][p_name] > 0)) { return font_size_map[p_theme_type][p_name]; - } else if (default_theme_font_size > 0) { + } else if (has_default_theme_font_size()) { return default_theme_font_size; } else { return default_font_size; @@ -798,7 +585,7 @@ int Theme::get_font_size(const StringName &p_name, const StringName &p_theme_typ } bool Theme::has_font_size(const StringName &p_name, const StringName &p_theme_type) const { - return ((font_size_map.has(p_theme_type) && font_size_map[p_theme_type].has(p_name) && (font_size_map[p_theme_type][p_name] > 0)) || (default_theme_font_size > 0)); + return ((font_size_map.has(p_theme_type) && font_size_map[p_theme_type].has(p_name) && (font_size_map[p_theme_type][p_name] > 0)) || has_default_theme_font_size()); } bool Theme::has_font_size_nocheck(const StringName &p_name, const StringName &p_theme_type) const { @@ -813,7 +600,7 @@ void Theme::rename_font_size(const StringName &p_old_name, const StringName &p_n font_size_map[p_theme_type][p_name] = font_size_map[p_theme_type][p_old_name]; font_size_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_font_size(const StringName &p_name, const StringName &p_theme_type) { @@ -822,7 +609,7 @@ void Theme::clear_font_size(const StringName &p_name, const StringName &p_theme_ font_size_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_font_size_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -855,10 +642,12 @@ void Theme::get_font_size_type_list(List<StringName> *p_list) const { } } +// Colors. void Theme::set_color(const StringName &p_name, const StringName &p_theme_type, const Color &p_color) { + bool existing = has_color_nocheck(p_name, p_theme_type); color_map[p_theme_type][p_name] = p_color; - _emit_theme_changed(); + _emit_theme_changed(!existing); } Color Theme::get_color(const StringName &p_name, const StringName &p_theme_type) const { @@ -885,7 +674,7 @@ void Theme::rename_color(const StringName &p_old_name, const StringName &p_name, color_map[p_theme_type][p_name] = color_map[p_theme_type][p_old_name]; color_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_color(const StringName &p_name, const StringName &p_theme_type) { @@ -894,7 +683,7 @@ void Theme::clear_color(const StringName &p_name, const StringName &p_theme_type color_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_color_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -927,10 +716,12 @@ void Theme::get_color_type_list(List<StringName> *p_list) const { } } +// Theme constants. void Theme::set_constant(const StringName &p_name, const StringName &p_theme_type, int p_constant) { + bool existing = has_constant_nocheck(p_name, p_theme_type); constant_map[p_theme_type][p_name] = p_constant; - _emit_theme_changed(); + _emit_theme_changed(!existing); } int Theme::get_constant(const StringName &p_name, const StringName &p_theme_type) const { @@ -957,7 +748,7 @@ void Theme::rename_constant(const StringName &p_old_name, const StringName &p_na constant_map[p_theme_type][p_name] = constant_map[p_theme_type][p_old_name]; constant_map[p_theme_type].erase(p_old_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::clear_constant(const StringName &p_name, const StringName &p_theme_type) { @@ -966,7 +757,7 @@ void Theme::clear_constant(const StringName &p_name, const StringName &p_theme_t constant_map[p_theme_type].erase(p_name); - _emit_theme_changed(); + _emit_theme_changed(true); } void Theme::get_constant_list(StringName p_theme_type, List<StringName> *p_list) const { @@ -999,6 +790,7 @@ void Theme::get_constant_type_list(List<StringName> *p_list) const { } } +// Generic methods for managing theme items. void Theme::set_theme_item(DataType p_data_type, const StringName &p_name, const StringName &p_theme_type, const Variant &p_value) { switch (p_data_type) { case DATA_TYPE_COLOR: { @@ -1230,6 +1022,7 @@ void Theme::get_theme_item_type_list(DataType p_data_type, List<StringName> *p_l } } +// Theme type variations. void Theme::set_type_variation(const StringName &p_theme_type, const StringName &p_base_type) { ERR_FAIL_COND_MSG(p_theme_type == StringName(), "An empty theme type cannot be marked as a variation of another type."); ERR_FAIL_COND_MSG(ClassDB::class_exists(p_theme_type), "A type associated with a built-in class cannot be marked as a variation of another type."); @@ -1243,7 +1036,7 @@ void Theme::set_type_variation(const StringName &p_theme_type, const StringName variation_map[p_theme_type] = p_base_type; variation_base_map[p_base_type].push_back(p_theme_type); - _emit_theme_changed(); + _emit_theme_changed(true); } bool Theme::is_type_variation(const StringName &p_theme_type, const StringName &p_base_type) const { @@ -1257,7 +1050,7 @@ void Theme::clear_type_variation(const StringName &p_theme_type) { variation_base_map[base_type].erase(p_theme_type); variation_map.erase(p_theme_type); - _emit_theme_changed(); + _emit_theme_changed(true); } StringName Theme::get_type_variation_base(const StringName &p_theme_type) const { @@ -1287,67 +1080,355 @@ void Theme::get_type_variation_list(const StringName &p_base_type, List<StringNa } } -void Theme::_freeze_change_propagation() { - no_change_propagation = true; -} +// Theme types. +void Theme::get_type_list(List<StringName> *p_list) const { + ERR_FAIL_NULL(p_list); -void Theme::_unfreeze_and_propagate_changes() { - no_change_propagation = false; - _emit_theme_changed(); + Set<StringName> types; + const StringName *key = nullptr; + + // Icons. + while ((key = icon_map.next(key))) { + types.insert(*key); + } + + key = nullptr; + + // StyleBoxes. + while ((key = style_map.next(key))) { + types.insert(*key); + } + + key = nullptr; + + // Fonts. + while ((key = font_map.next(key))) { + types.insert(*key); + } + + key = nullptr; + + // Font sizes. + while ((key = font_size_map.next(key))) { + types.insert(*key); + } + + key = nullptr; + + // Colors. + while ((key = color_map.next(key))) { + types.insert(*key); + } + + key = nullptr; + + // Constants. + while ((key = constant_map.next(key))) { + types.insert(*key); + } + + for (Set<StringName>::Element *E = types.front(); E; E = E->next()) { + p_list->push_back(E->get()); + } } -void Theme::clear() { - // These items need disconnecting. - { - const StringName *K = nullptr; - while ((K = icon_map.next(K))) { - const StringName *L = nullptr; - while ((L = icon_map[*K].next(L))) { - Ref<Texture2D> icon = icon_map[*K][*L]; - if (icon.is_valid()) { - icon->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); - } +void Theme::get_type_dependencies(const StringName &p_base_type, const StringName &p_type_variation, List<StringName> *p_list) { + ERR_FAIL_NULL(p_list); + + // Build the dependency chain for type variations. + if (p_type_variation != StringName()) { + StringName variation_name = p_type_variation; + while (variation_name != StringName()) { + p_list->push_back(variation_name); + variation_name = get_type_variation_base(variation_name); + + // If we have reached the base type dependency, it's safe to stop (assuming no funny business was done to the Theme). + if (variation_name == p_base_type) { + break; } } } - { - const StringName *K = nullptr; - while ((K = style_map.next(K))) { - const StringName *L = nullptr; - while ((L = style_map[*K].next(L))) { - Ref<StyleBox> style = style_map[*K][*L]; - if (style.is_valid()) { - style->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); - } - } - } + // Continue building the chain using native class hierarchy. + StringName class_name = p_base_type; + while (class_name != StringName()) { + p_list->push_back(class_name); + class_name = ClassDB::get_parent_class_nocheck(class_name); } +} - { - const StringName *K = nullptr; - while ((K = font_map.next(K))) { - const StringName *L = nullptr; - while ((L = font_map[*K].next(L))) { - Ref<Font> font = font_map[*K][*L]; - if (font.is_valid()) { - font->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); - } - } - } +// Internal methods for getting lists as a Vector of String (compatible with public API). +Vector<String> Theme::_get_icon_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_icon_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); } + return ilret; +} - icon_map.clear(); - style_map.clear(); - font_map.clear(); - font_size_map.clear(); - color_map.clear(); - constant_map.clear(); +Vector<String> Theme::_get_icon_type_list() const { + Vector<String> ilret; + List<StringName> il; - variation_map.clear(); - variation_base_map.clear(); + get_icon_type_list(&il); + ilret.resize(il.size()); - _emit_theme_changed(); + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_stylebox_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_stylebox_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_stylebox_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_stylebox_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_font_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_font_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_font_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_font_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_font_size_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_font_size_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_font_size_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_font_size_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_color_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_color_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_color_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_color_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_constant_list(const String &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_constant_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_constant_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_constant_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_theme_item_list(DataType p_data_type, const String &p_theme_type) const { + switch (p_data_type) { + case DATA_TYPE_COLOR: + return _get_color_list(p_theme_type); + case DATA_TYPE_CONSTANT: + return _get_constant_list(p_theme_type); + case DATA_TYPE_FONT: + return _get_font_list(p_theme_type); + case DATA_TYPE_FONT_SIZE: + return _get_font_size_list(p_theme_type); + case DATA_TYPE_ICON: + return _get_icon_list(p_theme_type); + case DATA_TYPE_STYLEBOX: + return _get_stylebox_list(p_theme_type); + case DATA_TYPE_MAX: + break; // Can't happen, but silences warning. + } + + return Vector<String>(); +} + +Vector<String> Theme::_get_theme_item_type_list(DataType p_data_type) const { + switch (p_data_type) { + case DATA_TYPE_COLOR: + return _get_color_type_list(); + case DATA_TYPE_CONSTANT: + return _get_constant_type_list(); + case DATA_TYPE_FONT: + return _get_font_type_list(); + case DATA_TYPE_FONT_SIZE: + return _get_font_size_type_list(); + case DATA_TYPE_ICON: + return _get_icon_type_list(); + case DATA_TYPE_STYLEBOX: + return _get_stylebox_type_list(); + case DATA_TYPE_MAX: + break; // Can't happen, but silences warning. + } + + return Vector<String>(); +} + +Vector<String> Theme::_get_type_variation_list(const StringName &p_theme_type) const { + Vector<String> ilret; + List<StringName> il; + + get_type_variation_list(p_theme_type, &il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +Vector<String> Theme::_get_type_list() const { + Vector<String> ilret; + List<StringName> il; + + get_type_list(&il); + ilret.resize(il.size()); + + int i = 0; + String *w = ilret.ptrw(); + for (List<StringName>::Element *E = il.front(); E; E = E->next(), i++) { + w[i] = E->get(); + } + return ilret; +} + +// Theme bulk manipulations. +void Theme::_emit_theme_changed(bool p_notify_list_changed) { + if (no_change_propagation) { + return; + } + + if (p_notify_list_changed) { + notify_property_list_changed(); + } + emit_changed(); +} + +void Theme::_freeze_change_propagation() { + no_change_propagation = true; +} + +void Theme::_unfreeze_and_propagate_changes() { + no_change_propagation = false; + _emit_theme_changed(true); } void Theme::merge_with(const Ref<Theme> &p_other) { @@ -1434,80 +1515,58 @@ void Theme::merge_with(const Ref<Theme> &p_other) { _unfreeze_and_propagate_changes(); } -void Theme::get_type_list(List<StringName> *p_list) const { - ERR_FAIL_NULL(p_list); - - Set<StringName> types; - const StringName *key = nullptr; - - // Icons. - while ((key = icon_map.next(key))) { - types.insert(*key); - } - - key = nullptr; - - // StyleBoxes. - while ((key = style_map.next(key))) { - types.insert(*key); - } - - key = nullptr; - - // Fonts. - while ((key = font_map.next(key))) { - types.insert(*key); - } - - key = nullptr; - - // Font sizes. - while ((key = font_size_map.next(key))) { - types.insert(*key); - } - - key = nullptr; - - // Colors. - while ((key = color_map.next(key))) { - types.insert(*key); - } - - key = nullptr; - - // Constants. - while ((key = constant_map.next(key))) { - types.insert(*key); +void Theme::clear() { + // These items need disconnecting. + { + const StringName *K = nullptr; + while ((K = icon_map.next(K))) { + const StringName *L = nullptr; + while ((L = icon_map[*K].next(L))) { + Ref<Texture2D> icon = icon_map[*K][*L]; + if (icon.is_valid()) { + icon->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); + } + } + } } - for (Set<StringName>::Element *E = types.front(); E; E = E->next()) { - p_list->push_back(E->get()); + { + const StringName *K = nullptr; + while ((K = style_map.next(K))) { + const StringName *L = nullptr; + while ((L = style_map[*K].next(L))) { + Ref<StyleBox> style = style_map[*K][*L]; + if (style.is_valid()) { + style->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); + } + } + } } -} -void Theme::get_type_dependencies(const StringName &p_base_type, const StringName &p_type_variation, List<StringName> *p_list) { - ERR_FAIL_NULL(p_list); - - // Build the dependency chain for type variations. - if (p_type_variation != StringName()) { - StringName variation_name = p_type_variation; - while (variation_name != StringName()) { - p_list->push_back(variation_name); - variation_name = get_type_variation_base(variation_name); - - // If we have reached the base type dependency, it's safe to stop (assuming no funny business was done to the Theme). - if (variation_name == p_base_type) { - break; + { + const StringName *K = nullptr; + while ((K = font_map.next(K))) { + const StringName *L = nullptr; + while ((L = font_map[*K].next(L))) { + Ref<Font> font = font_map[*K][*L]; + if (font.is_valid()) { + font->disconnect("changed", callable_mp(this, &Theme::_emit_theme_changed)); + } } } } - // Continue building the chain using native class hierarchy. - StringName class_name = p_base_type; - while (class_name != StringName()) { - p_list->push_back(class_name); - class_name = ClassDB::get_parent_class_nocheck(class_name); - } + icon_map.clear(); + style_map.clear(); + font_map.clear(); + font_size_map.clear(); + color_map.clear(); + constant_map.clear(); + + variation_map.clear(); + variation_base_map.clear(); + + _emit_theme_changed(true); } void Theme::reset_state() { @@ -1563,11 +1622,17 @@ void Theme::_bind_methods() { ClassDB::bind_method(D_METHOD("get_constant_list", "theme_type"), &Theme::_get_constant_list); ClassDB::bind_method(D_METHOD("get_constant_type_list"), &Theme::_get_constant_type_list); + ClassDB::bind_method(D_METHOD("set_default_base_scale", "font_size"), &Theme::set_default_theme_base_scale); + ClassDB::bind_method(D_METHOD("get_default_base_scale"), &Theme::get_default_theme_base_scale); + ClassDB::bind_method(D_METHOD("has_default_base_scale"), &Theme::has_default_theme_base_scale); + ClassDB::bind_method(D_METHOD("set_default_font", "font"), &Theme::set_default_theme_font); ClassDB::bind_method(D_METHOD("get_default_font"), &Theme::get_default_theme_font); + ClassDB::bind_method(D_METHOD("has_default_font"), &Theme::has_default_theme_font); ClassDB::bind_method(D_METHOD("set_default_font_size", "font_size"), &Theme::set_default_theme_font_size); ClassDB::bind_method(D_METHOD("get_default_font_size"), &Theme::get_default_theme_font_size); + ClassDB::bind_method(D_METHOD("has_default_font_size"), &Theme::has_default_theme_font_size); ClassDB::bind_method(D_METHOD("set_theme_item", "data_type", "name", "theme_type", "value"), &Theme::set_theme_item); ClassDB::bind_method(D_METHOD("get_theme_item", "data_type", "name", "theme_type"), &Theme::get_theme_item); @@ -1588,6 +1653,7 @@ void Theme::_bind_methods() { ClassDB::bind_method(D_METHOD("merge_with", "other"), &Theme::merge_with); ClassDB::bind_method(D_METHOD("clear"), &Theme::clear); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "default_base_scale", PROPERTY_HINT_RANGE, "0.0,2.0,0.01,or_greater"), "set_default_base_scale", "get_default_base_scale"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "default_font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_default_font", "get_default_font"); ADD_PROPERTY(PropertyInfo(Variant::INT, "default_font_size"), "set_default_font_size", "get_default_font_size"); diff --git a/scene/resources/theme.h b/scene/resources/theme.h index 15f21b91b8..d170d53ae3 100644 --- a/scene/resources/theme.h +++ b/scene/resources/theme.h @@ -61,7 +61,7 @@ public: private: bool no_change_propagation = false; - void _emit_theme_changed(); + void _emit_theme_changed(bool p_notify_list_changed = false); HashMap<StringName, HashMap<StringName, Ref<Texture2D>>> icon_map; HashMap<StringName, HashMap<StringName, Ref<StyleBox>>> style_map; @@ -96,13 +96,19 @@ protected: bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List<PropertyInfo> *p_list) const; - static Ref<Theme> project_default_theme; + // Universal Theme resources used when no other theme has the item. static Ref<Theme> default_theme; + static Ref<Theme> project_default_theme; + + // Universal default values, final fallback for every theme. + static float default_base_scale; static Ref<Texture2D> default_icon; static Ref<StyleBox> default_style; static Ref<Font> default_font; static int default_font_size; + // Default values configurable for each individual theme. + float default_theme_base_scale = 0.0; Ref<Font> default_theme_font; int default_theme_font_size = -1; @@ -120,16 +126,23 @@ public: static Ref<Theme> get_project_default(); static void set_project_default(const Ref<Theme> &p_project_default); + static void set_default_base_scale(float p_base_scale); static void set_default_icon(const Ref<Texture2D> &p_icon); static void set_default_style(const Ref<StyleBox> &p_style); static void set_default_font(const Ref<Font> &p_font); static void set_default_font_size(int p_font_size); + void set_default_theme_base_scale(float p_base_scale); + float get_default_theme_base_scale() const; + bool has_default_theme_base_scale() const; + void set_default_theme_font(const Ref<Font> &p_default_font); Ref<Font> get_default_theme_font() const; + bool has_default_theme_font() const; void set_default_theme_font_size(int p_font_size); int get_default_theme_font_size() const; + bool has_default_theme_font_size() const; void set_icon(const StringName &p_name, const StringName &p_theme_type, const Ref<Texture2D> &p_icon); Ref<Texture2D> get_icon(const StringName &p_name, const StringName &p_theme_type) const; diff --git a/scene/scene_string_names.cpp b/scene/scene_string_names.cpp index 23d257d9af..186764e69e 100644 --- a/scene/scene_string_names.cpp +++ b/scene/scene_string_names.cpp @@ -75,6 +75,7 @@ SceneStringNames::SceneStringNames() { focus_entered = StaticCString::create("focus_entered"); focus_exited = StaticCString::create("focus_exited"); + pre_sort_children = StaticCString::create("pre_sort_children"); sort_children = StaticCString::create("sort_children"); body_shape_entered = StaticCString::create("body_shape_entered"); diff --git a/scene/scene_string_names.h b/scene/scene_string_names.h index cf116aa140..67007c85e0 100644 --- a/scene/scene_string_names.h +++ b/scene/scene_string_names.h @@ -89,6 +89,7 @@ public: StringName focus_entered; StringName focus_exited; + StringName pre_sort_children; StringName sort_children; StringName finished; diff --git a/servers/physics_2d/body_direct_state_2d_sw.cpp b/servers/physics_2d/body_direct_state_2d_sw.cpp index 1c6adfe27c..b0673b9006 100644 --- a/servers/physics_2d/body_direct_state_2d_sw.cpp +++ b/servers/physics_2d/body_direct_state_2d_sw.cpp @@ -59,7 +59,7 @@ real_t PhysicsDirectBodyState2DSW::get_inverse_inertia() const { } void PhysicsDirectBodyState2DSW::set_linear_velocity(const Vector2 &p_velocity) { - body->set_active(true); + body->wakeup(); body->set_linear_velocity(p_velocity); } @@ -68,7 +68,7 @@ Vector2 PhysicsDirectBodyState2DSW::get_linear_velocity() const { } void PhysicsDirectBodyState2DSW::set_angular_velocity(real_t p_velocity) { - body->set_active(true); + body->wakeup(); body->set_angular_velocity(p_velocity); } @@ -89,32 +89,32 @@ Vector2 PhysicsDirectBodyState2DSW::get_velocity_at_local_position(const Vector2 } void PhysicsDirectBodyState2DSW::add_central_force(const Vector2 &p_force) { - body->set_active(true); + body->wakeup(); body->add_central_force(p_force); } void PhysicsDirectBodyState2DSW::add_force(const Vector2 &p_force, const Vector2 &p_position) { - body->set_active(true); + body->wakeup(); body->add_force(p_force, p_position); } void PhysicsDirectBodyState2DSW::add_torque(real_t p_torque) { - body->set_active(true); + body->wakeup(); body->add_torque(p_torque); } void PhysicsDirectBodyState2DSW::apply_central_impulse(const Vector2 &p_impulse) { - body->set_active(true); + body->wakeup(); body->apply_central_impulse(p_impulse); } void PhysicsDirectBodyState2DSW::apply_impulse(const Vector2 &p_impulse, const Vector2 &p_position) { - body->set_active(true); + body->wakeup(); body->apply_impulse(p_impulse, p_position); } void PhysicsDirectBodyState2DSW::apply_torque_impulse(real_t p_torque) { - body->set_active(true); + body->wakeup(); body->apply_torque_impulse(p_torque); } diff --git a/servers/physics_2d/physics_server_2d_sw.cpp b/servers/physics_2d/physics_server_2d_sw.cpp index 4315b55df4..c2205e33b0 100644 --- a/servers/physics_2d/physics_server_2d_sw.cpp +++ b/servers/physics_2d/physics_server_2d_sw.cpp @@ -948,7 +948,7 @@ void PhysicsServer2DSW::body_set_pickable(RID p_body, bool p_pickable) { body->set_pickable(p_pickable); } -bool PhysicsServer2DSW::body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, MotionResult *r_result, bool p_collide_separation_ray, const Set<RID> &p_exclude) { +bool PhysicsServer2DSW::body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result) { Body2DSW *body = body_owner.get_or_null(p_body); ERR_FAIL_COND_V(!body, false); ERR_FAIL_COND_V(!body->get_space(), false); @@ -956,7 +956,7 @@ bool PhysicsServer2DSW::body_test_motion(RID p_body, const Transform2D &p_from, _update_shapes(); - return body->get_space()->test_body_motion(body, p_from, p_motion, p_margin, r_result, p_collide_separation_ray, p_exclude); + return body->get_space()->test_body_motion(body, p_parameters, r_result); } PhysicsDirectBodyState2D *PhysicsServer2DSW::body_get_direct_state(RID p_body) { diff --git a/servers/physics_2d/physics_server_2d_sw.h b/servers/physics_2d/physics_server_2d_sw.h index 1f35e83995..b8e375a087 100644 --- a/servers/physics_2d/physics_server_2d_sw.h +++ b/servers/physics_2d/physics_server_2d_sw.h @@ -246,7 +246,7 @@ public: virtual void body_set_pickable(RID p_body, bool p_pickable) override; - virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.08, MotionResult *r_result = nullptr, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) override; + virtual bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override; // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState2D *body_get_direct_state(RID p_body) override; diff --git a/servers/physics_2d/physics_server_2d_wrap_mt.h b/servers/physics_2d/physics_server_2d_wrap_mt.h index 7925344d76..8d9e366661 100644 --- a/servers/physics_2d/physics_server_2d_wrap_mt.h +++ b/servers/physics_2d/physics_server_2d_wrap_mt.h @@ -254,9 +254,9 @@ public: FUNC2(body_set_pickable, RID, bool); - bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.08, MotionResult *r_result = nullptr, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) override { + bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override { ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false); - return physics_2d_server->body_test_motion(p_body, p_from, p_motion, p_margin, r_result, p_collide_separation_ray, p_exclude); + return physics_2d_server->body_test_motion(p_body, p_parameters, r_result); } // this function only works on physics process, errors and returns null otherwise diff --git a/servers/physics_2d/space_2d_sw.cpp b/servers/physics_2d/space_2d_sw.cpp index 5cd9bf3223..dd0780b5ff 100644 --- a/servers/physics_2d/space_2d_sw.cpp +++ b/servers/physics_2d/space_2d_sw.cpp @@ -525,7 +525,7 @@ int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb) { return amount; } -bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, PhysicsServer2D::MotionResult *r_result, bool p_collide_separation_ray, const Set<RID> &p_exclude) { +bool Space2DSW::test_body_motion(Body2DSW *p_body, const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult *r_result) { //give me back regular physics engine logic //this is madness //and most people using this function will think @@ -557,25 +557,25 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co if (!shapes_found) { if (r_result) { *r_result = PhysicsServer2D::MotionResult(); - r_result->travel = p_motion; + r_result->travel = p_parameters.motion; } return false; } // Undo the currently transform the physics server is aware of and apply the provided one - body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb)); - body_aabb = body_aabb.grow(p_margin); + body_aabb = p_parameters.from.xform(p_body->get_inv_transform().xform(body_aabb)); + body_aabb = body_aabb.grow(p_parameters.margin); static const int max_excluded_shape_pairs = 32; ExcludedShapeSW excluded_shape_pairs[max_excluded_shape_pairs]; int excluded_shape_pair_count = 0; - real_t min_contact_depth = p_margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR; + real_t min_contact_depth = p_parameters.margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR; - real_t motion_length = p_motion.length(); - Vector2 motion_normal = p_motion / motion_length; + real_t motion_length = p_parameters.motion.length(); + Vector2 motion_normal = p_parameters.motion / motion_length; - Transform2D body_transform = p_from; + Transform2D body_transform = p_parameters.from; bool recovered = false; @@ -612,7 +612,10 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co for (int i = 0; i < amount; i++) { const CollisionObject2DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } @@ -624,7 +627,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized(); real_t owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx); - cbk.valid_depth = MAX(owc_margin, p_margin); //user specified, but never less than actual margin or it won't work + cbk.valid_depth = MAX(owc_margin, p_parameters.margin); //user specified, but never less than actual margin or it won't work cbk.invalid_by_dir = 0; if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { @@ -649,7 +652,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co bool did_collide = false; Shape2DSW *against_shape = col_obj->get_shape(shape_idx); - if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, p_margin)) { + if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, nullptr, p_parameters.margin)) { did_collide = cbk.passed > current_passed; //more passed, so collision actually existed } @@ -714,7 +717,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co // STEP 2 ATTEMPT MOTION Rect2 motion_aabb = body_aabb; - motion_aabb.position += p_motion; + motion_aabb.position += p_parameters.motion; motion_aabb = motion_aabb.merge(body_aabb); int amount = _cull_aabb_for_body(p_body, motion_aabb); @@ -728,7 +731,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co // Colliding separation rays allows to properly snap to the ground, // otherwise it's not needed in regular motion. - if (!p_collide_separation_ray && (body_shape->get_type() == PhysicsServer2D::SHAPE_SEPARATION_RAY)) { + if (!p_parameters.collide_separation_ray && (body_shape->get_type() == PhysicsServer2D::SHAPE_SEPARATION_RAY)) { // When slide on slope is on, separation ray shape acts like a regular shape. if (!static_cast<SeparationRayShape2DSW *>(body_shape)->get_slide_on_slope()) { continue; @@ -744,9 +747,13 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co for (int i = 0; i < amount; i++) { const CollisionObject2DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } + int col_shape_idx = intersection_query_subindex_results[i]; Shape2DSW *against_shape = col_obj->get_shape(col_shape_idx); @@ -765,7 +772,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(col_shape_idx); //test initial overlap, does it collide if going all the way? - if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) { + if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_parameters.motion, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, nullptr, 0)) { continue; } @@ -790,7 +797,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co real_t fraction = low + (hi - low) * fraction_coeff; Vector2 sep = motion_normal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * fraction, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, &sep, 0); + bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_parameters.motion * fraction, against_shape, col_obj_shape_xform, Vector2(), nullptr, nullptr, &sep, 0); if (collided) { hi = fraction; @@ -827,7 +834,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co cbk.valid_depth = 10e20; Vector2 sep = motion_normal; //important optimization for this to work fast enough - bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(col_shape_idx), col_obj_shape_xform, Vector2(), PhysicsServer2DSW::_shape_col_cbk, &cbk, &sep, 0); + bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_parameters.motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(col_shape_idx), col_obj_shape_xform, Vector2(), PhysicsServer2DSW::_shape_col_cbk, &cbk, &sep, 0); if (!collided || cbk.amount == 0) { continue; } @@ -865,7 +872,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co //it collided, let's get the rest info in unsafe advance Transform2D ugt = body_transform; - ugt.elements[2] += p_motion * unsafe; + ugt.elements[2] += p_parameters.motion * unsafe; _RestCallbackData2D rcd; rcd.best_len = 0; @@ -886,13 +893,16 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co Transform2D body_shape_xform = ugt * p_body->get_shape_transform(j); Shape2DSW *body_shape = p_body->get_shape(j); - body_aabb.position += p_motion * unsafe; + body_aabb.position += p_parameters.motion * unsafe; int amount = _cull_aabb_for_body(p_body, body_aabb); for (int i = 0; i < amount; i++) { const CollisionObject2DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } @@ -917,7 +927,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co rcd.valid_dir = col_obj_shape_xform.get_axis(1).normalized(); real_t owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx); - rcd.valid_depth = MAX(owc_margin, p_margin); //user specified, but never less than actual margin or it won't work + rcd.valid_depth = MAX(owc_margin, p_parameters.margin); //user specified, but never less than actual margin or it won't work if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) { const Body2DSW *b = static_cast<const Body2DSW *>(col_obj); @@ -939,7 +949,7 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co rcd.object = col_obj; rcd.shape = shape_idx; rcd.local_shape = j; - bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), _rest_cbk_result, &rcd, nullptr, p_margin); + bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), _rest_cbk_result, &rcd, nullptr, p_parameters.margin); if (!sc) { continue; } @@ -962,9 +972,9 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co Vector2 rel_vec = r_result->collision_point - (body->get_transform().get_origin() + body->get_center_of_mass()); r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity(); - r_result->travel = safe * p_motion; - r_result->remainder = p_motion - safe * p_motion; - r_result->travel += (body_transform.get_origin() - p_from.get_origin()); + r_result->travel = safe * p_parameters.motion; + r_result->remainder = p_parameters.motion - safe * p_parameters.motion; + r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin()); } collided = true; @@ -972,9 +982,9 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co } if (!collided && r_result) { - r_result->travel = p_motion; + r_result->travel = p_parameters.motion; r_result->remainder = Vector2(); - r_result->travel += (body_transform.get_origin() - p_from.get_origin()); + r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin()); } return collided; diff --git a/servers/physics_2d/space_2d_sw.h b/servers/physics_2d/space_2d_sw.h index a1a8a77ee4..746b5c6c9a 100644 --- a/servers/physics_2d/space_2d_sw.h +++ b/servers/physics_2d/space_2d_sw.h @@ -187,7 +187,7 @@ public: int get_collision_pairs() const { return collision_pairs; } - bool test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, PhysicsServer2D::MotionResult *r_result, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()); + bool test_body_motion(Body2DSW *p_body, const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult *r_result); void set_debug_contacts(int p_amount) { contact_debug.resize(p_amount); } _FORCE_INLINE_ bool is_debugging_contacts() const { return !contact_debug.is_empty(); } diff --git a/servers/physics_3d/body_direct_state_3d_sw.cpp b/servers/physics_3d/body_direct_state_3d_sw.cpp index e74baefc3a..d61a6ac8e4 100644 --- a/servers/physics_3d/body_direct_state_3d_sw.cpp +++ b/servers/physics_3d/body_direct_state_3d_sw.cpp @@ -66,7 +66,7 @@ Basis PhysicsDirectBodyState3DSW::get_inverse_inertia_tensor() const { } void PhysicsDirectBodyState3DSW::set_linear_velocity(const Vector3 &p_velocity) { - body->set_active(true); + body->wakeup(); body->set_linear_velocity(p_velocity); } @@ -75,7 +75,7 @@ Vector3 PhysicsDirectBodyState3DSW::get_linear_velocity() const { } void PhysicsDirectBodyState3DSW::set_angular_velocity(const Vector3 &p_velocity) { - body->set_active(true); + body->wakeup(); body->set_angular_velocity(p_velocity); } @@ -96,32 +96,32 @@ Vector3 PhysicsDirectBodyState3DSW::get_velocity_at_local_position(const Vector3 } void PhysicsDirectBodyState3DSW::add_central_force(const Vector3 &p_force) { - body->set_active(true); + body->wakeup(); body->add_central_force(p_force); } void PhysicsDirectBodyState3DSW::add_force(const Vector3 &p_force, const Vector3 &p_position) { - body->set_active(true); + body->wakeup(); body->add_force(p_force, p_position); } void PhysicsDirectBodyState3DSW::add_torque(const Vector3 &p_torque) { - body->set_active(true); + body->wakeup(); body->add_torque(p_torque); } void PhysicsDirectBodyState3DSW::apply_central_impulse(const Vector3 &p_impulse) { - body->set_active(true); + body->wakeup(); body->apply_central_impulse(p_impulse); } void PhysicsDirectBodyState3DSW::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) { - body->set_active(true); + body->wakeup(); body->apply_impulse(p_impulse, p_position); } void PhysicsDirectBodyState3DSW::apply_torque_impulse(const Vector3 &p_impulse) { - body->set_active(true); + body->wakeup(); body->apply_torque_impulse(p_impulse); } diff --git a/servers/physics_3d/physics_server_3d_sw.cpp b/servers/physics_3d/physics_server_3d_sw.cpp index 36f81e072d..b16e199a03 100644 --- a/servers/physics_3d/physics_server_3d_sw.cpp +++ b/servers/physics_3d/physics_server_3d_sw.cpp @@ -868,7 +868,7 @@ void PhysicsServer3DSW::body_set_ray_pickable(RID p_body, bool p_enable) { body->set_ray_pickable(p_enable); } -bool PhysicsServer3DSW::body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin, MotionResult *r_result, int p_max_collisions, bool p_collide_separation_ray, const Set<RID> &p_exclude) { +bool PhysicsServer3DSW::body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result) { Body3DSW *body = body_owner.get_or_null(p_body); ERR_FAIL_COND_V(!body, false); ERR_FAIL_COND_V(!body->get_space(), false); @@ -876,7 +876,7 @@ bool PhysicsServer3DSW::body_test_motion(RID p_body, const Transform3D &p_from, _update_shapes(); - return body->get_space()->test_body_motion(body, p_from, p_motion, p_margin, r_result, p_max_collisions, p_collide_separation_ray, p_exclude); + return body->get_space()->test_body_motion(body, p_parameters, r_result); } PhysicsDirectBodyState3D *PhysicsServer3DSW::body_get_direct_state(RID p_body) { diff --git a/servers/physics_3d/physics_server_3d_sw.h b/servers/physics_3d/physics_server_3d_sw.h index 106e260311..54a787198d 100644 --- a/servers/physics_3d/physics_server_3d_sw.h +++ b/servers/physics_3d/physics_server_3d_sw.h @@ -242,7 +242,7 @@ public: virtual void body_set_ray_pickable(RID p_body, bool p_enable) override; - virtual bool body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = nullptr, int p_max_collisions = 1, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) override; + virtual bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override; // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) override; diff --git a/servers/physics_3d/physics_server_3d_wrap_mt.h b/servers/physics_3d/physics_server_3d_wrap_mt.h index a86fb5a3d3..17d02addda 100644 --- a/servers/physics_3d/physics_server_3d_wrap_mt.h +++ b/servers/physics_3d/physics_server_3d_wrap_mt.h @@ -253,9 +253,9 @@ public: FUNC2(body_set_ray_pickable, RID, bool); - bool body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = nullptr, int p_max_collisions = 1, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) override { + bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override { ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false); - return physics_3d_server->body_test_motion(p_body, p_from, p_motion, p_margin, r_result, p_max_collisions, p_collide_separation_ray, p_exclude); + return physics_3d_server->body_test_motion(p_body, p_parameters, r_result); } // this function only works on physics process, errors and returns null otherwise diff --git a/servers/physics_3d/soft_body_3d_sw.cpp b/servers/physics_3d/soft_body_3d_sw.cpp index 5e8f8692ba..c9166810fe 100644 --- a/servers/physics_3d/soft_body_3d_sw.cpp +++ b/servers/physics_3d/soft_body_3d_sw.cpp @@ -318,11 +318,13 @@ void SoftBody3DSW::apply_nodes_transform(const Transform3D &p_transform) { } Vector3 SoftBody3DSW::get_vertex_position(int p_index) const { + ERR_FAIL_COND_V(p_index < 0, Vector3()); + if (soft_mesh.is_null()) { return Vector3(); } - ERR_FAIL_INDEX_V(p_index, (int)map_visual_to_physics.size(), Vector3()); + ERR_FAIL_COND_V(p_index >= (int)map_visual_to_physics.size(), Vector3()); uint32_t node_index = map_visual_to_physics[p_index]; ERR_FAIL_COND_V(node_index >= nodes.size(), Vector3()); @@ -330,11 +332,13 @@ Vector3 SoftBody3DSW::get_vertex_position(int p_index) const { } void SoftBody3DSW::set_vertex_position(int p_index, const Vector3 &p_position) { + ERR_FAIL_COND(p_index < 0); + if (soft_mesh.is_null()) { return; } - ERR_FAIL_INDEX(p_index, (int)map_visual_to_physics.size()); + ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size()); uint32_t node_index = map_visual_to_physics[p_index]; ERR_FAIL_COND(node_index >= nodes.size()); @@ -344,6 +348,8 @@ void SoftBody3DSW::set_vertex_position(int p_index, const Vector3 &p_position) { } void SoftBody3DSW::pin_vertex(int p_index) { + ERR_FAIL_COND(p_index < 0); + if (is_vertex_pinned(p_index)) { return; } @@ -351,7 +357,7 @@ void SoftBody3DSW::pin_vertex(int p_index) { pinned_vertices.push_back(p_index); if (!soft_mesh.is_null()) { - ERR_FAIL_INDEX(p_index, (int)map_visual_to_physics.size()); + ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size()); uint32_t node_index = map_visual_to_physics[p_index]; ERR_FAIL_COND(node_index >= nodes.size()); @@ -361,13 +367,15 @@ void SoftBody3DSW::pin_vertex(int p_index) { } void SoftBody3DSW::unpin_vertex(int p_index) { + ERR_FAIL_COND(p_index < 0); + uint32_t pinned_count = pinned_vertices.size(); for (uint32_t i = 0; i < pinned_count; ++i) { if (p_index == pinned_vertices[i]) { pinned_vertices.remove(i); if (!soft_mesh.is_null()) { - ERR_FAIL_INDEX(p_index, (int)map_visual_to_physics.size()); + ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size()); uint32_t node_index = map_visual_to_physics[p_index]; ERR_FAIL_COND(node_index >= nodes.size()); @@ -387,10 +395,10 @@ void SoftBody3DSW::unpin_all_vertices() { real_t inv_node_mass = nodes.size() * inv_total_mass; uint32_t pinned_count = pinned_vertices.size(); for (uint32_t i = 0; i < pinned_count; ++i) { - uint32_t vertex_index = pinned_vertices[i]; + int pinned_vertex = pinned_vertices[i]; - ERR_CONTINUE(vertex_index >= map_visual_to_physics.size()); - uint32_t node_index = map_visual_to_physics[vertex_index]; + ERR_CONTINUE(pinned_vertex >= (int)map_visual_to_physics.size()); + uint32_t node_index = map_visual_to_physics[pinned_vertex]; ERR_CONTINUE(node_index >= nodes.size()); Node &node = nodes[node_index]; @@ -402,6 +410,8 @@ void SoftBody3DSW::unpin_all_vertices() { } bool SoftBody3DSW::is_vertex_pinned(int p_index) const { + ERR_FAIL_COND_V(p_index < 0, false); + uint32_t pinned_count = pinned_vertices.size(); for (uint32_t i = 0; i < pinned_count; ++i) { if (p_index == pinned_vertices[i]) { diff --git a/servers/physics_3d/space_3d_sw.cpp b/servers/physics_3d/space_3d_sw.cpp index 369dad45eb..c88747c017 100644 --- a/servers/physics_3d/space_3d_sw.cpp +++ b/servers/physics_3d/space_3d_sw.cpp @@ -620,7 +620,7 @@ int Space3DSW::_cull_aabb_for_body(Body3DSW *p_body, const AABB &p_aabb) { return amount; } -bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin, PhysicsServer3D::MotionResult *r_result, int p_max_collisions, bool p_collide_separation_ray, const Set<RID> &p_exclude) { +bool Space3DSW::test_body_motion(Body3DSW *p_body, const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult *r_result) { //give me back regular physics engine logic //this is madness //and most people using this function will think @@ -628,7 +628,7 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co //this took about a week to get right.. //but is it right? who knows at this point.. - ERR_FAIL_INDEX_V(p_max_collisions, PhysicsServer3D::MotionResult::MAX_COLLISIONS, false); + ERR_FAIL_INDEX_V(p_parameters.max_collisions, PhysicsServer3D::MotionResult::MAX_COLLISIONS, false); if (r_result) { *r_result = PhysicsServer3D::MotionResult(); @@ -652,22 +652,22 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co if (!shapes_found) { if (r_result) { - r_result->travel = p_motion; + r_result->travel = p_parameters.motion; } return false; } // Undo the currently transform the physics server is aware of and apply the provided one - body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb)); - body_aabb = body_aabb.grow(p_margin); + body_aabb = p_parameters.from.xform(p_body->get_inv_transform().xform(body_aabb)); + body_aabb = body_aabb.grow(p_parameters.margin); - real_t min_contact_depth = p_margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR; + real_t min_contact_depth = p_parameters.margin * TEST_MOTION_MIN_CONTACT_DEPTH_FACTOR; - real_t motion_length = p_motion.length(); - Vector3 motion_normal = p_motion / motion_length; + real_t motion_length = p_parameters.motion.length(); + Vector3 motion_normal = p_parameters.motion / motion_length; - Transform3D body_transform = p_from; + Transform3D body_transform = p_parameters.from; bool recovered = false; @@ -701,13 +701,16 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co for (int i = 0; i < amount; i++) { const CollisionObject3DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } int shape_idx = intersection_query_subindex_results[i]; - if (CollisionSolver3DSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, nullptr, p_margin)) { + if (CollisionSolver3DSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, nullptr, p_parameters.margin)) { collided = cbk.amount > 0; } } @@ -757,7 +760,7 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co // STEP 2 ATTEMPT MOTION AABB motion_aabb = body_aabb; - motion_aabb.position += p_motion; + motion_aabb.position += p_parameters.motion; motion_aabb = motion_aabb.merge(body_aabb); int amount = _cull_aabb_for_body(p_body, motion_aabb); @@ -771,7 +774,7 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co // Colliding separation rays allows to properly snap to the ground, // otherwise it's not needed in regular motion. - if (!p_collide_separation_ray && (body_shape->get_type() == PhysicsServer3D::SHAPE_SEPARATION_RAY)) { + if (!p_parameters.collide_separation_ray && (body_shape->get_type() == PhysicsServer3D::SHAPE_SEPARATION_RAY)) { // When slide on slope is on, separation ray shape acts like a regular shape. if (!static_cast<SeparationRayShape3DSW *>(body_shape)->get_slide_on_slope()) { continue; @@ -783,7 +786,7 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co Transform3D body_shape_xform_inv = body_shape_xform.affine_inverse(); MotionShape3DSW mshape; mshape.shape = body_shape; - mshape.motion = body_shape_xform_inv.basis.xform(p_motion); + mshape.motion = body_shape_xform_inv.basis.xform(p_parameters.motion); bool stuck = false; @@ -792,7 +795,10 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co for (int i = 0; i < amount; i++) { const CollisionObject3DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } @@ -821,7 +827,7 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co for (int k = 0; k < 8; k++) { //steps should be customizable.. real_t fraction = low + (hi - low) * fraction_coeff; - mshape.motion = body_shape_xform_inv.basis.xform(p_motion * fraction); + mshape.motion = body_shape_xform_inv.basis.xform(p_parameters.motion * fraction); Vector3 lA, lB; Vector3 sep = motion_normal; //important optimization for this to work fast enough @@ -883,13 +889,13 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co //it collided, let's get the rest info in unsafe advance Transform3D ugt = body_transform; - ugt.origin += p_motion * unsafe; + ugt.origin += p_parameters.motion * unsafe; _RestResultData results[PhysicsServer3D::MotionResult::MAX_COLLISIONS]; _RestCallbackData rcd; - if (p_max_collisions > 1) { - rcd.max_results = p_max_collisions; + if (p_parameters.max_collisions > 1) { + rcd.max_results = p_parameters.max_collisions; rcd.other_results = results; } @@ -907,20 +913,24 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co Transform3D body_shape_xform = ugt * p_body->get_shape_transform(j); Shape3DSW *body_shape = p_body->get_shape(j); - body_aabb.position += p_motion * unsafe; + body_aabb.position += p_parameters.motion * unsafe; int amount = _cull_aabb_for_body(p_body, body_aabb); for (int i = 0; i < amount; i++) { const CollisionObject3DSW *col_obj = intersection_query_results[i]; - if (p_exclude.has(col_obj->get_self())) { + if (p_parameters.exclude_bodies.has(col_obj->get_self())) { + continue; + } + if (p_parameters.exclude_objects.has(col_obj->get_instance_id())) { continue; } + int shape_idx = intersection_query_subindex_results[i]; rcd.object = col_obj; rcd.shape = shape_idx; - bool sc = CollisionSolver3DSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, nullptr, p_margin); + bool sc = CollisionSolver3DSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, nullptr, p_parameters.margin); if (!sc) { continue; } @@ -948,12 +958,12 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co collision.collider_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(rel_vec); } - r_result->travel = safe * p_motion; - r_result->remainder = p_motion - safe * p_motion; - r_result->travel += (body_transform.get_origin() - p_from.get_origin()); + r_result->travel = safe * p_parameters.motion; + r_result->remainder = p_parameters.motion - safe * p_parameters.motion; + r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin()); - r_result->safe_fraction = safe; - r_result->unsafe_fraction = unsafe; + r_result->collision_safe_fraction = safe; + r_result->collision_unsafe_fraction = unsafe; r_result->collision_count = rcd.result_count; } @@ -963,12 +973,12 @@ bool Space3DSW::test_body_motion(Body3DSW *p_body, const Transform3D &p_from, co } if (!collided && r_result) { - r_result->travel = p_motion; + r_result->travel = p_parameters.motion; r_result->remainder = Vector3(); - r_result->travel += (body_transform.get_origin() - p_from.get_origin()); + r_result->travel += (body_transform.get_origin() - p_parameters.from.get_origin()); - r_result->safe_fraction = 1.0; - r_result->unsafe_fraction = 1.0; + r_result->collision_safe_fraction = 1.0; + r_result->collision_unsafe_fraction = 1.0; } return collided; diff --git a/servers/physics_3d/space_3d_sw.h b/servers/physics_3d/space_3d_sw.h index daa1244bf8..69cc3c4bbd 100644 --- a/servers/physics_3d/space_3d_sw.h +++ b/servers/physics_3d/space_3d_sw.h @@ -207,7 +207,7 @@ public: void set_elapsed_time(ElapsedTime p_time, uint64_t p_msec) { elapsed_time[p_time] = p_msec; } uint64_t get_elapsed_time(ElapsedTime p_time) const { return elapsed_time[p_time]; } - bool test_body_motion(Body3DSW *p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin, PhysicsServer3D::MotionResult *r_result, int p_max_collisions = 1, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()); + bool test_body_motion(Body3DSW *p_body, const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult *r_result); Space3DSW(); ~Space3DSW(); diff --git a/servers/physics_server_2d.cpp b/servers/physics_server_2d.cpp index 8e743e0dc0..fe2970912a 100644 --- a/servers/physics_server_2d.cpp +++ b/servers/physics_server_2d.cpp @@ -199,7 +199,7 @@ Vector<RID> PhysicsShapeQueryParameters2D::get_exclude() const { ret.resize(exclude.size()); int idx = 0; for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) { - ret.write[idx] = E->get(); + ret.write[idx++] = E->get(); } return ret; } @@ -412,6 +412,73 @@ void PhysicsDirectSpaceState2D::_bind_methods() { /////////////////////////////// +Vector<RID> PhysicsTestMotionParameters2D::get_exclude_bodies() const { + Vector<RID> exclude; + exclude.resize(parameters.exclude_bodies.size()); + + int body_index = 0; + for (RID body : parameters.exclude_bodies) { + exclude.write[body_index++] = body; + } + + return exclude; +} + +void PhysicsTestMotionParameters2D::set_exclude_bodies(const Vector<RID> &p_exclude) { + for (RID body : p_exclude) { + parameters.exclude_bodies.insert(body); + } +} + +Array PhysicsTestMotionParameters2D::get_exclude_objects() const { + Array exclude; + exclude.resize(parameters.exclude_objects.size()); + + int object_index = 0; + for (ObjectID object_id : parameters.exclude_objects) { + exclude[object_index++] = object_id; + } + + return exclude; +} + +void PhysicsTestMotionParameters2D::set_exclude_objects(const Array &p_exclude) { + for (int i = 0; i < p_exclude.size(); ++i) { + ObjectID object_id = p_exclude[i]; + ERR_CONTINUE(object_id.is_null()); + parameters.exclude_objects.insert(object_id); + } +} + +void PhysicsTestMotionParameters2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_from"), &PhysicsTestMotionParameters2D::get_from); + ClassDB::bind_method(D_METHOD("set_from"), &PhysicsTestMotionParameters2D::set_from); + + ClassDB::bind_method(D_METHOD("get_motion"), &PhysicsTestMotionParameters2D::get_motion); + ClassDB::bind_method(D_METHOD("set_motion"), &PhysicsTestMotionParameters2D::set_motion); + + ClassDB::bind_method(D_METHOD("get_margin"), &PhysicsTestMotionParameters2D::get_margin); + ClassDB::bind_method(D_METHOD("set_margin"), &PhysicsTestMotionParameters2D::set_margin); + + ClassDB::bind_method(D_METHOD("is_collide_separation_ray_enabled"), &PhysicsTestMotionParameters2D::is_collide_separation_ray_enabled); + ClassDB::bind_method(D_METHOD("set_collide_separation_ray_enabled"), &PhysicsTestMotionParameters2D::set_collide_separation_ray_enabled); + + ClassDB::bind_method(D_METHOD("get_exclude_bodies"), &PhysicsTestMotionParameters2D::get_exclude_bodies); + ClassDB::bind_method(D_METHOD("set_exclude_bodies"), &PhysicsTestMotionParameters2D::set_exclude_bodies); + + ClassDB::bind_method(D_METHOD("get_exclude_objects"), &PhysicsTestMotionParameters2D::get_exclude_objects); + ClassDB::bind_method(D_METHOD("set_exclude_objects"), &PhysicsTestMotionParameters2D::set_exclude_objects); + + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "from"), "set_from", "get_from"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion"), "set_motion", "get_motion"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin"), "set_margin", "get_margin"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_separation_ray"), "set_collide_separation_ray_enabled", "is_collide_separation_ray_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "exclude_bodies"), "set_exclude_bodies", "get_exclude_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "exclude_objects"), "set_exclude_objects", "get_exclude_objects"); +} + +/////////////////////////////// + Vector2 PhysicsTestMotionResult2D::get_travel() const { return result.travel; } @@ -448,6 +515,10 @@ int PhysicsTestMotionResult2D::get_collider_shape() const { return result.collider_shape; } +int PhysicsTestMotionResult2D::get_collision_local_shape() const { + return result.collision_local_shape; +} + real_t PhysicsTestMotionResult2D::get_collision_depth() const { return result.collision_depth; } @@ -470,36 +541,23 @@ void PhysicsTestMotionResult2D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_collider_rid"), &PhysicsTestMotionResult2D::get_collider_rid); ClassDB::bind_method(D_METHOD("get_collider"), &PhysicsTestMotionResult2D::get_collider); ClassDB::bind_method(D_METHOD("get_collider_shape"), &PhysicsTestMotionResult2D::get_collider_shape); + ClassDB::bind_method(D_METHOD("get_collision_local_shape"), &PhysicsTestMotionResult2D::get_collision_local_shape); ClassDB::bind_method(D_METHOD("get_collision_depth"), &PhysicsTestMotionResult2D::get_collision_depth); ClassDB::bind_method(D_METHOD("get_collision_safe_fraction"), &PhysicsTestMotionResult2D::get_collision_safe_fraction); ClassDB::bind_method(D_METHOD("get_collision_unsafe_fraction"), &PhysicsTestMotionResult2D::get_collision_unsafe_fraction); - - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "travel"), "", "get_travel"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "remainder"), "", "get_remainder"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "collision_point"), "", "get_collision_point"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "collision_normal"), "", "get_collision_normal"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "collider_velocity"), "", "get_collider_velocity"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id", PROPERTY_HINT_OBJECT_ID), "", "get_collider_id"); - ADD_PROPERTY(PropertyInfo(Variant::RID, "collider_rid"), "", "get_collider_rid"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_collider"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape"), "", "get_collider_shape"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_depth"), "", "get_collision_depth"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_safe_fraction"), "", "get_collision_safe_fraction"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_unsafe_fraction"), "", "get_collision_unsafe_fraction"); } /////////////////////////////////////// -bool PhysicsServer2D::_body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, const Ref<PhysicsTestMotionResult2D> &p_result, bool p_collide_separation_ray, const Vector<RID> &p_exclude) { - MotionResult *r = nullptr; +bool PhysicsServer2D::_body_test_motion(RID p_body, const Ref<PhysicsTestMotionParameters2D> &p_parameters, const Ref<PhysicsTestMotionResult2D> &p_result) { + ERR_FAIL_COND_V(!p_parameters.is_valid(), false); + + MotionResult *result_ptr = nullptr; if (p_result.is_valid()) { - r = p_result->get_result_ptr(); + result_ptr = p_result->get_result_ptr(); } - Set<RID> exclude; - for (int i = 0; i < p_exclude.size(); i++) { - exclude.insert(p_exclude[i]); - } - return body_test_motion(p_body, p_from, p_motion, p_margin, r, p_collide_separation_ray, exclude); + + return body_test_motion(p_body, p_parameters->get_parameters(), result_ptr); } void PhysicsServer2D::_bind_methods() { @@ -626,7 +684,7 @@ void PhysicsServer2D::_bind_methods() { ClassDB::bind_method(D_METHOD("body_set_force_integration_callback", "body", "callable", "userdata"), &PhysicsServer2D::body_set_force_integration_callback, DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("body_test_motion", "body", "from", "motion", "margin", "result", "collide_separation_ray", "exclude"), &PhysicsServer2D::_body_test_motion, DEFVAL(0.08), DEFVAL(Variant()), DEFVAL(false), DEFVAL(Array())); + ClassDB::bind_method(D_METHOD("body_test_motion", "body", "parameters", "result"), &PhysicsServer2D::_body_test_motion, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("body_get_direct_state", "body"), &PhysicsServer2D::body_get_direct_state); diff --git a/servers/physics_server_2d.h b/servers/physics_server_2d.h index ed0584aaa6..26e1411111 100644 --- a/servers/physics_server_2d.h +++ b/servers/physics_server_2d.h @@ -198,6 +198,7 @@ public: PhysicsDirectSpaceState2D(); }; +class PhysicsTestMotionParameters2D; class PhysicsTestMotionResult2D; class PhysicsServer2D : public Object { @@ -205,7 +206,7 @@ class PhysicsServer2D : public Object { static PhysicsServer2D *singleton; - virtual bool _body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.08, const Ref<PhysicsTestMotionResult2D> &p_result = Ref<PhysicsTestMotionResult2D>(), bool p_collide_separation_ray = false, const Vector<RID> &p_exclude = Vector<RID>()); + virtual bool _body_test_motion(RID p_body, const Ref<PhysicsTestMotionParameters2D> &p_parameters, const Ref<PhysicsTestMotionResult2D> &p_result = Ref<PhysicsTestMotionResult2D>()); protected: static void _bind_methods(); @@ -465,6 +466,22 @@ public: // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState2D *body_get_direct_state(RID p_body) = 0; + struct MotionParameters { + Transform2D from; + Vector2 motion; + real_t margin = 0.08; + bool collide_separation_ray = false; + Set<RID> exclude_bodies; + Set<ObjectID> exclude_objects; + + MotionParameters() {} + + MotionParameters(const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.08) : + from(p_from), + motion(p_motion), + margin(p_margin) {} + }; + struct MotionResult { Vector2 travel; Vector2 remainder; @@ -485,18 +502,7 @@ public: } }; - virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.08, MotionResult *r_result = nullptr, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) = 0; - - struct SeparationResult { - real_t collision_depth; - Vector2 collision_point; - Vector2 collision_normal; - Vector2 collider_velocity; - int collision_local_shape; - ObjectID collider_id; - RID collider; - int collider_shape; - }; + virtual bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) = 0; /* JOINT API */ @@ -579,11 +585,40 @@ public: ~PhysicsServer2D(); }; +class PhysicsTestMotionParameters2D : public RefCounted { + GDCLASS(PhysicsTestMotionParameters2D, RefCounted); + + PhysicsServer2D::MotionParameters parameters; + +protected: + static void _bind_methods(); + +public: + const PhysicsServer2D::MotionParameters &get_parameters() const { return parameters; } + + const Transform2D &get_from() const { return parameters.from; } + void set_from(const Transform2D &p_from) { parameters.from = p_from; } + + const Vector2 &get_motion() const { return parameters.motion; } + void set_motion(const Vector2 &p_motion) { parameters.motion = p_motion; } + + real_t get_margin() const { return parameters.margin; } + void set_margin(real_t p_margin) { parameters.margin = p_margin; } + + bool is_collide_separation_ray_enabled() const { return parameters.collide_separation_ray; } + void set_collide_separation_ray_enabled(bool p_enabled) { parameters.collide_separation_ray = p_enabled; } + + Vector<RID> get_exclude_bodies() const; + void set_exclude_bodies(const Vector<RID> &p_exclude); + + Array get_exclude_objects() const; + void set_exclude_objects(const Array &p_exclude); +}; + class PhysicsTestMotionResult2D : public RefCounted { GDCLASS(PhysicsTestMotionResult2D, RefCounted); PhysicsServer2D::MotionResult result; - friend class PhysicsServer2D; protected: static void _bind_methods(); @@ -601,6 +636,7 @@ public: RID get_collider_rid() const; Object *get_collider() const; int get_collider_shape() const; + int get_collision_local_shape() const; real_t get_collision_depth() const; real_t get_collision_safe_fraction() const; real_t get_collision_unsafe_fraction() const; diff --git a/servers/physics_server_3d.cpp b/servers/physics_server_3d.cpp index 9384cdc7b8..d66a8bfe0d 100644 --- a/servers/physics_server_3d.cpp +++ b/servers/physics_server_3d.cpp @@ -194,7 +194,7 @@ Vector<RID> PhysicsShapeQueryParameters3D::get_exclude() const { ret.resize(exclude.size()); int idx = 0; for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) { - ret.write[idx] = E->get(); + ret.write[idx++] = E->get(); } return ret; } @@ -362,6 +362,77 @@ void PhysicsDirectSpaceState3D::_bind_methods() { /////////////////////////////// +Vector<RID> PhysicsTestMotionParameters3D::get_exclude_bodies() const { + Vector<RID> exclude; + exclude.resize(parameters.exclude_bodies.size()); + + int body_index = 0; + for (RID body : parameters.exclude_bodies) { + exclude.write[body_index++] = body; + } + + return exclude; +} + +void PhysicsTestMotionParameters3D::set_exclude_bodies(const Vector<RID> &p_exclude) { + for (RID body : p_exclude) { + parameters.exclude_bodies.insert(body); + } +} + +Array PhysicsTestMotionParameters3D::get_exclude_objects() const { + Array exclude; + exclude.resize(parameters.exclude_objects.size()); + + int object_index = 0; + for (ObjectID object_id : parameters.exclude_objects) { + exclude[object_index++] = object_id; + } + + return exclude; +} + +void PhysicsTestMotionParameters3D::set_exclude_objects(const Array &p_exclude) { + for (int i = 0; i < p_exclude.size(); ++i) { + ObjectID object_id = p_exclude[i]; + ERR_CONTINUE(object_id.is_null()); + parameters.exclude_objects.insert(object_id); + } +} + +void PhysicsTestMotionParameters3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_from"), &PhysicsTestMotionParameters3D::get_from); + ClassDB::bind_method(D_METHOD("set_from"), &PhysicsTestMotionParameters3D::set_from); + + ClassDB::bind_method(D_METHOD("get_motion"), &PhysicsTestMotionParameters3D::get_motion); + ClassDB::bind_method(D_METHOD("set_motion"), &PhysicsTestMotionParameters3D::set_motion); + + ClassDB::bind_method(D_METHOD("get_margin"), &PhysicsTestMotionParameters3D::get_margin); + ClassDB::bind_method(D_METHOD("set_margin"), &PhysicsTestMotionParameters3D::set_margin); + + ClassDB::bind_method(D_METHOD("get_max_collisions"), &PhysicsTestMotionParameters3D::get_max_collisions); + ClassDB::bind_method(D_METHOD("set_max_collisions"), &PhysicsTestMotionParameters3D::set_max_collisions); + + ClassDB::bind_method(D_METHOD("is_collide_separation_ray_enabled"), &PhysicsTestMotionParameters3D::is_collide_separation_ray_enabled); + ClassDB::bind_method(D_METHOD("set_collide_separation_ray_enabled"), &PhysicsTestMotionParameters3D::set_collide_separation_ray_enabled); + + ClassDB::bind_method(D_METHOD("get_exclude_bodies"), &PhysicsTestMotionParameters3D::get_exclude_bodies); + ClassDB::bind_method(D_METHOD("set_exclude_bodies"), &PhysicsTestMotionParameters3D::set_exclude_bodies); + + ClassDB::bind_method(D_METHOD("get_exclude_objects"), &PhysicsTestMotionParameters3D::get_exclude_objects); + ClassDB::bind_method(D_METHOD("set_exclude_objects"), &PhysicsTestMotionParameters3D::set_exclude_objects); + + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "from"), "set_from", "get_from"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "motion"), "set_motion", "get_motion"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin"), "set_margin", "get_margin"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "max_collisions"), "set_max_collisions", "get_max_collisions"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_separation_ray"), "set_collide_separation_ray_enabled", "is_collide_separation_ray_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "exclude_bodies"), "set_exclude_bodies", "get_exclude_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "exclude_objects"), "set_exclude_objects", "get_exclude_objects"); +} + +/////////////////////////////// + Vector3 PhysicsTestMotionResult3D::get_travel() const { return result.travel; } @@ -370,12 +441,12 @@ Vector3 PhysicsTestMotionResult3D::get_remainder() const { return result.remainder; } -real_t PhysicsTestMotionResult3D::get_safe_fraction() const { - return result.safe_fraction; +real_t PhysicsTestMotionResult3D::get_collision_safe_fraction() const { + return result.collision_safe_fraction; } -real_t PhysicsTestMotionResult3D::get_unsafe_fraction() const { - return result.unsafe_fraction; +real_t PhysicsTestMotionResult3D::get_collision_unsafe_fraction() const { + return result.collision_unsafe_fraction; } int PhysicsTestMotionResult3D::get_collision_count() const { @@ -417,48 +488,21 @@ int PhysicsTestMotionResult3D::get_collider_shape(int p_collision_index) const { return result.collisions[p_collision_index].collider_shape; } +int PhysicsTestMotionResult3D::get_collision_local_shape(int p_collision_index) const { + ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, 0); + return result.collisions[p_collision_index].local_shape; +} + real_t PhysicsTestMotionResult3D::get_collision_depth(int p_collision_index) const { ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, 0.0); return result.collisions[p_collision_index].depth; } -Vector3 PhysicsTestMotionResult3D::get_best_collision_point() const { - return result.collision_count ? get_collision_point() : Vector3(); -} - -Vector3 PhysicsTestMotionResult3D::get_best_collision_normal() const { - return result.collision_count ? get_collision_normal() : Vector3(); -} - -Vector3 PhysicsTestMotionResult3D::get_best_collider_velocity() const { - return result.collision_count ? get_collider_velocity() : Vector3(); -} - -ObjectID PhysicsTestMotionResult3D::get_best_collider_id() const { - return result.collision_count ? get_collider_id() : ObjectID(); -} - -RID PhysicsTestMotionResult3D::get_best_collider_rid() const { - return result.collision_count ? get_collider_rid() : RID(); -} - -Object *PhysicsTestMotionResult3D::get_best_collider() const { - return result.collision_count ? get_collider() : nullptr; -} - -int PhysicsTestMotionResult3D::get_best_collider_shape() const { - return result.collision_count ? get_collider_shape() : 0; -} - -real_t PhysicsTestMotionResult3D::get_best_collision_depth() const { - return result.collision_count ? get_collision_depth() : 0.0; -} - void PhysicsTestMotionResult3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_travel"), &PhysicsTestMotionResult3D::get_travel); ClassDB::bind_method(D_METHOD("get_remainder"), &PhysicsTestMotionResult3D::get_remainder); - ClassDB::bind_method(D_METHOD("get_safe_fraction"), &PhysicsTestMotionResult3D::get_safe_fraction); - ClassDB::bind_method(D_METHOD("get_unsafe_fraction"), &PhysicsTestMotionResult3D::get_unsafe_fraction); + ClassDB::bind_method(D_METHOD("get_collision_safe_fraction"), &PhysicsTestMotionResult3D::get_collision_safe_fraction); + ClassDB::bind_method(D_METHOD("get_collision_unsafe_fraction"), &PhysicsTestMotionResult3D::get_collision_unsafe_fraction); ClassDB::bind_method(D_METHOD("get_collision_count"), &PhysicsTestMotionResult3D::get_collision_count); ClassDB::bind_method(D_METHOD("get_collision_point", "collision_index"), &PhysicsTestMotionResult3D::get_collision_point, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collision_normal", "collision_index"), &PhysicsTestMotionResult3D::get_collision_normal, DEFVAL(0)); @@ -467,44 +511,21 @@ void PhysicsTestMotionResult3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_collider_rid", "collision_index"), &PhysicsTestMotionResult3D::get_collider_rid, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collider", "collision_index"), &PhysicsTestMotionResult3D::get_collider, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collider_shape", "collision_index"), &PhysicsTestMotionResult3D::get_collider_shape, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("get_collision_local_shape", "collision_index"), &PhysicsTestMotionResult3D::get_collision_local_shape, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_collision_depth", "collision_index"), &PhysicsTestMotionResult3D::get_collision_depth, DEFVAL(0)); - - ClassDB::bind_method(D_METHOD("get_best_collision_point"), &PhysicsTestMotionResult3D::get_best_collision_point); - ClassDB::bind_method(D_METHOD("get_best_collision_normal"), &PhysicsTestMotionResult3D::get_best_collision_normal); - ClassDB::bind_method(D_METHOD("get_best_collider_velocity"), &PhysicsTestMotionResult3D::get_best_collider_velocity); - ClassDB::bind_method(D_METHOD("get_best_collider_id"), &PhysicsTestMotionResult3D::get_best_collider_id); - ClassDB::bind_method(D_METHOD("get_best_collider_rid"), &PhysicsTestMotionResult3D::get_best_collider_rid); - ClassDB::bind_method(D_METHOD("get_best_collider"), &PhysicsTestMotionResult3D::get_best_collider); - ClassDB::bind_method(D_METHOD("get_best_collider_shape"), &PhysicsTestMotionResult3D::get_best_collider_shape); - ClassDB::bind_method(D_METHOD("get_best_collision_depth"), &PhysicsTestMotionResult3D::get_best_collision_depth); - - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "travel"), "", "get_travel"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "remainder"), "", "get_remainder"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "safe_fraction"), "", "get_safe_fraction"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unsafe_fraction"), "", "get_unsafe_fraction"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_count"), "", "get_collision_count"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collision_point"), "", "get_best_collision_point"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collision_normal"), "", "get_best_collision_normal"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collider_velocity"), "", "get_best_collider_velocity"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id", PROPERTY_HINT_OBJECT_ID), "", "get_best_collider_id"); - ADD_PROPERTY(PropertyInfo(Variant::RID, "collider_rid"), "", "get_best_collider_rid"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_best_collider"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape"), "", "get_best_collider_shape"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_depth"), "", "get_best_collision_depth"); } /////////////////////////////////////// -bool PhysicsServer3D::_body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin, const Ref<PhysicsTestMotionResult3D> &p_result, bool p_collide_separation_ray, const Vector<RID> &p_exclude, int p_max_collisions) { - MotionResult *r = nullptr; +bool PhysicsServer3D::_body_test_motion(RID p_body, const Ref<PhysicsTestMotionParameters3D> &p_parameters, const Ref<PhysicsTestMotionResult3D> &p_result) { + ERR_FAIL_COND_V(!p_parameters.is_valid(), false); + + MotionResult *result_ptr = nullptr; if (p_result.is_valid()) { - r = p_result->get_result_ptr(); - } - Set<RID> exclude; - for (int i = 0; i < p_exclude.size(); i++) { - exclude.insert(p_exclude[i]); + result_ptr = p_result->get_result_ptr(); } - return body_test_motion(p_body, p_from, p_motion, p_margin, r, p_max_collisions, p_collide_separation_ray, exclude); + + return body_test_motion(p_body, p_parameters->get_parameters(), result_ptr); } RID PhysicsServer3D::shape_create(ShapeType p_shape) { @@ -662,7 +683,7 @@ void PhysicsServer3D::_bind_methods() { ClassDB::bind_method(D_METHOD("body_set_ray_pickable", "body", "enable"), &PhysicsServer3D::body_set_ray_pickable); - ClassDB::bind_method(D_METHOD("body_test_motion", "body", "from", "motion", "margin", "result", "collide_separation_ray", "exclude", "max_collisions"), &PhysicsServer3D::_body_test_motion, DEFVAL(0.001), DEFVAL(Variant()), DEFVAL(false), DEFVAL(Array()), DEFVAL(1)); + ClassDB::bind_method(D_METHOD("body_test_motion", "body", "parameters", "result"), &PhysicsServer3D::_body_test_motion, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("body_get_direct_state", "body"), &PhysicsServer3D::body_get_direct_state); diff --git a/servers/physics_server_3d.h b/servers/physics_server_3d.h index dbd734ba32..c609afc11e 100644 --- a/servers/physics_server_3d.h +++ b/servers/physics_server_3d.h @@ -203,6 +203,7 @@ public: virtual ~RenderingServerHandler() {} }; +class PhysicsTestMotionParameters3D; class PhysicsTestMotionResult3D; class PhysicsServer3D : public Object { @@ -210,7 +211,7 @@ class PhysicsServer3D : public Object { static PhysicsServer3D *singleton; - virtual bool _body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin = 0.001, const Ref<PhysicsTestMotionResult3D> &p_result = Ref<PhysicsTestMotionResult3D>(), bool p_collide_separation_ray = false, const Vector<RID> &p_exclude = Vector<RID>(), int p_max_collisions = 1); + virtual bool _body_test_motion(RID p_body, const Ref<PhysicsTestMotionParameters3D> &p_parameters, const Ref<PhysicsTestMotionResult3D> &p_result = Ref<PhysicsTestMotionResult3D>()); protected: static void _bind_methods(); @@ -483,6 +484,23 @@ public: // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) = 0; + struct MotionParameters { + Transform3D from; + Vector3 motion; + real_t margin = 0.001; + int max_collisions = 1; + bool collide_separation_ray = false; + Set<RID> exclude_bodies; + Set<ObjectID> exclude_objects; + + MotionParameters() {} + + MotionParameters(const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin = 0.001) : + from(p_from), + motion(p_motion), + margin(p_margin) {} + }; + struct MotionCollision { Vector3 position; Vector3 normal; @@ -501,15 +519,15 @@ public: struct MotionResult { Vector3 travel; Vector3 remainder; - real_t safe_fraction = 0.0; - real_t unsafe_fraction = 0.0; + real_t collision_safe_fraction = 0.0; + real_t collision_unsafe_fraction = 0.0; static const int MAX_COLLISIONS = 32; MotionCollision collisions[MAX_COLLISIONS]; int collision_count = 0; }; - virtual bool body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = nullptr, int p_max_collisions = 1, bool p_collide_separation_ray = false, const Set<RID> &p_exclude = Set<RID>()) = 0; + virtual bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) = 0; /* SOFT BODY */ @@ -760,11 +778,43 @@ public: ~PhysicsServer3D(); }; +class PhysicsTestMotionParameters3D : public RefCounted { + GDCLASS(PhysicsTestMotionParameters3D, RefCounted); + + PhysicsServer3D::MotionParameters parameters; + +protected: + static void _bind_methods(); + +public: + const PhysicsServer3D::MotionParameters &get_parameters() const { return parameters; } + + const Transform3D &get_from() const { return parameters.from; } + void set_from(const Transform3D &p_from) { parameters.from = p_from; } + + const Vector3 &get_motion() const { return parameters.motion; } + void set_motion(const Vector3 &p_motion) { parameters.motion = p_motion; } + + real_t get_margin() const { return parameters.margin; } + void set_margin(real_t p_margin) { parameters.margin = p_margin; } + + int get_max_collisions() const { return parameters.max_collisions; } + void set_max_collisions(int p_max_collisions) { parameters.max_collisions = p_max_collisions; } + + bool is_collide_separation_ray_enabled() const { return parameters.collide_separation_ray; } + void set_collide_separation_ray_enabled(bool p_enabled) { parameters.collide_separation_ray = p_enabled; } + + Vector<RID> get_exclude_bodies() const; + void set_exclude_bodies(const Vector<RID> &p_exclude); + + Array get_exclude_objects() const; + void set_exclude_objects(const Array &p_exclude); +}; + class PhysicsTestMotionResult3D : public RefCounted { GDCLASS(PhysicsTestMotionResult3D, RefCounted); PhysicsServer3D::MotionResult result; - friend class PhysicsServer3D; protected: static void _bind_methods(); @@ -774,8 +824,8 @@ public: Vector3 get_travel() const; Vector3 get_remainder() const; - real_t get_safe_fraction() const; - real_t get_unsafe_fraction() const; + real_t get_collision_safe_fraction() const; + real_t get_collision_unsafe_fraction() const; int get_collision_count() const; @@ -786,16 +836,8 @@ public: RID get_collider_rid(int p_collision_index = 0) const; Object *get_collider(int p_collision_index = 0) const; int get_collider_shape(int p_collision_index = 0) const; + int get_collision_local_shape(int p_collision_index = 0) const; real_t get_collision_depth(int p_collision_index = 0) const; - - Vector3 get_best_collision_point() const; - Vector3 get_best_collision_normal() const; - Vector3 get_best_collider_velocity() const; - ObjectID get_best_collider_id() const; - RID get_best_collider_rid() const; - Object *get_best_collider() const; - int get_best_collider_shape() const; - real_t get_best_collision_depth() const; }; typedef PhysicsServer3D *(*CreatePhysicsServer3DCallback)(); diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp index d5eccce88e..28cd8374c0 100644 --- a/servers/register_server_types.cpp +++ b/servers/register_server_types.cpp @@ -122,8 +122,6 @@ void register_server_types() { GDREGISTER_VIRTUAL_CLASS(RenderingServer); GDREGISTER_CLASS(AudioServer); - TextServer::initialize_hex_code_box_fonts(); - GDREGISTER_VIRTUAL_CLASS(PhysicsServer2D); GDREGISTER_VIRTUAL_CLASS(PhysicsServer3D); GDREGISTER_VIRTUAL_CLASS(NavigationServer2D); @@ -210,12 +208,14 @@ void register_server_types() { GDREGISTER_VIRTUAL_CLASS(PhysicsDirectBodyState2D); GDREGISTER_VIRTUAL_CLASS(PhysicsDirectSpaceState2D); + GDREGISTER_CLASS(PhysicsTestMotionParameters2D); GDREGISTER_CLASS(PhysicsTestMotionResult2D); GDREGISTER_CLASS(PhysicsShapeQueryParameters2D); GDREGISTER_CLASS(PhysicsShapeQueryParameters3D); GDREGISTER_VIRTUAL_CLASS(PhysicsDirectBodyState3D); GDREGISTER_VIRTUAL_CLASS(PhysicsDirectSpaceState3D); + GDREGISTER_CLASS(PhysicsTestMotionParameters3D); GDREGISTER_CLASS(PhysicsTestMotionResult3D); // Physics 2D @@ -239,7 +239,6 @@ void unregister_server_types() { NativeExtensionManager::get_singleton()->deinitialize_extensions(NativeExtension::INITIALIZATION_LEVEL_SERVERS); memdelete(shader_types); - TextServer::finish_hex_code_box_fonts(); } void register_server_singletons() { diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp index 0416b06d0d..a1c3481ed6 100644 --- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp @@ -373,7 +373,7 @@ void SceneShaderForwardClustered::ShaderData::get_instance_param_list(List<Rende p.info = ShaderLanguage::uniform_to_property_info(E.value); p.info.name = E.key; //supply name p.index = E.value.instance_index; - p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.hint); + p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint); p_param_list->push_back(p); } } @@ -398,7 +398,7 @@ Variant SceneShaderForwardClustered::ShaderData::get_default_parameter(const Str if (uniforms.has(p_parameter)) { ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter]; Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value; - return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint); } return Variant(); } diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp index 4118735cf2..16d650a540 100644 --- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp +++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp @@ -365,7 +365,7 @@ void SceneShaderForwardMobile::ShaderData::get_instance_param_list(List<Renderer p.info = ShaderLanguage::uniform_to_property_info(E.value); p.info.name = E.key; //supply name p.index = E.value.instance_index; - p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.hint); + p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint); p_param_list->push_back(p); } } @@ -390,7 +390,7 @@ Variant SceneShaderForwardMobile::ShaderData::get_default_parameter(const String if (uniforms.has(p_parameter)) { ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter]; Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value; - return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint); } return Variant(); } diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp index b792ec9971..c69c9eeadf 100644 --- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp @@ -2161,7 +2161,7 @@ void RendererCanvasRenderRD::ShaderData::get_instance_param_list(List<RendererSt p.info = ShaderLanguage::uniform_to_property_info(E.value); p.info.name = E.key; //supply name p.index = E.value.instance_index; - p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.hint); + p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint); p_param_list->push_back(p); } } @@ -2186,7 +2186,7 @@ Variant RendererCanvasRenderRD::ShaderData::get_default_parameter(const StringNa if (uniforms.has(p_parameter)) { ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter]; Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value; - return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint); } return Variant(); } diff --git a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp index 830b0e7bae..7925e735a0 100644 --- a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp @@ -177,7 +177,7 @@ void RendererSceneSkyRD::SkyShaderData::get_instance_param_list(List<RendererSto p.info = ShaderLanguage::uniform_to_property_info(E.value); p.info.name = E.key; //supply name p.index = E.value.instance_index; - p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.hint); + p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint); p_param_list->push_back(p); } } @@ -202,7 +202,7 @@ Variant RendererSceneSkyRD::SkyShaderData::get_default_parameter(const StringNam if (uniforms.has(p_parameter)) { ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter]; Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value; - return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint); } return Variant(); } diff --git a/servers/rendering/renderer_rd/renderer_storage_rd.cpp b/servers/rendering/renderer_rd/renderer_storage_rd.cpp index 5ef1f46742..771be4bb3d 100644 --- a/servers/rendering/renderer_rd/renderer_storage_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_storage_rd.cpp @@ -1691,73 +1691,183 @@ void RendererStorageRD::material_set_data_request_function(ShaderType p_shader_t material_data_request_func[p_shader_type] = p_function; } -_FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, const Variant &value, uint8_t *data, bool p_linear_color) { +_FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, int p_array_size, const Variant &value, uint8_t *data, bool p_linear_color) { switch (type) { case ShaderLanguage::TYPE_BOOL: { - bool v = value; - uint32_t *gui = (uint32_t *)data; - *gui = v ? 1 : 0; + + if (p_array_size > 0) { + const PackedInt32Array &ba = value; + int s = ba.size(); + const int *r = ba.ptr(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = (r[i] != 0) ? 1 : 0; + } else { + gui[j] = 0; + } + gui[j + 1] = 0; // ignored + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + bool v = value; + gui[0] = v ? 1 : 0; + } } break; case ShaderLanguage::TYPE_BVEC2: { - int v = value; uint32_t *gui = (uint32_t *)data; - gui[0] = v & 1 ? 1 : 0; - gui[1] = v & 2 ? 1 : 0; + if (p_array_size > 0) { + const PackedInt32Array &ba = value; + int s = ba.size(); + const int *r = ba.ptr(); + int count = 2 * p_array_size; + + for (int i = 0, j = 0; i < count; i += 2, j += 4) { + if (i < s) { + gui[j] = r[i] ? 1 : 0; + gui[j + 1] = r[i + 1] ? 1 : 0; + } else { + gui[j] = 0; + gui[j + 1] = 0; + } + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + int v = value; + gui[0] = v & 1 ? 1 : 0; + gui[1] = v & 2 ? 1 : 0; + } } break; case ShaderLanguage::TYPE_BVEC3: { - int v = value; uint32_t *gui = (uint32_t *)data; - gui[0] = (v & 1) ? 1 : 0; - gui[1] = (v & 2) ? 1 : 0; - gui[2] = (v & 4) ? 1 : 0; + if (p_array_size > 0) { + const PackedInt32Array &ba = value; + int s = ba.size(); + const int *r = ba.ptr(); + int count = 3 * p_array_size; + + for (int i = 0, j = 0; i < count; i += 3, j += 4) { + if (i < s) { + gui[j] = r[i] ? 1 : 0; + gui[j + 1] = r[i + 1] ? 1 : 0; + gui[j + 2] = r[i + 2] ? 1 : 0; + } else { + gui[j] = 0; + gui[j + 1] = 0; + gui[j + 2] = 0; + } + gui[j + 3] = 0; // ignored + } + } else { + int v = value; + gui[0] = (v & 1) ? 1 : 0; + gui[1] = (v & 2) ? 1 : 0; + gui[2] = (v & 4) ? 1 : 0; + } } break; case ShaderLanguage::TYPE_BVEC4: { - int v = value; uint32_t *gui = (uint32_t *)data; - gui[0] = (v & 1) ? 1 : 0; - gui[1] = (v & 2) ? 1 : 0; - gui[2] = (v & 4) ? 1 : 0; - gui[3] = (v & 8) ? 1 : 0; + if (p_array_size > 0) { + const PackedInt32Array &ba = value; + int s = ba.size(); + const int *r = ba.ptr(); + int count = 4 * p_array_size; + + for (int i = 0; i < count; i += 4) { + if (i < s) { + gui[i] = r[i] ? 1 : 0; + gui[i + 1] = r[i + 1] ? 1 : 0; + gui[i + 2] = r[i + 2] ? 1 : 0; + gui[i + 3] = r[i + 3] ? 1 : 0; + } else { + gui[i] = 0; + gui[i + 1] = 0; + gui[i + 2] = 0; + gui[i + 3] = 0; + } + } + } else { + int v = value; + gui[0] = (v & 1) ? 1 : 0; + gui[1] = (v & 2) ? 1 : 0; + gui[2] = (v & 4) ? 1 : 0; + gui[3] = (v & 8) ? 1 : 0; + } } break; case ShaderLanguage::TYPE_INT: { - int v = value; int32_t *gui = (int32_t *)data; - gui[0] = v; + if (p_array_size > 0) { + Vector<int> iv = value; + int s = iv.size(); + const int *r = iv.ptr(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = r[i]; + } else { + gui[j] = 0; + } + gui[j + 1] = 0; // ignored + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + int v = value; + gui[0] = v; + } } break; case ShaderLanguage::TYPE_IVEC2: { Vector<int> iv = value; int s = iv.size(); int32_t *gui = (int32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 2 * p_array_size; - for (int i = 0; i < 2; i++) { + const int *r = iv.ptr(); + for (int i = 0, j = 0; i < count; i += 2, j += 4) { if (i < s) { - gui[i] = r[i]; + gui[j] = r[i]; + gui[j + 1] = r[i + 1]; } else { - gui[i] = 0; + gui[j] = 0; + gui[j + 1] = 0; } + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored } - } break; case ShaderLanguage::TYPE_IVEC3: { Vector<int> iv = value; int s = iv.size(); int32_t *gui = (int32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 3 * p_array_size; - for (int i = 0; i < 3; i++) { + const int *r = iv.ptr(); + for (int i = 0, j = 0; i < count; i += 3, j += 4) { if (i < s) { - gui[i] = r[i]; + gui[j] = r[i]; + gui[j + 1] = r[i + 1]; + gui[j + 2] = r[i + 2]; } else { - gui[i] = 0; + gui[j] = 0; + gui[j + 1] = 0; + gui[j + 2] = 0; } + gui[j + 3] = 0; // ignored } } break; case ShaderLanguage::TYPE_IVEC4: { @@ -1765,35 +1875,70 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy int s = iv.size(); int32_t *gui = (int32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 4 * p_array_size; - for (int i = 0; i < 4; i++) { + const int *r = iv.ptr(); + for (int i = 0; i < count; i += 4) { if (i < s) { gui[i] = r[i]; + gui[i + 1] = r[i + 1]; + gui[i + 2] = r[i + 2]; + gui[i + 3] = r[i + 3]; } else { gui[i] = 0; + gui[i + 1] = 0; + gui[i + 2] = 0; + gui[i + 3] = 0; } } } break; case ShaderLanguage::TYPE_UINT: { - int v = value; uint32_t *gui = (uint32_t *)data; - gui[0] = v; + if (p_array_size > 0) { + Vector<int> iv = value; + int s = iv.size(); + const int *r = iv.ptr(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = r[i]; + } else { + gui[j] = 0; + } + gui[j + 1] = 0; // ignored + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + int v = value; + gui[0] = v; + } } break; case ShaderLanguage::TYPE_UVEC2: { Vector<int> iv = value; int s = iv.size(); uint32_t *gui = (uint32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 2 * p_array_size; - for (int i = 0; i < 2; i++) { + const int *r = iv.ptr(); + for (int i = 0, j = 0; i < count; i += 2, j += 4) { if (i < s) { - gui[i] = r[i]; + gui[j] = r[i]; + gui[j + 1] = r[i + 1]; } else { - gui[i] = 0; + gui[j] = 0; + gui[j + 1] = 0; } + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored } } break; case ShaderLanguage::TYPE_UVEC3: { @@ -1801,141 +1946,370 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy int s = iv.size(); uint32_t *gui = (uint32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 3 * p_array_size; - for (int i = 0; i < 3; i++) { + const int *r = iv.ptr(); + for (int i = 0, j = 0; i < count; i += 3, j += 4) { if (i < s) { - gui[i] = r[i]; + gui[j] = r[i]; + gui[j + 1] = r[i + 1]; + gui[j + 2] = r[i + 2]; } else { - gui[i] = 0; + gui[j] = 0; + gui[j + 1] = 0; + gui[j + 2] = 0; } + gui[j + 3] = 0; // ignored } - } break; case ShaderLanguage::TYPE_UVEC4: { Vector<int> iv = value; int s = iv.size(); uint32_t *gui = (uint32_t *)data; - const int *r = iv.ptr(); + if (p_array_size <= 0) { + p_array_size = 1; + } + int count = 4 * p_array_size; - for (int i = 0; i < 4; i++) { + const int *r = iv.ptr(); + for (int i = 0; i < count; i++) { if (i < s) { gui[i] = r[i]; + gui[i + 1] = r[i + 1]; + gui[i + 2] = r[i + 2]; + gui[i + 3] = r[i + 3]; } else { gui[i] = 0; + gui[i + 1] = 0; + gui[i + 2] = 0; + gui[i + 3] = 0; } } } break; case ShaderLanguage::TYPE_FLOAT: { - float v = value; float *gui = (float *)data; - gui[0] = v; + if (p_array_size > 0) { + const PackedFloat32Array &a = value; + int s = a.size(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = a[i]; + } else { + gui[j] = 0; + } + gui[j + 1] = 0; // ignored + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + float v = value; + gui[0] = v; + } } break; case ShaderLanguage::TYPE_VEC2: { - Vector2 v = value; float *gui = (float *)data; - gui[0] = v.x; - gui[1] = v.y; + if (p_array_size > 0) { + const PackedVector2Array &a = value; + int s = a.size(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = a[i].x; + gui[j + 1] = a[i].y; + } else { + gui[j] = 0; + gui[j + 1] = 0; + } + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + } + } else { + Vector2 v = value; + gui[0] = v.x; + gui[1] = v.y; + } } break; case ShaderLanguage::TYPE_VEC3: { - Vector3 v = value; float *gui = (float *)data; - gui[0] = v.x; - gui[1] = v.y; - gui[2] = v.z; + if (p_array_size > 0) { + const PackedVector3Array &a = value; + int s = a.size(); + + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + gui[j] = a[i].x; + gui[j + 1] = a[i].y; + gui[j + 2] = a[i].z; + } else { + gui[j] = 0; + gui[j + 1] = 0; + gui[j + 2] = 0; + } + gui[j + 3] = 0; // ignored + } + } else { + Vector3 v = value; + gui[0] = v.x; + gui[1] = v.y; + gui[2] = v.z; + } } break; case ShaderLanguage::TYPE_VEC4: { float *gui = (float *)data; - if (value.get_type() == Variant::COLOR) { - Color v = value; + if (p_array_size > 0) { + if (value.get_type() == Variant::PACKED_COLOR_ARRAY) { + const PackedColorArray &a = value; + int s = a.size(); - if (p_linear_color) { - v = v.to_linear(); + for (int i = 0, j = 0; i < p_array_size; i++, j += 4) { + if (i < s) { + Color color = a[i]; + if (p_linear_color) { + color = color.to_linear(); + } + gui[j] = color.r; + gui[j + 1] = color.g; + gui[j + 2] = color.b; + gui[j + 3] = color.a; + } else { + gui[j] = 0; + gui[j + 1] = 0; + gui[j + 2] = 0; + gui[j + 3] = 0; + } + } + } else { + const PackedFloat32Array &a = value; + int s = a.size(); + int count = 4 * p_array_size; + + for (int i = 0; i < count; i += 4) { + if (i + 3 < s) { + gui[i] = a[i]; + gui[i + 1] = a[i + 1]; + gui[i + 2] = a[i + 2]; + gui[i + 3] = a[i + 3]; + } else { + gui[i] = 0; + gui[i + 1] = 0; + gui[i + 2] = 0; + gui[i + 3] = 0; + } + } } + } else { + if (value.get_type() == Variant::COLOR) { + Color v = value; - gui[0] = v.r; - gui[1] = v.g; - gui[2] = v.b; - gui[3] = v.a; - } else if (value.get_type() == Variant::RECT2) { - Rect2 v = value; - - gui[0] = v.position.x; - gui[1] = v.position.y; - gui[2] = v.size.x; - gui[3] = v.size.y; - } else if (value.get_type() == Variant::QUATERNION) { - Quaternion v = value; + if (p_linear_color) { + v = v.to_linear(); + } - gui[0] = v.x; - gui[1] = v.y; - gui[2] = v.z; - gui[3] = v.w; - } else { - Plane v = value; + gui[0] = v.r; + gui[1] = v.g; + gui[2] = v.b; + gui[3] = v.a; + } else if (value.get_type() == Variant::RECT2) { + Rect2 v = value; + + gui[0] = v.position.x; + gui[1] = v.position.y; + gui[2] = v.size.x; + gui[3] = v.size.y; + } else if (value.get_type() == Variant::QUATERNION) { + Quaternion v = value; + + gui[0] = v.x; + gui[1] = v.y; + gui[2] = v.z; + gui[3] = v.w; + } else { + Plane v = value; - gui[0] = v.normal.x; - gui[1] = v.normal.y; - gui[2] = v.normal.z; - gui[3] = v.d; + gui[0] = v.normal.x; + gui[1] = v.normal.y; + gui[2] = v.normal.z; + gui[3] = v.d; + } } } break; case ShaderLanguage::TYPE_MAT2: { - Transform2D v = value; float *gui = (float *)data; - //in std140 members of mat2 are treated as vec4s - gui[0] = v.elements[0][0]; - gui[1] = v.elements[0][1]; - gui[2] = 0; - gui[3] = 0; - gui[4] = v.elements[1][0]; - gui[5] = v.elements[1][1]; - gui[6] = 0; - gui[7] = 0; + if (p_array_size > 0) { + const PackedFloat32Array &a = value; + int s = a.size(); + + for (int i = 0, j = 0; i < p_array_size * 4; i += 4, j += 8) { + if (i + 3 < s) { + gui[j] = a[i]; + gui[j + 1] = a[i + 1]; + + gui[j + 4] = a[i + 2]; + gui[j + 5] = a[i + 3]; + } else { + gui[j] = 1; + gui[j + 1] = 0; + + gui[j + 4] = 0; + gui[j + 5] = 1; + } + gui[j + 2] = 0; // ignored + gui[j + 3] = 0; // ignored + gui[j + 6] = 0; // ignored + gui[j + 7] = 0; // ignored + } + } else { + Transform2D v = value; + + //in std140 members of mat2 are treated as vec4s + gui[0] = v.elements[0][0]; + gui[1] = v.elements[0][1]; + gui[2] = 0; // ignored + gui[3] = 0; // ignored + + gui[4] = v.elements[1][0]; + gui[5] = v.elements[1][1]; + gui[6] = 0; // ignored + gui[7] = 0; // ignored + } } break; case ShaderLanguage::TYPE_MAT3: { - Basis v = value; float *gui = (float *)data; - gui[0] = v.elements[0][0]; - gui[1] = v.elements[1][0]; - gui[2] = v.elements[2][0]; - gui[3] = 0; - gui[4] = v.elements[0][1]; - gui[5] = v.elements[1][1]; - gui[6] = v.elements[2][1]; - gui[7] = 0; - gui[8] = v.elements[0][2]; - gui[9] = v.elements[1][2]; - gui[10] = v.elements[2][2]; - gui[11] = 0; + if (p_array_size > 0) { + const PackedFloat32Array &a = value; + int s = a.size(); + + for (int i = 0, j = 0; i < p_array_size * 9; i += 9, j += 12) { + if (i + 8 < s) { + gui[j] = a[i]; + gui[j + 1] = a[i + 1]; + gui[j + 2] = a[i + 2]; + + gui[j + 4] = a[i + 3]; + gui[j + 5] = a[i + 4]; + gui[j + 6] = a[i + 5]; + + gui[j + 8] = a[i + 6]; + gui[j + 9] = a[i + 7]; + gui[j + 10] = a[i + 8]; + } else { + gui[j] = 1; + gui[j + 1] = 0; + gui[j + 2] = 0; + + gui[j + 4] = 0; + gui[j + 5] = 1; + gui[j + 6] = 0; + + gui[j + 8] = 0; + gui[j + 9] = 0; + gui[j + 10] = 1; + } + gui[j + 3] = 0; // ignored + gui[j + 7] = 0; // ignored + gui[j + 11] = 0; // ignored + } + } else { + Basis v = value; + gui[0] = v.elements[0][0]; + gui[1] = v.elements[1][0]; + gui[2] = v.elements[2][0]; + gui[3] = 0; // ignored + + gui[4] = v.elements[0][1]; + gui[5] = v.elements[1][1]; + gui[6] = v.elements[2][1]; + gui[7] = 0; // ignored + + gui[8] = v.elements[0][2]; + gui[9] = v.elements[1][2]; + gui[10] = v.elements[2][2]; + gui[11] = 0; // ignored + } } break; case ShaderLanguage::TYPE_MAT4: { - Transform3D v = value; float *gui = (float *)data; - gui[0] = v.basis.elements[0][0]; - gui[1] = v.basis.elements[1][0]; - gui[2] = v.basis.elements[2][0]; - gui[3] = 0; - gui[4] = v.basis.elements[0][1]; - gui[5] = v.basis.elements[1][1]; - gui[6] = v.basis.elements[2][1]; - gui[7] = 0; - gui[8] = v.basis.elements[0][2]; - gui[9] = v.basis.elements[1][2]; - gui[10] = v.basis.elements[2][2]; - gui[11] = 0; - gui[12] = v.origin.x; - gui[13] = v.origin.y; - gui[14] = v.origin.z; - gui[15] = 1; + if (p_array_size > 0) { + const PackedFloat32Array &a = value; + int s = a.size(); + + for (int i = 0; i < p_array_size * 16; i += 16) { + if (i + 15 < s) { + gui[i] = a[i]; + gui[i + 1] = a[i + 1]; + gui[i + 2] = a[i + 2]; + gui[i + 3] = a[i + 3]; + + gui[i + 4] = a[i + 4]; + gui[i + 5] = a[i + 5]; + gui[i + 6] = a[i + 6]; + gui[i + 7] = a[i + 7]; + + gui[i + 8] = a[i + 8]; + gui[i + 9] = a[i + 9]; + gui[i + 10] = a[i + 10]; + gui[i + 11] = a[i + 11]; + + gui[i + 12] = a[i + 12]; + gui[i + 13] = a[i + 13]; + gui[i + 14] = a[i + 14]; + gui[i + 15] = a[i + 15]; + } else { + gui[i] = 1; + gui[i + 1] = 0; + gui[i + 2] = 0; + gui[i + 3] = 0; + + gui[i + 4] = 0; + gui[i + 5] = 1; + gui[i + 6] = 0; + gui[i + 7] = 0; + + gui[i + 8] = 0; + gui[i + 9] = 0; + gui[i + 10] = 1; + gui[i + 11] = 0; + + gui[i + 12] = 0; + gui[i + 13] = 0; + gui[i + 14] = 0; + gui[i + 15] = 1; + } + } + } else { + Transform3D v = value; + gui[0] = v.basis.elements[0][0]; + gui[1] = v.basis.elements[1][0]; + gui[2] = v.basis.elements[2][0]; + gui[3] = 0; + + gui[4] = v.basis.elements[0][1]; + gui[5] = v.basis.elements[1][1]; + gui[6] = v.basis.elements[2][1]; + gui[7] = 0; + + gui[8] = v.basis.elements[0][2]; + gui[9] = v.basis.elements[1][2]; + gui[10] = v.basis.elements[2][2]; + gui[11] = 0; + + gui[12] = v.origin.x; + gui[13] = v.origin.y; + gui[14] = v.origin.z; + gui[15] = 1; + } } break; default: { } @@ -2094,19 +2468,23 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, } } -_FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, uint8_t *data) { +_FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, int p_array_size, uint8_t *data) { + if (p_array_size <= 0) { + p_array_size = 1; + } + switch (type) { case ShaderLanguage::TYPE_BOOL: case ShaderLanguage::TYPE_INT: case ShaderLanguage::TYPE_UINT: case ShaderLanguage::TYPE_FLOAT: { - memset(data, 0, 4); + memset(data, 0, 4 * p_array_size); } break; case ShaderLanguage::TYPE_BVEC2: case ShaderLanguage::TYPE_IVEC2: case ShaderLanguage::TYPE_UVEC2: case ShaderLanguage::TYPE_VEC2: { - memset(data, 0, 8); + memset(data, 0, 8 * p_array_size); } break; case ShaderLanguage::TYPE_BVEC3: case ShaderLanguage::TYPE_IVEC3: @@ -2116,16 +2494,16 @@ _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, case ShaderLanguage::TYPE_IVEC4: case ShaderLanguage::TYPE_UVEC4: case ShaderLanguage::TYPE_VEC4: { - memset(data, 0, 16); + memset(data, 0, 16 * p_array_size); } break; case ShaderLanguage::TYPE_MAT2: { - memset(data, 0, 32); + memset(data, 0, 32 * p_array_size); } break; case ShaderLanguage::TYPE_MAT3: { - memset(data, 0, 48); + memset(data, 0, 48 * p_array_size); } break; case ShaderLanguage::TYPE_MAT4: { - memset(data, 0, 64); + memset(data, 0, 64 * p_array_size); } break; default: { @@ -2175,7 +2553,7 @@ void RendererStorageRD::MaterialData::update_uniform_buffer(const Map<StringName if (V) { //user provided - _fill_std140_variant_ubo_value(E.value.type, V->get(), data, p_use_linear_color); + _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, V->get(), data, p_use_linear_color); } else if (E.value.default_value.size()) { //default value @@ -2185,10 +2563,10 @@ void RendererStorageRD::MaterialData::update_uniform_buffer(const Map<StringName //zero because it was not provided if (E.value.type == ShaderLanguage::TYPE_VEC4 && E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { //colors must be set as black, with alpha as 1.0 - _fill_std140_variant_ubo_value(E.value.type, Color(0, 0, 0, 1), data, p_use_linear_color); + _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, Color(0, 0, 0, 1), data, p_use_linear_color); } else { //else just zero it out - _fill_std140_ubo_empty(E.value.type, data); + _fill_std140_ubo_empty(E.value.type, E.value.array_size, data); } } } @@ -2241,10 +2619,11 @@ void RendererStorageRD::MaterialData::update_textures(const Map<StringName, Vari bool uses_global_textures = false; global_textures_pass++; - for (int i = 0; i < p_texture_uniforms.size(); i++) { + for (int i = 0, k = 0; i < p_texture_uniforms.size(); i++) { const StringName &uniform_name = p_texture_uniforms[i].name; + int uniform_array_size = p_texture_uniforms[i].array_size; - RID texture; + Vector<RID> textures; if (p_texture_uniforms[i].global) { RendererStorageRD *rs = base_singleton; @@ -2265,31 +2644,51 @@ void RendererStorageRD::MaterialData::update_textures(const Map<StringName, Vari E->get() = global_textures_pass; } - texture = v->override.get_type() != Variant::NIL ? v->override : v->value; + textures.push_back(v->override.get_type() != Variant::NIL ? v->override : v->value); } } else { WARN_PRINT("Shader uses global uniform texture '" + String(uniform_name) + "', but it was removed at some point. Material will not display correctly."); } } else { - if (!texture.is_valid()) { - const Map<StringName, Variant>::Element *V = p_parameters.find(uniform_name); - if (V) { - texture = V->get(); + const Map<StringName, Variant>::Element *V = p_parameters.find(uniform_name); + if (V) { + if (V->get().is_array()) { + Array array = (Array)V->get(); + if (uniform_array_size > 0) { + for (int j = 0; j < array.size(); j++) { + textures.push_back(array[j]); + } + } else { + if (array.size() > 0) { + textures.push_back(array[0]); + } + } + } else { + textures.push_back(V->get()); } } - if (!texture.is_valid()) { + if (uniform_array_size > 0) { + if (textures.size() < uniform_array_size) { + const Map<StringName, RID>::Element *W = p_default_textures.find(uniform_name); + if (W) { + for (int j = textures.size(); j < uniform_array_size; j++) { + textures.push_back(W->get()); + } + } + } + } else if (textures.is_empty()) { const Map<StringName, RID>::Element *W = p_default_textures.find(uniform_name); if (W) { - texture = W->get(); + textures.push_back(W->get()); } } } RID rd_texture; - if (texture.is_null()) { + if (textures.is_empty()) { //check default usage switch (p_texture_uniforms[i].hint) { case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: @@ -2306,45 +2705,56 @@ void RendererStorageRD::MaterialData::update_textures(const Map<StringName, Vari rd_texture = singleton->texture_rd_get_default(DEFAULT_RD_TEXTURE_WHITE); } break; } +#ifdef TOOLS_ENABLED + if (roughness_detect_texture && normal_detect_texture && normal_detect_texture->path != String()) { + roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel); + } +#endif + if (uniform_array_size > 0) { + for (int j = 0; j < uniform_array_size; j++) { + p_textures[k++] = rd_texture; + } + } else { + p_textures[k] = rd_texture; + ++k; + } } else { bool srgb = p_use_linear_color && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO); - Texture *tex = singleton->texture_owner.get_or_null(texture); + for (int j = 0; j < textures.size(); j++) { + Texture *tex = singleton->texture_owner.get_or_null(textures[j]); - if (tex) { - rd_texture = (srgb && tex->rd_texture_srgb.is_valid()) ? tex->rd_texture_srgb : tex->rd_texture; + if (tex) { + rd_texture = (srgb && tex->rd_texture_srgb.is_valid()) ? tex->rd_texture_srgb : tex->rd_texture; #ifdef TOOLS_ENABLED - if (tex->detect_3d_callback && p_use_linear_color) { - tex->detect_3d_callback(tex->detect_3d_callback_ud); - } - if (tex->detect_normal_callback && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL)) { - if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL) { - normal_detect_texture = tex; + if (tex->detect_3d_callback && p_use_linear_color) { + tex->detect_3d_callback(tex->detect_3d_callback_ud); + } + if (tex->detect_normal_callback && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL)) { + if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL) { + normal_detect_texture = tex; + } + tex->detect_normal_callback(tex->detect_normal_callback_ud); + } + if (tex->detect_roughness_callback && (p_texture_uniforms[i].hint >= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R || p_texture_uniforms[i].hint <= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_GRAY)) { + //find the normal texture + roughness_detect_texture = tex; + roughness_channel = RS::TextureDetectRoughnessChannel(p_texture_uniforms[i].hint - ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R); } - tex->detect_normal_callback(tex->detect_normal_callback_ud); +#endif } - if (tex->detect_roughness_callback && (p_texture_uniforms[i].hint >= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R || p_texture_uniforms[i].hint <= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_GRAY)) { - //find the normal texture - roughness_detect_texture = tex; - roughness_channel = RS::TextureDetectRoughnessChannel(p_texture_uniforms[i].hint - ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R); + if (rd_texture.is_null()) { + rd_texture = singleton->texture_rd_get_default(DEFAULT_RD_TEXTURE_WHITE); + } +#ifdef TOOLS_ENABLED + if (roughness_detect_texture && normal_detect_texture && normal_detect_texture->path != String()) { + roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel); } - #endif - } - - if (rd_texture.is_null()) { - //wtf - rd_texture = singleton->texture_rd_get_default(DEFAULT_RD_TEXTURE_WHITE); + p_textures[k++] = rd_texture; } } - - p_textures[i] = rd_texture; - } -#ifdef TOOLS_ENABLED - if (roughness_detect_texture && normal_detect_texture && normal_detect_texture->path != String()) { - roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel); } -#endif { //for textures no longer used, unregister them List<Map<StringName, uint64_t>::Element *> to_delete; @@ -2412,7 +2822,10 @@ bool RendererStorageRD::MaterialData::update_parameters_uniform_set(const Map<St RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw(), p_barrier); } - uint32_t tex_uniform_count = p_texture_uniforms.size(); + uint32_t tex_uniform_count = 0U; + for (int i = 0; i < p_texture_uniforms.size(); i++) { + tex_uniform_count += uint32_t(p_texture_uniforms[i].array_size > 0 ? p_texture_uniforms[i].array_size : 1); + } if ((uint32_t)texture_cache.size() != tex_uniform_count || p_textures_dirty) { texture_cache.resize(tex_uniform_count); @@ -2452,11 +2865,19 @@ bool RendererStorageRD::MaterialData::update_parameters_uniform_set(const Map<St } const RID *textures = texture_cache.ptrw(); - for (uint32_t i = 0; i < tex_uniform_count; i++) { + for (int i = 0, k = 0; i < p_texture_uniforms.size(); i++) { + const int array_size = p_texture_uniforms[i].array_size; + RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; - u.binding = 1 + i; - u.ids.push_back(textures[i]); + u.binding = 1 + k; + if (array_size > 0) { + for (int j = 0; j < array_size; j++) { + u.ids.push_back(textures[k++]); + } + } else { + u.ids.push_back(textures[k++]); + } uniforms.push_back(u); } } @@ -5327,7 +5748,7 @@ void RendererStorageRD::ParticlesShaderData::get_instance_param_list(List<Render p.info = ShaderLanguage::uniform_to_property_info(E.value); p.info.name = E.key; //supply name p.index = E.value.instance_index; - p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.hint); + p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint); p_param_list->push_back(p); } } @@ -5352,7 +5773,7 @@ Variant RendererStorageRD::ParticlesShaderData::get_default_parameter(const Stri if (uniforms.has(p_parameter)) { ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter]; Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value; - return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint); } return Variant(); } @@ -8551,7 +8972,7 @@ void RendererStorageRD::global_variables_instance_update(RID p_instance, int p_i pos += p_index; - _fill_std140_variant_ubo_value(datatype, p_value, (uint8_t *)&global_variables.buffer_values[pos], true); //instances always use linear color in this renderer + _fill_std140_variant_ubo_value(datatype, 0, p_value, (uint8_t *)&global_variables.buffer_values[pos], true); //instances always use linear color in this renderer _global_variable_mark_buffer_dirty(pos, 1); } diff --git a/servers/rendering/renderer_rd/shader_compiler_rd.cpp b/servers/rendering/renderer_rd/shader_compiler_rd.cpp index cddb679eba..2f4671785a 100644 --- a/servers/rendering/renderer_rd/shader_compiler_rd.cpp +++ b/servers/rendering/renderer_rd/shader_compiler_rd.cpp @@ -91,7 +91,7 @@ static int _get_datatype_size(SL::DataType p_type) { case SL::TYPE_VEC4: return 16; case SL::TYPE_MAT2: - return 32; //4 * 4 + 4 * 4 + return 32; // 4 * 4 + 4 * 4 case SL::TYPE_MAT3: return 48; // 4 * 4 + 4 * 4 + 4 * 4 case SL::TYPE_MAT4: @@ -608,7 +608,7 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge continue; // Instances are indexed directly, don't need index uniforms. } if (SL::is_sampler_type(uniform.type)) { - ucode = "layout(set = " + itos(actions.texture_layout_set) + ", binding = " + itos(actions.base_texture_binding_index + uniform.texture_order) + ") uniform "; + ucode = "layout(set = " + itos(actions.texture_layout_set) + ", binding = " + itos(actions.base_texture_binding_index + uniform.texture_binding) + ") uniform "; } bool is_buffer_global = !SL::is_sampler_type(uniform.type) && uniform.scope == SL::ShaderNode::Uniform::SCOPE_GLOBAL; @@ -622,6 +622,11 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge } ucode += " " + _mkid(uniform_name); + if (uniform.array_size > 0) { + ucode += "["; + ucode += itos(uniform.array_size); + ucode += "]"; + } ucode += ";\n"; if (SL::is_sampler_type(uniform.type)) { for (int j = 0; j < STAGE_MAX; j++) { @@ -635,6 +640,7 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge texture.filter = uniform.filter; texture.repeat = uniform.repeat; texture.global = uniform.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL; + texture.array_size = uniform.array_size; if (texture.global) { r_gen_code.uses_global_textures = true; } @@ -650,7 +656,16 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge uniform_sizes.write[uniform.order] = _get_datatype_size(ShaderLanguage::TYPE_UINT); uniform_alignments.write[uniform.order] = _get_datatype_alignment(ShaderLanguage::TYPE_UINT); } else { - uniform_sizes.write[uniform.order] = _get_datatype_size(uniform.type); + if (uniform.array_size > 0) { + int size = _get_datatype_size(uniform.type) * uniform.array_size; + int m = (16 * uniform.array_size); + if ((size % m) != 0) { + size += m - (size % m); + } + uniform_sizes.write[uniform.order] = size; + } else { + uniform_sizes.write[uniform.order] = _get_datatype_size(uniform.type); + } uniform_alignments.write[uniform.order] = _get_datatype_alignment(uniform.type); } } @@ -1074,10 +1089,32 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge if (p_default_actions.renames.has(anode->name)) { code = p_default_actions.renames[anode->name]; } else { - if (use_fragment_varying) { - code = "frag_to_light."; + if (shader->uniforms.has(anode->name)) { + //its a uniform! + const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[anode->name]; + if (u.texture_order >= 0) { + code = _mkid(anode->name); //texture, use as is + } else { + //a scalar or vector + if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) { + code = actions.base_uniform_string + _mkid(anode->name); //texture, use as is + //global variable, this means the code points to an index to the global table + code = _get_global_variable_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type); + } else if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) { + //instance variable, index it as such + code = "(" + p_default_actions.instance_uniform_index_variable + "+" + itos(u.instance_index) + ")"; + code = _get_global_variable_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type); + } else { + //regular uniform, index from UBO + code = actions.base_uniform_string + _mkid(anode->name); + } + } + } else { + if (use_fragment_varying) { + code = "frag_to_light."; + } + code += _mkid(anode->name); } - code += _mkid(anode->name); } if (anode->call_expression != nullptr) { @@ -1193,46 +1230,63 @@ String ShaderCompilerRD::_dump_node_code(const SL::Node *p_node, int p_level, Ge code += ", "; } String node_code = _dump_node_code(onode->arguments[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); - if (is_texture_func && i == 1 && onode->arguments[i]->type == SL::Node::TYPE_VARIABLE) { + if (is_texture_func && i == 1 && (onode->arguments[i]->type == SL::Node::TYPE_VARIABLE || onode->arguments[i]->type == SL::Node::TYPE_OPERATOR)) { //need to map from texture to sampler in order to sample - const SL::VariableNode *varnode = static_cast<const SL::VariableNode *>(onode->arguments[i]); + StringName texture_uniform; + bool correct_texture_uniform = false; + + if (onode->arguments[i]->type == SL::Node::TYPE_VARIABLE) { + const SL::VariableNode *varnode = static_cast<const SL::VariableNode *>(onode->arguments[i]); + texture_uniform = varnode->name; + correct_texture_uniform = true; + } else { // array indexing operator handling + const SL::OperatorNode *opnode = static_cast<const SL::OperatorNode *>(onode->arguments[i]); + if (opnode->op == SL::Operator::OP_INDEX && opnode->arguments[0]->type == SL::Node::TYPE_ARRAY) { + const SL::ArrayNode *anode = static_cast<const SL::ArrayNode *>(opnode->arguments[0]); + texture_uniform = anode->name; + correct_texture_uniform = true; + } + } - StringName texture_uniform = varnode->name; - is_screen_texture = (texture_uniform == "SCREEN_TEXTURE"); + if (correct_texture_uniform) { + is_screen_texture = (texture_uniform == "SCREEN_TEXTURE"); - String sampler_name; + String sampler_name; - if (actions.custom_samplers.has(texture_uniform)) { - sampler_name = actions.custom_samplers[texture_uniform]; - } else { - if (shader->uniforms.has(texture_uniform)) { - sampler_name = _get_sampler_name(shader->uniforms[texture_uniform].filter, shader->uniforms[texture_uniform].repeat); + if (actions.custom_samplers.has(texture_uniform)) { + sampler_name = actions.custom_samplers[texture_uniform]; } else { - bool found = false; - - for (int j = 0; j < function->arguments.size(); j++) { - if (function->arguments[j].name == texture_uniform) { - if (function->arguments[j].tex_builtin_check) { - ERR_CONTINUE(!actions.custom_samplers.has(function->arguments[j].tex_builtin)); - sampler_name = actions.custom_samplers[function->arguments[j].tex_builtin]; - found = true; - break; - } - if (function->arguments[j].tex_argument_check) { - sampler_name = _get_sampler_name(function->arguments[j].tex_argument_filter, function->arguments[j].tex_argument_repeat); - found = true; - break; + if (shader->uniforms.has(texture_uniform)) { + sampler_name = _get_sampler_name(shader->uniforms[texture_uniform].filter, shader->uniforms[texture_uniform].repeat); + } else { + bool found = false; + + for (int j = 0; j < function->arguments.size(); j++) { + if (function->arguments[j].name == texture_uniform) { + if (function->arguments[j].tex_builtin_check) { + ERR_CONTINUE(!actions.custom_samplers.has(function->arguments[j].tex_builtin)); + sampler_name = actions.custom_samplers[function->arguments[j].tex_builtin]; + found = true; + break; + } + if (function->arguments[j].tex_argument_check) { + sampler_name = _get_sampler_name(function->arguments[j].tex_argument_filter, function->arguments[j].tex_argument_repeat); + found = true; + break; + } } } - } - if (!found) { - //function was most likely unused, so use anything (compiler will remove it anyway) - sampler_name = _get_sampler_name(ShaderLanguage::FILTER_DEFAULT, ShaderLanguage::REPEAT_DEFAULT); + if (!found) { + //function was most likely unused, so use anything (compiler will remove it anyway) + sampler_name = _get_sampler_name(ShaderLanguage::FILTER_DEFAULT, ShaderLanguage::REPEAT_DEFAULT); + } } } - } - code += ShaderLanguage::get_datatype_name(onode->arguments[i]->get_datatype()) + "(" + node_code + ", " + sampler_name + ")"; + code += ShaderLanguage::get_datatype_name(onode->arguments[i]->get_datatype()) + "(" + node_code + ", " + sampler_name + ")"; + } else { + code += node_code; + } } else { code += node_code; } diff --git a/servers/rendering/renderer_rd/shader_compiler_rd.h b/servers/rendering/renderer_rd/shader_compiler_rd.h index 0fe9047967..2ab689c27c 100644 --- a/servers/rendering/renderer_rd/shader_compiler_rd.h +++ b/servers/rendering/renderer_rd/shader_compiler_rd.h @@ -65,6 +65,7 @@ public: ShaderLanguage::TextureFilter filter; ShaderLanguage::TextureRepeat repeat; bool global; + int array_size; }; Vector<Texture> texture_uniforms; diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp index f960d4af5f..f4de887912 100644 --- a/servers/rendering/shader_language.cpp +++ b/servers/rendering/shader_language.cpp @@ -930,7 +930,6 @@ void ShaderLanguage::clear() { error_set = false; error_str = ""; last_const = false; - pass_array = false; while (nodes) { Node *n = nodes; nodes = nodes->next; @@ -1078,6 +1077,9 @@ bool ShaderLanguage::_find_identifier(const BlockNode *p_block, bool p_allow_rea if (r_data_type) { *r_data_type = shader->uniforms[p_identifier].type; } + if (r_array_size) { + *r_array_size = shader->uniforms[p_identifier].array_size; + } if (r_type) { *r_type = IDENTIFIER_UNIFORM; } @@ -2384,9 +2386,12 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, const FunctionI failed_builtin = true; bool fail = false; for (int i = 0; i < argcount; i++) { - if (p_func->arguments[i + 1]->type == Node::TYPE_ARRAY && !static_cast<const ArrayNode *>(p_func->arguments[i + 1])->is_indexed()) { - fail = true; - break; + if (p_func->arguments[i + 1]->type == Node::TYPE_ARRAY) { + const ArrayNode *anode = static_cast<const ArrayNode *>(p_func->arguments[i + 1]); + if (anode->call_expression == nullptr && !anode->is_indexed()) { + fail = true; + break; + } } if (get_scalar_type(args[i]) == args[i] && p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode *>(p_func->arguments[i + 1]), builtin_func_defs[idx].args[i])) { //all good, but needs implicit conversion later @@ -2921,86 +2926,294 @@ bool ShaderLanguage::is_sampler_type(DataType p_type) { p_type == TYPE_SAMPLERCUBEARRAY; } -Variant ShaderLanguage::constant_value_to_variant(const Vector<ShaderLanguage::ConstantNode::Value> &p_value, DataType p_type, ShaderLanguage::ShaderNode::Uniform::Hint p_hint) { +Variant ShaderLanguage::constant_value_to_variant(const Vector<ShaderLanguage::ConstantNode::Value> &p_value, DataType p_type, int p_array_size, ShaderLanguage::ShaderNode::Uniform::Hint p_hint) { + int array_size = p_array_size; + if (p_value.size() > 0) { Variant value; switch (p_type) { case ShaderLanguage::TYPE_BOOL: - value = Variant(p_value[0].boolean); + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].boolean); + } + value = Variant(array); + } else { + value = Variant(p_value[0].boolean); + } break; case ShaderLanguage::TYPE_BVEC2: + array_size *= 2; + + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].boolean); + } + value = Variant(array); + } else { + value = Variant(p_value[0].boolean); + } + break; case ShaderLanguage::TYPE_BVEC3: + array_size *= 3; + + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].boolean); + } + value = Variant(array); + } else { + value = Variant(p_value[0].boolean); + } + break; case ShaderLanguage::TYPE_BVEC4: + array_size *= 4; + + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].boolean); + } + value = Variant(array); + } else { + value = Variant(p_value[0].boolean); + } + break; case ShaderLanguage::TYPE_INT: - value = Variant(p_value[0].sint); + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].sint); + } + value = Variant(array); + } else { + value = Variant(p_value[0].sint); + } break; case ShaderLanguage::TYPE_IVEC2: - value = Variant(Vector2(p_value[0].sint, p_value[1].sint)); + if (array_size > 0) { + array_size *= 2; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].sint); + } + value = Variant(array); + } else { + value = Variant(Vector2(p_value[0].sint, p_value[1].sint)); + } break; case ShaderLanguage::TYPE_IVEC3: - value = Variant(Vector3(p_value[0].sint, p_value[1].sint, p_value[2].sint)); + if (array_size > 0) { + array_size *= 3; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].sint); + } + value = Variant(array); + } else { + value = Variant(Vector3(p_value[0].sint, p_value[1].sint, p_value[2].sint)); + } break; case ShaderLanguage::TYPE_IVEC4: - value = Variant(Plane(p_value[0].sint, p_value[1].sint, p_value[2].sint, p_value[3].sint)); + if (array_size > 0) { + array_size *= 4; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].sint); + } + value = Variant(array); + } else { + value = Variant(Plane(p_value[0].sint, p_value[1].sint, p_value[2].sint, p_value[3].sint)); + } break; case ShaderLanguage::TYPE_UINT: - value = Variant(p_value[0].uint); + if (array_size > 0) { + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].uint); + } + value = Variant(array); + } else { + value = Variant(p_value[0].uint); + } break; case ShaderLanguage::TYPE_UVEC2: - value = Variant(Vector2(p_value[0].uint, p_value[1].uint)); + if (array_size > 0) { + array_size *= 2; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].uint); + } + value = Variant(array); + } else { + value = Variant(Vector2(p_value[0].uint, p_value[1].uint)); + } break; case ShaderLanguage::TYPE_UVEC3: - value = Variant(Vector3(p_value[0].uint, p_value[1].uint, p_value[2].uint)); + if (array_size > 0) { + array_size *= 3; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].uint); + } + value = Variant(array); + } else { + value = Variant(Vector3(p_value[0].uint, p_value[1].uint, p_value[2].uint)); + } break; case ShaderLanguage::TYPE_UVEC4: - value = Variant(Plane(p_value[0].uint, p_value[1].uint, p_value[2].uint, p_value[3].uint)); + if (array_size > 0) { + array_size *= 4; + + PackedInt32Array array = PackedInt32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].uint); + } + value = Variant(array); + } else { + value = Variant(Plane(p_value[0].uint, p_value[1].uint, p_value[2].uint, p_value[3].uint)); + } break; case ShaderLanguage::TYPE_FLOAT: - value = Variant(p_value[0].real); + if (array_size > 0) { + PackedFloat32Array array = PackedFloat32Array(); + for (int i = 0; i < array_size; i++) { + array.push_back(p_value[i].real); + } + value = Variant(array); + } else { + value = Variant(p_value[0].real); + } break; case ShaderLanguage::TYPE_VEC2: - value = Variant(Vector2(p_value[0].real, p_value[1].real)); + if (array_size > 0) { + array_size *= 2; + + PackedVector2Array array = PackedVector2Array(); + for (int i = 0; i < array_size; i += 2) { + array.push_back(Vector2(p_value[i].real, p_value[i + 1].real)); + } + value = Variant(array); + } else { + value = Variant(Vector2(p_value[0].real, p_value[1].real)); + } break; case ShaderLanguage::TYPE_VEC3: - value = Variant(Vector3(p_value[0].real, p_value[1].real, p_value[2].real)); + if (array_size > 0) { + array_size *= 3; + + PackedVector3Array array = PackedVector3Array(); + for (int i = 0; i < array_size; i += 3) { + array.push_back(Vector3(p_value[i].real, p_value[i + 1].real, p_value[i + 2].real)); + } + value = Variant(array); + } else { + value = Variant(Vector3(p_value[0].real, p_value[1].real, p_value[2].real)); + } break; case ShaderLanguage::TYPE_VEC4: - if (p_hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { - value = Variant(Color(p_value[0].real, p_value[1].real, p_value[2].real, p_value[3].real)); + if (array_size > 0) { + array_size *= 4; + + if (p_hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { + PackedColorArray array = PackedColorArray(); + for (int i = 0; i < array_size; i += 4) { + array.push_back(Color(p_value[i].real, p_value[i + 1].real, p_value[i + 2].real, p_value[i + 3].real)); + } + value = Variant(array); + } else { + PackedFloat32Array array = PackedFloat32Array(); + for (int i = 0; i < array_size; i += 4) { + array.push_back(p_value[i].real); + array.push_back(p_value[i + 1].real); + array.push_back(p_value[i + 2].real); + array.push_back(p_value[i + 3].real); + } + value = Variant(array); + } } else { - value = Variant(Plane(p_value[0].real, p_value[1].real, p_value[2].real, p_value[3].real)); + if (p_hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { + value = Variant(Color(p_value[0].real, p_value[1].real, p_value[2].real, p_value[3].real)); + } else { + value = Variant(Plane(p_value[0].real, p_value[1].real, p_value[2].real, p_value[3].real)); + } } break; case ShaderLanguage::TYPE_MAT2: - value = Variant(Transform2D(p_value[0].real, p_value[2].real, p_value[1].real, p_value[3].real, 0.0, 0.0)); + if (array_size > 0) { + array_size *= 4; + + PackedFloat32Array array = PackedFloat32Array(); + for (int i = 0; i < array_size; i += 4) { + array.push_back(p_value[i].real); + array.push_back(p_value[i + 1].real); + array.push_back(p_value[i + 2].real); + array.push_back(p_value[i + 3].real); + } + value = Variant(array); + } else { + value = Variant(Transform2D(p_value[0].real, p_value[2].real, p_value[1].real, p_value[3].real, 0.0, 0.0)); + } break; case ShaderLanguage::TYPE_MAT3: { - Basis p; - p[0][0] = p_value[0].real; - p[0][1] = p_value[1].real; - p[0][2] = p_value[2].real; - p[1][0] = p_value[3].real; - p[1][1] = p_value[4].real; - p[1][2] = p_value[5].real; - p[2][0] = p_value[6].real; - p[2][1] = p_value[7].real; - p[2][2] = p_value[8].real; - value = Variant(p); + if (array_size > 0) { + array_size *= 9; + + PackedFloat32Array array = PackedFloat32Array(); + for (int i = 0; i < array_size; i += 9) { + for (int j = 0; j < 9; j++) { + array.push_back(p_value[i + j].real); + } + } + value = Variant(array); + } else { + Basis p; + p[0][0] = p_value[0].real; + p[0][1] = p_value[1].real; + p[0][2] = p_value[2].real; + p[1][0] = p_value[3].real; + p[1][1] = p_value[4].real; + p[1][2] = p_value[5].real; + p[2][0] = p_value[6].real; + p[2][1] = p_value[7].real; + p[2][2] = p_value[8].real; + value = Variant(p); + } break; } case ShaderLanguage::TYPE_MAT4: { - Basis p; - p[0][0] = p_value[0].real; - p[0][1] = p_value[1].real; - p[0][2] = p_value[2].real; - p[1][0] = p_value[4].real; - p[1][1] = p_value[5].real; - p[1][2] = p_value[6].real; - p[2][0] = p_value[8].real; - p[2][1] = p_value[9].real; - p[2][2] = p_value[10].real; - Transform3D t = Transform3D(p, Vector3(p_value[3].real, p_value[7].real, p_value[11].real)); - value = Variant(t); + if (array_size > 0) { + array_size *= 16; + + PackedFloat32Array array = PackedFloat32Array(); + for (int i = 0; i < array_size; i += 16) { + for (int j = 0; j < 16; j++) { + array.push_back(p_value[i + j].real); + } + } + value = Variant(array); + } else { + Basis p; + p[0][0] = p_value[0].real; + p[0][1] = p_value[1].real; + p[0][2] = p_value[2].real; + p[1][0] = p_value[4].real; + p[1][1] = p_value[5].real; + p[1][2] = p_value[6].real; + p[2][0] = p_value[8].real; + p[2][1] = p_value[9].real; + p[2][2] = p_value[10].real; + Transform3D t = Transform3D(p, Vector3(p_value[3].real, p_value[7].real, p_value[11].real)); + value = Variant(t); + } break; } case ShaderLanguage::TYPE_ISAMPLER2DARRAY: @@ -3036,31 +3249,50 @@ PropertyInfo ShaderLanguage::uniform_to_property_info(const ShaderNode::Uniform pi.type = Variant::NIL; break; case ShaderLanguage::TYPE_BOOL: - pi.type = Variant::BOOL; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_INT32_ARRAY; + } else { + pi.type = Variant::BOOL; + } break; case ShaderLanguage::TYPE_BVEC2: - pi.type = Variant::INT; - pi.hint = PROPERTY_HINT_FLAGS; - pi.hint_string = "x,y"; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_INT32_ARRAY; + } else { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y"; + } break; case ShaderLanguage::TYPE_BVEC3: - pi.type = Variant::INT; - pi.hint = PROPERTY_HINT_FLAGS; - pi.hint_string = "x,y,z"; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_INT32_ARRAY; + } else { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y,z"; + } break; case ShaderLanguage::TYPE_BVEC4: - pi.type = Variant::INT; - pi.hint = PROPERTY_HINT_FLAGS; - pi.hint_string = "x,y,z,w"; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_INT32_ARRAY; + } else { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y,z,w"; + } break; case ShaderLanguage::TYPE_UINT: case ShaderLanguage::TYPE_INT: { - pi.type = Variant::INT; - if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { - pi.hint = PROPERTY_HINT_RANGE; - pi.hint_string = rtos(p_uniform.hint_range[0]) + "," + rtos(p_uniform.hint_range[1]) + "," + rtos(p_uniform.hint_range[2]); + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_INT32_ARRAY; + } else { + pi.type = Variant::INT; + if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { + pi.hint = PROPERTY_HINT_RANGE; + pi.hint_string = rtos(p_uniform.hint_range[0]) + "," + rtos(p_uniform.hint_range[1]) + "," + rtos(p_uniform.hint_range[2]); + } } - } break; case ShaderLanguage::TYPE_IVEC2: case ShaderLanguage::TYPE_IVEC3: @@ -3071,59 +3303,106 @@ PropertyInfo ShaderLanguage::uniform_to_property_info(const ShaderNode::Uniform pi.type = Variant::PACKED_INT32_ARRAY; } break; case ShaderLanguage::TYPE_FLOAT: { - pi.type = Variant::FLOAT; - if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { - pi.hint = PROPERTY_HINT_RANGE; - pi.hint_string = rtos(p_uniform.hint_range[0]) + "," + rtos(p_uniform.hint_range[1]) + "," + rtos(p_uniform.hint_range[2]); + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_FLOAT32_ARRAY; + } else { + pi.type = Variant::FLOAT; + if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { + pi.hint = PROPERTY_HINT_RANGE; + pi.hint_string = rtos(p_uniform.hint_range[0]) + "," + rtos(p_uniform.hint_range[1]) + "," + rtos(p_uniform.hint_range[2]); + } } - } break; case ShaderLanguage::TYPE_VEC2: - pi.type = Variant::VECTOR2; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_VECTOR2_ARRAY; + } else { + pi.type = Variant::VECTOR2; + } break; case ShaderLanguage::TYPE_VEC3: - pi.type = Variant::VECTOR3; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_VECTOR3_ARRAY; + } else { + pi.type = Variant::VECTOR3; + } break; case ShaderLanguage::TYPE_VEC4: { - if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { - pi.type = Variant::COLOR; + if (p_uniform.array_size > 0) { + if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { + pi.type = Variant::PACKED_COLOR_ARRAY; + } else { + pi.type = Variant::PACKED_FLOAT32_ARRAY; + } } else { - pi.type = Variant::PLANE; + if (p_uniform.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { + pi.type = Variant::COLOR; + } else { + pi.type = Variant::PLANE; + } } } break; case ShaderLanguage::TYPE_MAT2: - pi.type = Variant::TRANSFORM2D; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_FLOAT32_ARRAY; + } else { + pi.type = Variant::TRANSFORM2D; + } break; case ShaderLanguage::TYPE_MAT3: - pi.type = Variant::BASIS; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_FLOAT32_ARRAY; + } else { + pi.type = Variant::BASIS; + } break; case ShaderLanguage::TYPE_MAT4: - pi.type = Variant::TRANSFORM3D; + if (p_uniform.array_size > 0) { + pi.type = Variant::PACKED_FLOAT32_ARRAY; + } else { + pi.type = Variant::TRANSFORM3D; + } break; case ShaderLanguage::TYPE_SAMPLER2D: case ShaderLanguage::TYPE_ISAMPLER2D: case ShaderLanguage::TYPE_USAMPLER2D: { - pi.type = Variant::OBJECT; + if (p_uniform.array_size > 0) { + pi.type = Variant::ARRAY; + } else { + pi.type = Variant::OBJECT; + } pi.hint = PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string = "Texture2D"; } break; case ShaderLanguage::TYPE_SAMPLER2DARRAY: case ShaderLanguage::TYPE_ISAMPLER2DARRAY: case ShaderLanguage::TYPE_USAMPLER2DARRAY: { - pi.type = Variant::OBJECT; + if (p_uniform.array_size > 0) { + pi.type = Variant::ARRAY; + } else { + pi.type = Variant::OBJECT; + } pi.hint = PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string = "TextureLayered"; } break; case ShaderLanguage::TYPE_SAMPLER3D: case ShaderLanguage::TYPE_ISAMPLER3D: case ShaderLanguage::TYPE_USAMPLER3D: { - pi.type = Variant::OBJECT; + if (p_uniform.array_size > 0) { + pi.type = Variant::ARRAY; + } else { + pi.type = Variant::OBJECT; + } pi.hint = PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string = "Texture3D"; } break; case ShaderLanguage::TYPE_SAMPLERCUBE: case ShaderLanguage::TYPE_SAMPLERCUBEARRAY: { - pi.type = Variant::OBJECT; + if (p_uniform.array_size > 0) { + pi.type = Variant::ARRAY; + } else { + pi.type = Variant::OBJECT; + } pi.hint = PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string = "TextureLayered"; } break; @@ -3730,9 +4009,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_array_constructor(BlockNode *p_bloc if (!is_token_variable_datatype(tk.type)) { _set_tkpos(prev_pos); - pass_array = true; Node *n = _parse_and_reduce_expression(p_block, p_function_info); - pass_array = false; if (!n) { _set_error("Invalid data type for array"); @@ -3822,7 +4099,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_array_constructor(BlockNode *p_bloc return nullptr; } - if (!_compare_datatypes(p_type, p_struct_name, 0, n->get_datatype(), n->get_datatype_name(), 0)) { + if (!_compare_datatypes(p_type, p_struct_name, 0, n->get_datatype(), n->get_datatype_name(), n->get_array_size())) { return nullptr; } @@ -4070,9 +4347,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons int carg = -1; - pass_array = true; bool ok = _parse_function_arguments(p_block, p_function_info, func, &carg); - pass_array = false; // Check if block has a variable with the same name as function to prevent shader crash. ShaderLanguage::BlockNode *bnode = p_block; @@ -4324,62 +4599,58 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons Node *assign_expression = nullptr; if (array_size > 0) { - if (!pass_array) { - tk = _get_token(); + prepos = _get_tkpos(); + tk = _get_token(); - if (tk.type != TK_BRACKET_OPEN && tk.type != TK_PERIOD && tk.type != TK_OP_ASSIGN) { - _set_error("Expected '[','.' or '='"); + if (tk.type == TK_OP_ASSIGN) { + if (is_const) { + _set_error("Constants cannot be modified."); + return nullptr; + } + assign_expression = _parse_array_constructor(p_block, p_function_info, data_type, struct_name, array_size); + if (!assign_expression) { + return nullptr; + } + } else if (tk.type == TK_PERIOD) { + completion_class = TAG_ARRAY; + p_block->block_tag = SubClassTag::TAG_ARRAY; + call_expression = _parse_and_reduce_expression(p_block, p_function_info); + p_block->block_tag = SubClassTag::TAG_GLOBAL; + if (!call_expression) { + return nullptr; + } + data_type = call_expression->get_datatype(); + } else if (tk.type == TK_BRACKET_OPEN) { // indexing + index_expression = _parse_and_reduce_expression(p_block, p_function_info); + if (!index_expression) { return nullptr; } - if (tk.type == TK_OP_ASSIGN) { - if (is_const) { - _set_error("Constants cannot be modified."); - return nullptr; - } - assign_expression = _parse_array_constructor(p_block, p_function_info, data_type, struct_name, array_size); - if (!assign_expression) { - return nullptr; - } - } else if (tk.type == TK_PERIOD) { - completion_class = TAG_ARRAY; - p_block->block_tag = SubClassTag::TAG_ARRAY; - call_expression = _parse_and_reduce_expression(p_block, p_function_info); - p_block->block_tag = SubClassTag::TAG_GLOBAL; - if (!call_expression) { - return nullptr; - } - data_type = call_expression->get_datatype(); - } else { // indexing - index_expression = _parse_and_reduce_expression(p_block, p_function_info); - if (!index_expression) { - return nullptr; - } - - if (index_expression->get_datatype() != TYPE_INT && index_expression->get_datatype() != TYPE_UINT) { - _set_error("Only integer expressions are allowed for indexing"); - return nullptr; - } + if (index_expression->get_datatype() != TYPE_INT && index_expression->get_datatype() != TYPE_UINT) { + _set_error("Only integer expressions are allowed for indexing"); + return nullptr; + } - if (index_expression->type == Node::TYPE_CONSTANT) { - ConstantNode *cnode = (ConstantNode *)index_expression; - if (cnode) { - if (!cnode->values.is_empty()) { - int value = cnode->values[0].sint; - if (value < 0 || value >= array_size) { - _set_error(vformat("Index [%s] out of range [%s..%s]", value, 0, array_size - 1)); - return nullptr; - } + if (index_expression->type == Node::TYPE_CONSTANT) { + ConstantNode *cnode = (ConstantNode *)index_expression; + if (cnode) { + if (!cnode->values.is_empty()) { + int value = cnode->values[0].sint; + if (value < 0 || value >= array_size) { + _set_error(vformat("Index [%s] out of range [%s..%s]", value, 0, array_size - 1)); + return nullptr; } } } + } - tk = _get_token(); - if (tk.type != TK_BRACKET_CLOSE) { - _set_error("Expected ']'"); - return nullptr; - } + tk = _get_token(); + if (tk.type != TK_BRACKET_CLOSE) { + _set_error("Expected ']'"); + return nullptr; } + } else { + _set_tkpos(prepos); } ArrayNode *arrname = alloc_node<ArrayNode>(); @@ -4804,10 +5075,6 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons } mn->index_expression = index_expression; } else { - if (!pass_array) { - _set_error("Expected '[','.' or '='"); - return nullptr; - } _set_tkpos(prev_pos); } } @@ -5750,9 +6017,7 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun if (tk.type == TK_IDENTIFIER) { // a function call array initialization _set_tkpos(prev_pos); - pass_array = true; Node *n = _parse_and_reduce_expression(p_block, p_function_info); - pass_array = false; if (!n) { _set_error("Expected correct array initializer!"); @@ -6477,12 +6742,10 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun } else { _set_tkpos(pos); //rollback, wants expression - pass_array = true; Node *expr = _parse_and_reduce_expression(p_block, p_function_info); if (!expr) { return ERR_PARSE_ERROR; } - pass_array = false; if (b->parent_function->return_type != expr->get_datatype() || b->parent_function->return_array_size != expr->get_array_size() || return_struct_name != expr->get_datatype_name()) { _set_error("Expected return with an expression of type '" + (return_struct_name != "" ? return_struct_name : get_datatype_name(b->parent_function->return_type)) + array_size_string + "'"); @@ -6694,6 +6957,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct tk = _get_token(); int texture_uniforms = 0; + int texture_binding = 0; int uniforms = 0; int instance_index = 0; ShaderNode::Uniform::Scope uniform_scope = ShaderNode::Uniform::SCOPE_LOCAL; @@ -6903,6 +7167,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct } } + bool precision_defined = false; DataPrecision precision = PRECISION_DEFAULT; DataInterpolation interpolation = INTERPOLATION_SMOOTH; DataType type; @@ -6911,15 +7176,34 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct tk = _get_token(); if (is_token_interpolation(tk.type)) { + if (uniform) { + _set_error("Interpolation qualifiers are not supported for uniforms!"); + return ERR_PARSE_ERROR; + } interpolation = get_token_interpolation(tk.type); tk = _get_token(); } if (is_token_precision(tk.type)) { precision = get_token_precision(tk.type); + precision_defined = true; tk = _get_token(); } + if (shader->structs.has(tk.text)) { + if (uniform) { + if (precision_defined) { + _set_error("Precision modifier cannot be used on structs."); + return ERR_PARSE_ERROR; + } + _set_error("struct datatype is not yet supported for uniforms!"); + return ERR_PARSE_ERROR; + } else { + _set_error("struct datatype not allowed here"); + return ERR_PARSE_ERROR; + } + } + if (!is_token_datatype(tk.type)) { _set_error("Expected datatype. "); return ERR_PARSE_ERROR; @@ -6940,10 +7224,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct tk = _get_token(); if (tk.type == TK_BRACKET_OPEN) { - if (uniform) { - _set_error(vformat("Uniform arrays are not yet implemented!")); - return ERR_PARSE_ERROR; - } tk = _get_token(); if (tk.type == TK_INT_CONSTANT && tk.constant > 0) { @@ -6996,12 +7276,47 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct } ShaderNode::Uniform uniform2; + uniform2.type = type; + uniform2.scope = uniform_scope; + uniform2.precision = precision; + uniform2.array_size = array_size; + + tk = _get_token(); + if (tk.type == TK_BRACKET_OPEN) { + if (uniform2.array_size > 0) { + _set_error("Array size is already defined!"); + return ERR_PARSE_ERROR; + } + tk = _get_token(); + + if (tk.type == TK_INT_CONSTANT && tk.constant > 0) { + uniform2.array_size = (int)tk.constant; + + tk = _get_token(); + if (tk.type == TK_BRACKET_CLOSE) { + tk = _get_token(); + } else { + _set_error("Expected ']'"); + return ERR_PARSE_ERROR; + } + } else { + _set_error("Expected integer constant > 0"); + return ERR_PARSE_ERROR; + } + } + if (is_sampler_type(type)) { if (uniform_scope == ShaderNode::Uniform::SCOPE_INSTANCE) { _set_error("Uniforms with 'instance' qualifiers can't be of sampler type."); return ERR_PARSE_ERROR; } uniform2.texture_order = texture_uniforms++; + uniform2.texture_binding = texture_binding; + if (uniform2.array_size > 0) { + texture_binding += uniform2.array_size; + } else { + ++texture_binding; + } uniform2.order = -1; if (_validate_datatype(type) != OK) { return ERR_PARSE_ERROR; @@ -7011,19 +7326,22 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct _set_error("Uniforms with 'instance' qualifiers can't be of matrix type."); return ERR_PARSE_ERROR; } - uniform2.texture_order = -1; if (uniform_scope != ShaderNode::Uniform::SCOPE_INSTANCE) { uniform2.order = uniforms++; } } - uniform2.type = type; - uniform2.scope = uniform_scope; - uniform2.precision = precision; - - //todo parse default value - tk = _get_token(); + if (uniform2.array_size > 0) { + if (uniform_scope == ShaderNode::Uniform::SCOPE_GLOBAL) { + _set_error("'SCOPE_GLOBAL' qualifier is not yet supported for uniform array!"); + return ERR_PARSE_ERROR; + } + if (uniform_scope == ShaderNode::Uniform::SCOPE_INSTANCE) { + _set_error("'SCOPE_INSTANCE' qualifier is not yet supported for uniform array!"); + return ERR_PARSE_ERROR; + } + } int custom_instance_index = -1; @@ -7031,6 +7349,14 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct //hint do { tk = _get_token(); + + if (uniform2.array_size > 0) { + if (tk.type != TK_HINT_COLOR) { + _set_error("This hint is not yet supported for uniform arrays!"); + return ERR_PARSE_ERROR; + } + } + if (tk.type == TK_HINT_WHITE_TEXTURE) { uniform2.hint = ShaderNode::Uniform::HINT_WHITE; } else if (tk.type == TK_HINT_BLACK_TEXTURE) { @@ -7221,6 +7547,11 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct //reset scope for next uniform if (tk.type == TK_OP_ASSIGN) { + if (uniform2.array_size > 0) { + _set_error("Setting default value to a uniform array is not yet supported!"); + return ERR_PARSE_ERROR; + } + Node *expr = _parse_and_reduce_expression(nullptr, FunctionInfo()); if (!expr) { return ERR_PARSE_ERROR; @@ -7265,7 +7596,11 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct tk = _get_token(); if (tk.type != TK_SEMICOLON && tk.type != TK_BRACKET_OPEN) { - _set_error("Expected ';' or '['"); + if (array_size == 0) { + _set_error("Expected ';' or '['"); + } else { + _set_error("Expected ';'"); + } return ERR_PARSE_ERROR; } @@ -7290,7 +7625,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct return ERR_PARSE_ERROR; } } else { - _set_error("Expected single integer constant > 0"); + _set_error("Expected integer constant > 0"); return ERR_PARSE_ERROR; } } diff --git a/servers/rendering/shader_language.h b/servers/rendering/shader_language.h index 18525e054e..1444546f05 100644 --- a/servers/rendering/shader_language.h +++ b/servers/rendering/shader_language.h @@ -692,8 +692,10 @@ public: int order = 0; int texture_order = 0; + int texture_binding = 0; DataType type = TYPE_VOID; DataPrecision precision = PRECISION_DEFAULT; + int array_size = 0; Vector<ConstantNode::Value> default_value; Scope scope = SCOPE_LOCAL; Hint hint = HINT_NONE; @@ -776,7 +778,7 @@ public: static bool is_scalar_type(DataType p_type); static bool is_float_type(DataType p_type); static bool is_sampler_type(DataType p_type); - static Variant constant_value_to_variant(const Vector<ShaderLanguage::ConstantNode::Value> &p_value, DataType p_type, ShaderLanguage::ShaderNode::Uniform::Hint p_hint = ShaderLanguage::ShaderNode::Uniform::HINT_NONE); + static Variant constant_value_to_variant(const Vector<ShaderLanguage::ConstantNode::Value> &p_value, DataType p_type, int p_array_size, ShaderLanguage::ShaderNode::Uniform::Hint p_hint = ShaderLanguage::ShaderNode::Uniform::HINT_NONE); static PropertyInfo uniform_to_property_info(const ShaderNode::Uniform &p_uniform); static uint32_t get_type_size(DataType p_type); @@ -874,7 +876,6 @@ private: StringName current_function; bool last_const = false; - bool pass_array = false; StringName last_name; VaryingFunctionNames varying_function_names; diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp index 58e99f0e91..847f29f6ba 100644 --- a/servers/rendering_server.cpp +++ b/servers/rendering_server.cpp @@ -934,7 +934,7 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa } } - ERR_FAIL_COND_V((bsformat) != (format & (RS::ARRAY_FORMAT_INDEX - 1)), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V_MSG((bsformat) != (format & (ARRAY_FORMAT_VERTEX | ARRAY_FORMAT_NORMAL | ARRAY_FORMAT_TANGENT)), ERR_INVALID_PARAMETER, "Blend shape format must match the main array format for Vertex, Normal and Tangent arrays."); } } diff --git a/servers/text/text_server_extension.h b/servers/text/text_server_extension.h index 88a8c0cb0c..954b2cf660 100644 --- a/servers/text/text_server_extension.h +++ b/servers/text/text_server_extension.h @@ -33,6 +33,7 @@ #include "core/object/gdvirtual.gen.inc" #include "core/object/script_language.h" +#include "core/os/thread_safe.h" #include "core/variant/native_ptr.h" #include "servers/text_server.h" diff --git a/servers/text_server.cpp b/servers/text_server.cpp index a365fde64a..5087d32a7f 100644 --- a/servers/text_server.cpp +++ b/servers/text_server.cpp @@ -29,7 +29,7 @@ /*************************************************************************/ #include "servers/text_server.h" -#include "scene/main/canvas_item.h" +#include "servers/rendering_server.h" TextServerManager *TextServerManager::singleton = nullptr; @@ -479,111 +479,58 @@ void TextServer::_bind_methods() { BIND_ENUM_CONSTANT(SPACING_BOTTOM); } -Vector3 TextServer::hex_code_box_font_size[2] = { Vector3(5, 5, 1), Vector3(10, 10, 2) }; -Ref<CanvasTexture> TextServer::hex_code_box_font_tex[2] = { nullptr, nullptr }; - -void TextServer::initialize_hex_code_box_fonts() { - static unsigned int tamsyn5x9_png_len = 175; - static unsigned char tamsyn5x9_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x05, - 0x04, 0x03, 0x00, 0x00, 0x00, 0x20, 0x7c, 0x76, 0xda, 0x00, 0x00, 0x00, - 0x0f, 0x50, 0x4c, 0x54, 0x45, 0xfd, 0x07, 0x00, 0x00, 0x00, 0x00, 0x06, - 0x7e, 0x74, 0x00, 0x40, 0xc6, 0xff, 0xff, 0xff, 0x47, 0x9a, 0xd4, 0xc7, - 0x00, 0x00, 0x00, 0x01, 0x74, 0x52, 0x4e, 0x53, 0x00, 0x40, 0xe6, 0xd8, - 0x66, 0x00, 0x00, 0x00, 0x4e, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1d, 0x05, - 0xc1, 0x21, 0x01, 0x00, 0x00, 0x00, 0x83, 0x30, 0x04, 0xc1, 0x10, 0xef, - 0x9f, 0xe9, 0x1b, 0x86, 0x2c, 0x17, 0xb9, 0xcc, 0x65, 0x0c, 0x73, 0x38, - 0xc7, 0xe6, 0x22, 0x19, 0x88, 0x98, 0x10, 0x48, 0x4a, 0x29, 0x85, 0x14, - 0x02, 0x89, 0x10, 0xa3, 0x1c, 0x0b, 0x31, 0xd6, 0xe6, 0x08, 0x69, 0x39, - 0x48, 0x44, 0xa0, 0x0d, 0x4a, 0x22, 0xa1, 0x94, 0x42, 0x0a, 0x01, 0x63, - 0x6d, 0x0e, 0x72, 0x18, 0x61, 0x8c, 0x74, 0x38, 0xc7, 0x26, 0x1c, 0xf3, - 0x71, 0x16, 0x15, 0x27, 0x6a, 0xc2, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x49, - 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 - }; - - static unsigned int tamsyn10x20_png_len = 270; - static unsigned char tamsyn10x20_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x0a, - 0x04, 0x03, 0x00, 0x00, 0x00, 0xc1, 0x66, 0x48, 0x96, 0x00, 0x00, 0x00, - 0x0f, 0x50, 0x4c, 0x54, 0x45, 0x00, 0x00, 0x00, 0xf9, 0x07, 0x00, 0x5d, - 0x71, 0xa5, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x49, 0xdb, 0xcb, 0x7f, - 0x00, 0x00, 0x00, 0x01, 0x74, 0x52, 0x4e, 0x53, 0x00, 0x40, 0xe6, 0xd8, - 0x66, 0x00, 0x00, 0x00, 0xad, 0x49, 0x44, 0x41, 0x54, 0x28, 0xcf, 0xa5, - 0x92, 0x4b, 0x0e, 0x03, 0x31, 0x08, 0x43, 0xdf, 0x82, 0x83, 0x79, 0xe1, - 0xfb, 0x9f, 0xa9, 0x0b, 0x3e, 0x61, 0xa6, 0x1f, 0x55, 0xad, 0x14, 0x31, - 0x66, 0x42, 0x1c, 0x70, 0x0c, 0xb6, 0x00, 0x01, 0xb6, 0x08, 0xdb, 0x00, - 0x8d, 0xc2, 0x14, 0xb2, 0x55, 0xa1, 0xfe, 0x09, 0xc2, 0x26, 0xdc, 0x25, - 0x75, 0x22, 0x97, 0x1a, 0x25, 0x77, 0x28, 0x31, 0x02, 0x80, 0xc8, 0xdd, - 0x2c, 0x11, 0x1a, 0x54, 0x9f, 0xc8, 0xa2, 0x8a, 0x06, 0xa9, 0x93, 0x22, - 0xbd, 0xd4, 0xd0, 0x0c, 0xcf, 0x81, 0x2b, 0xca, 0xbb, 0x83, 0xe0, 0x10, - 0xe6, 0xad, 0xff, 0x10, 0x2a, 0x66, 0x34, 0x41, 0x58, 0x35, 0x54, 0x49, - 0x5a, 0x63, 0xa5, 0xc2, 0x87, 0xab, 0x52, 0x76, 0x9a, 0xba, 0xc6, 0xf4, - 0x75, 0x7a, 0x9e, 0x3c, 0x46, 0x86, 0x5c, 0xa3, 0xfd, 0x87, 0x0e, 0x75, - 0x08, 0x7b, 0xee, 0x7e, 0xea, 0x21, 0x5c, 0x4f, 0xf6, 0xc5, 0xc8, 0x4b, - 0xb9, 0x11, 0xf2, 0xd6, 0xe1, 0x8f, 0x84, 0x62, 0x7b, 0x67, 0xf9, 0x24, - 0xde, 0x6d, 0xbc, 0xb2, 0xcd, 0xb1, 0xf3, 0xf2, 0x2f, 0xe8, 0xe2, 0xe4, - 0xae, 0x4b, 0x4f, 0xcf, 0x2b, 0xdc, 0x8d, 0x0d, 0xf0, 0x00, 0x8f, 0x22, - 0x26, 0x65, 0x75, 0x8a, 0xe6, 0x84, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, - 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 - }; +Vector2 TextServer::get_hex_code_box_size(int p_size, char32_t p_index) const { + int w = ((p_index <= 0xFF) ? 1 : ((p_index <= 0xFFFF) ? 2 : 3)); + int sp = MAX(0, w - 1); + int sz = MAX(1, p_size / 15); - if (RenderingServer::get_singleton() != nullptr) { - Vector<uint8_t> hex_box_data; - - Ref<Image> image; - image.instantiate(); - - Ref<ImageTexture> hex_code_image_tex[2]; - - hex_box_data.resize(tamsyn5x9_png_len); - memcpy(hex_box_data.ptrw(), tamsyn5x9_png, tamsyn5x9_png_len); - image->load_png_from_buffer(hex_box_data); - hex_code_image_tex[0].instantiate(); - hex_code_image_tex[0]->create_from_image(image); - hex_code_box_font_tex[0].instantiate(); - hex_code_box_font_tex[0]->set_diffuse_texture(hex_code_image_tex[0]); - hex_code_box_font_tex[0]->set_texture_filter(CanvasItem::TEXTURE_FILTER_NEAREST); - hex_box_data.clear(); - - hex_box_data.resize(tamsyn10x20_png_len); - memcpy(hex_box_data.ptrw(), tamsyn10x20_png, tamsyn10x20_png_len); - image->load_png_from_buffer(hex_box_data); - hex_code_image_tex[1].instantiate(); - hex_code_image_tex[1]->create_from_image(image); - hex_code_box_font_tex[1].instantiate(); - hex_code_box_font_tex[1]->set_diffuse_texture(hex_code_image_tex[1]); - hex_code_box_font_tex[1]->set_texture_filter(CanvasItem::TEXTURE_FILTER_NEAREST); - hex_box_data.clear(); - } + return Vector2(4 + 3 * w + sp + 1, 15) * sz; } -void TextServer::finish_hex_code_box_fonts() { - if (hex_code_box_font_tex[0].is_valid()) { - hex_code_box_font_tex[0].unref(); +void TextServer::_draw_hex_code_box_number(RID p_canvas, int p_size, const Vector2 &p_pos, uint8_t p_index, const Color &p_color) const { + static uint8_t chars[] = { 0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F, 0x70, 0x7F, 0x7B, 0x77, 0x1F, 0x4E, 0x3D, 0x4F, 0x47, 0x00 }; + uint8_t x = chars[p_index]; + if (x & (1 << 6)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos, Size2(3, 1) * p_size), p_color); } - if (hex_code_box_font_tex[1].is_valid()) { - hex_code_box_font_tex[1].unref(); + if (x & (1 << 5)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos + Point2(2, 0) * p_size, Size2(1, 3) * p_size), p_color); + } + if (x & (1 << 4)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos + Point2(2, 2) * p_size, Size2(1, 3) * p_size), p_color); + } + if (x & (1 << 3)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos + Point2(0, 4) * p_size, Size2(3, 1) * p_size), p_color); + } + if (x & (1 << 2)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos + Point2(0, 2) * p_size, Size2(1, 3) * p_size), p_color); + } + if (x & (1 << 1)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos, Size2(1, 3) * p_size), p_color); + } + if (x & (1 << 0)) { + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(p_pos + Point2(0, 2) * p_size, Size2(3, 1) * p_size), p_color); } -} - -Vector2 TextServer::get_hex_code_box_size(int p_size, char32_t p_index) const { - int fnt = (p_size < 20) ? 0 : 1; - - real_t w = ((p_index <= 0xFF) ? 1 : ((p_index <= 0xFFFF) ? 2 : 3)) * hex_code_box_font_size[fnt].x; - real_t h = 2 * hex_code_box_font_size[fnt].y; - return Vector2(w + 4, h + 3 + 2 * hex_code_box_font_size[fnt].z); } void TextServer::draw_hex_code_box(RID p_canvas, int p_size, const Vector2 &p_pos, char32_t p_index, const Color &p_color) const { - int fnt = (p_size < 20) ? 0 : 1; - - ERR_FAIL_COND(hex_code_box_font_tex[fnt].is_null()); if (p_index == 0) { return; } + int w = ((p_index <= 0xFF) ? 1 : ((p_index <= 0xFFFF) ? 2 : 3)); + int sp = MAX(0, w - 1); + int sz = MAX(1, p_size / 15); + + Size2 size = Vector2(4 + 3 * w + sp, 15) * sz; + Point2 pos = p_pos - Point2i(0, size.y * 0.85); + + // Draw frame. + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, 0), Size2(sz, size.y)), p_color); + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(size.x - sz, 0), Size2(sz, size.y)), p_color); + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, 0), Size2(size.x, sz)), p_color); + RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, size.y - sz), Size2(size.x, sz)), p_color); + uint8_t a = p_index & 0x0F; uint8_t b = (p_index >> 4) & 0x0F; uint8_t c = (p_index >> 8) & 0x0F; @@ -591,47 +538,22 @@ void TextServer::draw_hex_code_box(RID p_canvas, int p_size, const Vector2 &p_po uint8_t e = (p_index >> 16) & 0x0F; uint8_t f = (p_index >> 20) & 0x0F; - Vector2 pos = p_pos; - Rect2 dest = Rect2(Vector2(), Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y)); - - real_t w = ((p_index <= 0xFF) ? 1 : ((p_index <= 0xFFFF) ? 2 : 3)) * hex_code_box_font_size[fnt].x; - real_t h = 2 * hex_code_box_font_size[fnt].y; - - pos.y -= Math::floor((h + 3 + hex_code_box_font_size[fnt].z)); - - RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, 0), Size2(1, h + 2 + 2 * hex_code_box_font_size[fnt].z)), p_color); - RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(w + 2, 0), Size2(1, h + 2 + 2 * hex_code_box_font_size[fnt].z)), p_color); - RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, 0), Size2(w + 3, 1)), p_color); - RenderingServer::get_singleton()->canvas_item_add_rect(p_canvas, Rect2(pos + Point2(0, h + 2 + 2 * hex_code_box_font_size[fnt].z), Size2(w + 3, 1)), p_color); - - pos += Point2(2, 2); + // Draw hex code. if (p_index <= 0xFF) { - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(b * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(a * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 2) * sz, b, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 8) * sz, a, p_color); } else if (p_index <= 0xFFFF) { - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(d * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(1, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(c * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(b * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(1, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(a * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 2) * sz, d, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(6, 2) * sz, c, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 8) * sz, b, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(6, 8) * sz, a, p_color); } else { - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(f * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(1, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(e * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(2, 0); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(d * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(0, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(c * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(1, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(b * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); - dest.position = pos + Vector2(hex_code_box_font_size[fnt].x, hex_code_box_font_size[fnt].y) * Point2(2, 1) + Point2(0, hex_code_box_font_size[fnt].z); - RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, dest, hex_code_box_font_tex[fnt]->get_rid(), Rect2(Point2(a * hex_code_box_font_size[fnt].x, 0), dest.size), p_color, false, false); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 2) * sz, f, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(6, 2) * sz, e, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(10, 2) * sz, d, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(2, 8) * sz, c, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(6, 8) * sz, b, p_color); + _draw_hex_code_box_number(p_canvas, sz, pos + Point2(10, 8) * sz, a, p_color); } } diff --git a/servers/text_server.h b/servers/text_server.h index da62ff8ef4..3a5f946fbf 100644 --- a/servers/text_server.h +++ b/servers/text_server.h @@ -36,9 +36,6 @@ #include "core/templates/rid.h" #include "core/variant/native_ptr.h" #include "core/variant/variant.h" -#include "scene/resources/texture.h" - -class CanvasTexture; struct Glyph; struct CaretInfo; @@ -128,6 +125,8 @@ public: SPACING_BOTTOM, }; + void _draw_hex_code_box_number(RID p_canvas, int p_size, const Vector2 &p_pos, uint8_t p_index, const Color &p_color) const; + protected: struct TrimData { int trim_pos = -1; @@ -197,13 +196,7 @@ protected: static void _bind_methods(); - static Vector3 hex_code_box_font_size[2]; - static Ref<CanvasTexture> hex_code_box_font_tex[2]; - public: - static void initialize_hex_code_box_fonts(); - static void finish_hex_code_box_fonts(); - virtual bool has_feature(Feature p_feature) const = 0; virtual String get_name() const = 0; virtual uint32_t get_features() const = 0; diff --git a/tests/test_code_edit.h b/tests/test_code_edit.h index 0e31a976bf..62235ed0ae 100644 --- a/tests/test_code_edit.h +++ b/tests/test_code_edit.h @@ -284,6 +284,26 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { CHECK_FALSE(code_edit->is_line_breakpointed(1)); ERR_PRINT_ON; SIGNAL_CHECK("breakpoint_toggled", args); + + /* Backspace above breakpointed line moves it. */ + ((Array)args[0])[0] = 2; + + code_edit->set_text("\n\n"); + code_edit->set_line_as_breakpoint(2, true); + CHECK(code_edit->is_line_breakpointed(2)); + SIGNAL_CHECK("breakpoint_toggled", args); + + code_edit->set_caret_line(1); + + Array arg2; + arg2.push_back(1); + args.push_back(arg2); + SEND_GUI_ACTION(code_edit, "ui_text_backspace"); + ERR_PRINT_OFF; + CHECK_FALSE(code_edit->is_line_breakpointed(2)); + ERR_PRINT_ON; + CHECK(code_edit->is_line_breakpointed(1)); + SIGNAL_CHECK("breakpoint_toggled", args); } SUBCASE("[CodeEdit] breakpoints and delete") { @@ -312,6 +332,26 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { CHECK_FALSE(code_edit->is_line_breakpointed(1)); ERR_PRINT_ON; SIGNAL_CHECK("breakpoint_toggled", args); + + /* Delete above breakpointed line moves it. */ + ((Array)args[0])[0] = 2; + + code_edit->set_text("\n\n"); + code_edit->set_line_as_breakpoint(2, true); + CHECK(code_edit->is_line_breakpointed(2)); + SIGNAL_CHECK("breakpoint_toggled", args); + + code_edit->set_caret_line(0); + + Array arg2; + arg2.push_back(1); + args.push_back(arg2); + SEND_GUI_ACTION(code_edit, "ui_text_delete"); + ERR_PRINT_OFF; + CHECK_FALSE(code_edit->is_line_breakpointed(2)); + ERR_PRINT_ON; + CHECK(code_edit->is_line_breakpointed(1)); + SIGNAL_CHECK("breakpoint_toggled", args); } SUBCASE("[CodeEdit] breakpoints and delete selection") { @@ -330,6 +370,41 @@ TEST_CASE("[SceneTree][CodeEdit] line gutters") { MessageQueue::get_singleton()->flush(); CHECK_FALSE(code_edit->is_line_breakpointed(0)); SIGNAL_CHECK("breakpoint_toggled", args); + + /* Should handle breakpoint move when deleting selection by adding less text then removed. */ + ((Array)args[0])[0] = 9; + + code_edit->set_text("\n\n\n\n\n\n\n\n\n"); + code_edit->set_line_as_breakpoint(9, true); + CHECK(code_edit->is_line_breakpointed(9)); + SIGNAL_CHECK("breakpoint_toggled", args); + + code_edit->select(0, 0, 6, 0); + + Array arg2; + arg2.push_back(4); + args.push_back(arg2); + SEND_GUI_ACTION(code_edit, "ui_text_newline"); + ERR_PRINT_OFF; + CHECK_FALSE(code_edit->is_line_breakpointed(9)); + ERR_PRINT_ON; + CHECK(code_edit->is_line_breakpointed(4)); + SIGNAL_CHECK("breakpoint_toggled", args); + + /* Should handle breakpoint move when deleting selection by adding more text then removed. */ + ((Array)args[0])[0] = 9; + ((Array)args[1])[0] = 14; + + code_edit->insert_text_at_caret("\n\n\n\n\n"); + MessageQueue::get_singleton()->flush(); + SIGNAL_DISCARD("breakpoint_toggled") + CHECK(code_edit->is_line_breakpointed(9)); + + code_edit->select(0, 0, 6, 0); + code_edit->insert_text_at_caret("\n\n\n\n\n\n\n\n\n\n\n"); + MessageQueue::get_singleton()->flush(); + CHECK(code_edit->is_line_breakpointed(14)); + SIGNAL_CHECK("breakpoint_toggled", args); } SUBCASE("[CodeEdit] breakpoints and undo") { diff --git a/tests/test_shader_lang.cpp b/tests/test_shader_lang.cpp index 6d58eb63cc..5598852f29 100644 --- a/tests/test_shader_lang.cpp +++ b/tests/test_shader_lang.cpp @@ -125,23 +125,28 @@ static String dump_node_code(SL::Node *p_node, int p_level) { ucode += _prestr(E.value.precision); ucode += _typestr(E.value.type); ucode += " " + String(E.key); + if (E.value.array_size > 0) { + ucode += "["; + ucode += itos(E.value.array_size); + ucode += "]"; + } else { + if (E.value.default_value.size()) { + ucode += " = " + get_constant_text(E.value.type, E.value.default_value); + } - if (E.value.default_value.size()) { - ucode += " = " + get_constant_text(E.value.type, E.value.default_value); - } - - static const char *hint_name[SL::ShaderNode::Uniform::HINT_MAX] = { - "", - "color", - "range", - "albedo", - "normal", - "black", - "white" - }; - - if (E.value.hint) { - ucode += " : " + String(hint_name[E.value.hint]); + static const char *hint_name[SL::ShaderNode::Uniform::HINT_MAX] = { + "", + "color", + "range", + "albedo", + "normal", + "black", + "white" + }; + + if (E.value.hint) { + ucode += " : " + String(hint_name[E.value.hint]); + } } code += ucode + "\n"; diff --git a/thirdparty/README.md b/thirdparty/README.md index 3d32609088..e7ceea6268 100644 --- a/thirdparty/README.md +++ b/thirdparty/README.md @@ -28,7 +28,7 @@ Files extracted from upstream source: - `src/*` apart from CMakeLists.txt and premake4.lua files - `LICENSE.txt`, and `VERSION` as `VERSION.txt` -Includes a warning fix which should be upstreamed soon (see patch in `patches`). +Includes some patches in the `patches` folder which have been sent upstream. ## certs @@ -138,11 +138,6 @@ Files extracted from upstream source: * Upstream: https://fonts.google.com/specimen/Open+Sans * Version: 1.10 (downloaded from Google Fonts in February 2021) * License: Apache 2.0 -- `Tamsyn*.png`: - * Upstream: http://www.fial.com/~scott/tamsyn-font/ - * Version: 1.11 (2015) - * License: Tamsyn - * Comment: Extracted "0..9,A..F" characters for hex code printing. ## freetype diff --git a/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp b/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp index 922e449cce..5862264a67 100644 --- a/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp +++ b/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp @@ -82,6 +82,11 @@ typedef BOOL(WINAPI* Pfn_GetLogicalProcessorInformation)(PSYSTEM_LOGICAL_PROCESS void getProcessorInformation(btProcessorInfo* procInfo) { memset(procInfo, 0, sizeof(*procInfo)); +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ + !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + // Can't dlopen libraries on UWP. + return; +#else Pfn_GetLogicalProcessorInformation getLogicalProcInfo = (Pfn_GetLogicalProcessorInformation)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if (getLogicalProcInfo == NULL) @@ -160,6 +165,7 @@ void getProcessorInformation(btProcessorInfo* procInfo) } } free(buf); +#endif } ///btThreadSupportWin32 helps to initialize/shutdown libspe2, start/stop SPU tasks and communication diff --git a/thirdparty/bullet/patches/fix-win32-scheduler-uwp.patch b/thirdparty/bullet/patches/fix-win32-scheduler-uwp.patch new file mode 100644 index 0000000000..c65db49388 --- /dev/null +++ b/thirdparty/bullet/patches/fix-win32-scheduler-uwp.patch @@ -0,0 +1,24 @@ +diff --git a/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp b/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp +index 922e449cce..5862264a67 100644 +--- a/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp ++++ b/thirdparty/bullet/LinearMath/TaskScheduler/btThreadSupportWin32.cpp +@@ -82,6 +82,11 @@ typedef BOOL(WINAPI* Pfn_GetLogicalProcessorInformation)(PSYSTEM_LOGICAL_PROCESS + void getProcessorInformation(btProcessorInfo* procInfo) + { + memset(procInfo, 0, sizeof(*procInfo)); ++#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ ++ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) ++ // Can't dlopen libraries on UWP. ++ return; ++#else + Pfn_GetLogicalProcessorInformation getLogicalProcInfo = + (Pfn_GetLogicalProcessorInformation)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); + if (getLogicalProcInfo == NULL) +@@ -160,6 +165,7 @@ void getProcessorInformation(btProcessorInfo* procInfo) + } + } + free(buf); ++#endif + } + + ///btThreadSupportWin32 helps to initialize/shutdown libspe2, start/stop SPU tasks and communication diff --git a/thirdparty/doctest/LICENSE.txt b/thirdparty/doctest/LICENSE.txt index 50a358cd1b..d67bb64f9d 100644 --- a/thirdparty/doctest/LICENSE.txt +++ b/thirdparty/doctest/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016-2020 Viktor Kirilov +Copyright (c) 2016-2021 Viktor Kirilov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/thirdparty/doctest/doctest.h b/thirdparty/doctest/doctest.h index 7712dd6b63..42eb039979 100644 --- a/thirdparty/doctest/doctest.h +++ b/thirdparty/doctest/doctest.h @@ -4,7 +4,7 @@ // // doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD // -// Copyright (c) 2016-2020 Viktor Kirilov +// Copyright (c) 2016-2021 Viktor Kirilov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at @@ -48,8 +48,8 @@ #define DOCTEST_VERSION_MAJOR 2 #define DOCTEST_VERSION_MINOR 4 -#define DOCTEST_VERSION_PATCH 4 -#define DOCTEST_VERSION_STR "2.4.4" +#define DOCTEST_VERSION_PATCH 6 +#define DOCTEST_VERSION_STR "2.4.6" #define DOCTEST_VERSION \ (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) @@ -354,7 +354,7 @@ DOCTEST_MSVC_SUPPRESS_WARNING(26812) // Prefer 'enum class' over 'enum' #define DOCTEST_GLOBAL_NO_WARNINGS(var) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-variable") \ - static int var DOCTEST_UNUSED // NOLINT(fuchsia-statically-constructed-objects,cert-err58-cpp) + static const int var DOCTEST_UNUSED // NOLINT(fuchsia-statically-constructed-objects,cert-err58-cpp) #define DOCTEST_GLOBAL_NO_WARNINGS_END() DOCTEST_CLANG_SUPPRESS_WARNING_POP #ifndef DOCTEST_BREAK_INTO_DEBUGGER @@ -362,16 +362,16 @@ DOCTEST_MSVC_SUPPRESS_WARNING(26812) // Prefer 'enum class' over 'enum' #ifdef DOCTEST_PLATFORM_LINUX #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) // Break at the location of the failing check if possible -#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT (hicpp-no-assembler) #else #include <signal.h> #define DOCTEST_BREAK_INTO_DEBUGGER() raise(SIGTRAP) #endif #elif defined(DOCTEST_PLATFORM_MAC) #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) -#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT (hicpp-no-assembler) #else -#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); // NOLINT (hicpp-no-assembler) #endif #elif DOCTEST_MSVC #define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() @@ -656,12 +656,14 @@ DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); struct DOCTEST_INTERFACE TestCaseData { - String m_file; // the file in which the test was registered + String m_file; // the file in which the test was registered (using String - see #350) unsigned m_line; // the line where the test was registered const char* m_name; // name of the test case const char* m_test_suite; // the test suite in which the test was added const char* m_description; bool m_skip; + bool m_no_breaks; + bool m_no_output; bool m_may_fail; bool m_should_fail; int m_expected_failures; @@ -715,12 +717,18 @@ struct DOCTEST_INTERFACE IContextScope virtual void stringify(std::ostream*) const = 0; }; +namespace detail { + struct DOCTEST_INTERFACE TestCase; +} // namespace detail + struct ContextOptions //!OCLINT too many fields { std::ostream* cout; // stdout stream - std::cout by default std::ostream* cerr; // stderr stream - std::cerr by default String binary_name; // the test binary name + const detail::TestCase* currentTest = nullptr; + // == parameters from the command line String out; // output filename String order_by; // how tests should be ordered @@ -773,6 +781,29 @@ namespace detail { template<class T> struct remove_reference<T&> { typedef T type; }; template<class T> struct remove_reference<T&&> { typedef T type; }; + template<typename T, typename U = T&&> U declval(int); + + template<typename T> T declval(long); + + template<typename T> auto declval() DOCTEST_NOEXCEPT -> decltype(declval<T>(0)) ; + + template<class T> struct is_lvalue_reference { const static bool value=false; }; + template<class T> struct is_lvalue_reference<T&> { const static bool value=true; }; + + template <class T> + inline T&& forward(typename remove_reference<T>::type& t) DOCTEST_NOEXCEPT + { + return static_cast<T&&>(t); + } + + template <class T> + inline T&& forward(typename remove_reference<T>::type&& t) DOCTEST_NOEXCEPT + { + static_assert(!is_lvalue_reference<T>::value, + "Can not forward an rvalue as an lvalue."); + return static_cast<T&&>(t); + } + template<class T> struct remove_const { typedef T type; }; template<class T> struct remove_const<const T> { typedef T type; }; #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS @@ -1040,10 +1071,20 @@ namespace detail { return toString(lhs) + op + toString(rhs); } +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-comparison") +#endif + +// This will check if there is any way it could find a operator like member or friend and uses it. +// If not it doesn't find the operator or if the operator at global scope is defined after +// this template, the template won't be instantiated due to SFINAE. Once the template is not +// instantiated it can look for global operator using normal conversions. +#define SFINAE_OP(ret,op) decltype(doctest::detail::declval<L>() op doctest::detail::declval<R>(),static_cast<ret>(0)) + #define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ template <typename R> \ - DOCTEST_NOINLINE Result operator op(const DOCTEST_REF_WRAP(R) rhs) { \ - bool res = op_macro(lhs, rhs); \ + DOCTEST_NOINLINE SFINAE_OP(Result,op) operator op(R&& rhs) { \ + bool res = op_macro(doctest::detail::forward<L>(lhs), doctest::detail::forward<R>(rhs)); \ if(m_at & assertType::is_false) \ res = !res; \ if(!res || doctest::getContextOptions()->success) \ @@ -1171,12 +1212,16 @@ namespace detail { L lhs; assertType::Enum m_at; - explicit Expression_lhs(L in, assertType::Enum at) - : lhs(in) + explicit Expression_lhs(L&& in, assertType::Enum at) + : lhs(doctest::detail::forward<L>(in)) , m_at(at) {} DOCTEST_NOINLINE operator Result() { - bool res = !!lhs; +// this is needed only foc MSVC 2015: +// https://ci.appveyor.com/project/onqtam/doctest/builds/38181202 +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4800) // 'int': forcing value to bool + bool res = static_cast<bool>(lhs); +DOCTEST_MSVC_SUPPRESS_WARNING_POP if(m_at & assertType::is_false) //!OCLINT bitwise operator in conditional res = !res; @@ -1185,6 +1230,10 @@ namespace detail { return Result(res); } + /* This is required for user-defined conversions from Expression_lhs to L */ + //operator L() const { return lhs; } + operator L() const { return lhs; } + // clang-format off DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional @@ -1225,6 +1274,10 @@ namespace detail { #endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_POP +#endif + struct DOCTEST_INTERFACE ExpressionDecomposer { assertType::Enum m_at; @@ -1236,8 +1289,8 @@ namespace detail { // https://github.com/catchorg/Catch2/issues/870 // https://github.com/catchorg/Catch2/issues/565 template <typename L> - Expression_lhs<const DOCTEST_REF_WRAP(L)> operator<<(const DOCTEST_REF_WRAP(L) operand) { - return Expression_lhs<const DOCTEST_REF_WRAP(L)>(operand, m_at); + Expression_lhs<L> operator<<(L &&operand) { + return Expression_lhs<L>(doctest::detail::forward<L>(operand), m_at); } }; @@ -1246,6 +1299,8 @@ namespace detail { const char* m_test_suite; const char* m_description; bool m_skip; + bool m_no_breaks; + bool m_no_output; bool m_may_fail; bool m_should_fail; int m_expected_failures; @@ -1524,7 +1579,7 @@ namespace detail { template <typename L> class ContextScope : public ContextScopeBase { - const L &lambda_; + const L lambda_; public: explicit ContextScope(const L &lambda) : lambda_(lambda) {} @@ -1585,6 +1640,8 @@ namespace detail { DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); DOCTEST_DEFINE_DECORATOR(description, const char*, ""); DOCTEST_DEFINE_DECORATOR(skip, bool, true); +DOCTEST_DEFINE_DECORATOR(no_breaks, bool, true); +DOCTEST_DEFINE_DECORATOR(no_output, bool, true); DOCTEST_DEFINE_DECORATOR(timeout, double, 0); DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); @@ -1921,10 +1978,12 @@ int registerReporter(const char* name, int priority, bool isReporter) { static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() { \ DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ - static doctest::detail::TestSuite data; \ + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmissing-field-initializers") \ + static doctest::detail::TestSuite data{}; \ static bool inited = false; \ DOCTEST_MSVC_SUPPRESS_WARNING_POP \ DOCTEST_CLANG_SUPPRESS_WARNING_POP \ + DOCTEST_GCC_SUPPRESS_WARNING_POP \ if(!inited) { \ data* decorators; \ inited = true; \ @@ -1979,17 +2038,15 @@ int registerReporter(const char* name, int priority, bool isReporter) { // for logging #define DOCTEST_INFO(...) \ DOCTEST_INFO_IMPL(DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_), DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_), \ - DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_), __VA_ARGS__) + __VA_ARGS__) -#define DOCTEST_INFO_IMPL(lambda_name, mb_name, s_name, ...) \ - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4626) \ - auto lambda_name = [&](std::ostream* s_name) { \ +#define DOCTEST_INFO_IMPL(mb_name, s_name, ...) \ + auto DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope( \ + [&](std::ostream* s_name) { \ doctest::detail::MessageBuilder mb_name(__FILE__, __LINE__, doctest::assertType::is_warn); \ mb_name.m_stream = s_name; \ mb_name * __VA_ARGS__; \ - }; \ - DOCTEST_MSVC_SUPPRESS_WARNING_POP \ - auto DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope(lambda_name) + }) #define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := ", x) @@ -2461,7 +2518,7 @@ int registerReporter(const char* name, int priority, bool isReporter) { #define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE #define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE -#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE DOCTEST_TEST_CASE_TEMPLATE_INVOKE +#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id,__VA_ARGS__) // clang-format on // BDD style macros @@ -2481,138 +2538,138 @@ int registerReporter(const char* name, int priority, bool isReporter) { // == SHORT VERSIONS OF THE MACROS #if !defined(DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES) -#define TEST_CASE DOCTEST_TEST_CASE -#define TEST_CASE_CLASS DOCTEST_TEST_CASE_CLASS -#define TEST_CASE_FIXTURE DOCTEST_TEST_CASE_FIXTURE -#define TYPE_TO_STRING DOCTEST_TYPE_TO_STRING -#define TEST_CASE_TEMPLATE DOCTEST_TEST_CASE_TEMPLATE -#define TEST_CASE_TEMPLATE_DEFINE DOCTEST_TEST_CASE_TEMPLATE_DEFINE -#define TEST_CASE_TEMPLATE_INVOKE DOCTEST_TEST_CASE_TEMPLATE_INVOKE -#define TEST_CASE_TEMPLATE_APPLY DOCTEST_TEST_CASE_TEMPLATE_APPLY -#define SUBCASE DOCTEST_SUBCASE -#define TEST_SUITE DOCTEST_TEST_SUITE -#define TEST_SUITE_BEGIN DOCTEST_TEST_SUITE_BEGIN +#define TEST_CASE(name) DOCTEST_TEST_CASE(name) +#define TEST_CASE_CLASS(name) DOCTEST_TEST_CASE_CLASS(name) +#define TEST_CASE_FIXTURE(x, name) DOCTEST_TEST_CASE_FIXTURE(x, name) +#define TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING(__VA_ARGS__) +#define TEST_CASE_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(name, T, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, T, id) +#define TEST_CASE_TEMPLATE_INVOKE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_APPLY(id, ...) DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, __VA_ARGS__) +#define SUBCASE(name) DOCTEST_SUBCASE(name) +#define TEST_SUITE(decorators) DOCTEST_TEST_SUITE(decorators) +#define TEST_SUITE_BEGIN(name) DOCTEST_TEST_SUITE_BEGIN(name) #define TEST_SUITE_END DOCTEST_TEST_SUITE_END -#define REGISTER_EXCEPTION_TRANSLATOR DOCTEST_REGISTER_EXCEPTION_TRANSLATOR -#define REGISTER_REPORTER DOCTEST_REGISTER_REPORTER -#define REGISTER_LISTENER DOCTEST_REGISTER_LISTENER -#define INFO DOCTEST_INFO -#define CAPTURE DOCTEST_CAPTURE -#define ADD_MESSAGE_AT DOCTEST_ADD_MESSAGE_AT -#define ADD_FAIL_CHECK_AT DOCTEST_ADD_FAIL_CHECK_AT -#define ADD_FAIL_AT DOCTEST_ADD_FAIL_AT -#define MESSAGE DOCTEST_MESSAGE -#define FAIL_CHECK DOCTEST_FAIL_CHECK -#define FAIL DOCTEST_FAIL -#define TO_LVALUE DOCTEST_TO_LVALUE - -#define WARN DOCTEST_WARN -#define WARN_FALSE DOCTEST_WARN_FALSE -#define WARN_THROWS DOCTEST_WARN_THROWS -#define WARN_THROWS_AS DOCTEST_WARN_THROWS_AS -#define WARN_THROWS_WITH DOCTEST_WARN_THROWS_WITH -#define WARN_THROWS_WITH_AS DOCTEST_WARN_THROWS_WITH_AS -#define WARN_NOTHROW DOCTEST_WARN_NOTHROW -#define CHECK DOCTEST_CHECK -#define CHECK_FALSE DOCTEST_CHECK_FALSE -#define CHECK_THROWS DOCTEST_CHECK_THROWS -#define CHECK_THROWS_AS DOCTEST_CHECK_THROWS_AS -#define CHECK_THROWS_WITH DOCTEST_CHECK_THROWS_WITH -#define CHECK_THROWS_WITH_AS DOCTEST_CHECK_THROWS_WITH_AS -#define CHECK_NOTHROW DOCTEST_CHECK_NOTHROW -#define REQUIRE DOCTEST_REQUIRE -#define REQUIRE_FALSE DOCTEST_REQUIRE_FALSE -#define REQUIRE_THROWS DOCTEST_REQUIRE_THROWS -#define REQUIRE_THROWS_AS DOCTEST_REQUIRE_THROWS_AS -#define REQUIRE_THROWS_WITH DOCTEST_REQUIRE_THROWS_WITH -#define REQUIRE_THROWS_WITH_AS DOCTEST_REQUIRE_THROWS_WITH_AS -#define REQUIRE_NOTHROW DOCTEST_REQUIRE_NOTHROW - -#define WARN_MESSAGE DOCTEST_WARN_MESSAGE -#define WARN_FALSE_MESSAGE DOCTEST_WARN_FALSE_MESSAGE -#define WARN_THROWS_MESSAGE DOCTEST_WARN_THROWS_MESSAGE -#define WARN_THROWS_AS_MESSAGE DOCTEST_WARN_THROWS_AS_MESSAGE -#define WARN_THROWS_WITH_MESSAGE DOCTEST_WARN_THROWS_WITH_MESSAGE -#define WARN_THROWS_WITH_AS_MESSAGE DOCTEST_WARN_THROWS_WITH_AS_MESSAGE -#define WARN_NOTHROW_MESSAGE DOCTEST_WARN_NOTHROW_MESSAGE -#define CHECK_MESSAGE DOCTEST_CHECK_MESSAGE -#define CHECK_FALSE_MESSAGE DOCTEST_CHECK_FALSE_MESSAGE -#define CHECK_THROWS_MESSAGE DOCTEST_CHECK_THROWS_MESSAGE -#define CHECK_THROWS_AS_MESSAGE DOCTEST_CHECK_THROWS_AS_MESSAGE -#define CHECK_THROWS_WITH_MESSAGE DOCTEST_CHECK_THROWS_WITH_MESSAGE -#define CHECK_THROWS_WITH_AS_MESSAGE DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE -#define CHECK_NOTHROW_MESSAGE DOCTEST_CHECK_NOTHROW_MESSAGE -#define REQUIRE_MESSAGE DOCTEST_REQUIRE_MESSAGE -#define REQUIRE_FALSE_MESSAGE DOCTEST_REQUIRE_FALSE_MESSAGE -#define REQUIRE_THROWS_MESSAGE DOCTEST_REQUIRE_THROWS_MESSAGE -#define REQUIRE_THROWS_AS_MESSAGE DOCTEST_REQUIRE_THROWS_AS_MESSAGE -#define REQUIRE_THROWS_WITH_MESSAGE DOCTEST_REQUIRE_THROWS_WITH_MESSAGE -#define REQUIRE_THROWS_WITH_AS_MESSAGE DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE -#define REQUIRE_NOTHROW_MESSAGE DOCTEST_REQUIRE_NOTHROW_MESSAGE - -#define SCENARIO DOCTEST_SCENARIO -#define SCENARIO_CLASS DOCTEST_SCENARIO_CLASS -#define SCENARIO_TEMPLATE DOCTEST_SCENARIO_TEMPLATE -#define SCENARIO_TEMPLATE_DEFINE DOCTEST_SCENARIO_TEMPLATE_DEFINE -#define GIVEN DOCTEST_GIVEN -#define WHEN DOCTEST_WHEN -#define AND_WHEN DOCTEST_AND_WHEN -#define THEN DOCTEST_THEN -#define AND_THEN DOCTEST_AND_THEN - -#define WARN_EQ DOCTEST_WARN_EQ -#define CHECK_EQ DOCTEST_CHECK_EQ -#define REQUIRE_EQ DOCTEST_REQUIRE_EQ -#define WARN_NE DOCTEST_WARN_NE -#define CHECK_NE DOCTEST_CHECK_NE -#define REQUIRE_NE DOCTEST_REQUIRE_NE -#define WARN_GT DOCTEST_WARN_GT -#define CHECK_GT DOCTEST_CHECK_GT -#define REQUIRE_GT DOCTEST_REQUIRE_GT -#define WARN_LT DOCTEST_WARN_LT -#define CHECK_LT DOCTEST_CHECK_LT -#define REQUIRE_LT DOCTEST_REQUIRE_LT -#define WARN_GE DOCTEST_WARN_GE -#define CHECK_GE DOCTEST_CHECK_GE -#define REQUIRE_GE DOCTEST_REQUIRE_GE -#define WARN_LE DOCTEST_WARN_LE -#define CHECK_LE DOCTEST_CHECK_LE -#define REQUIRE_LE DOCTEST_REQUIRE_LE -#define WARN_UNARY DOCTEST_WARN_UNARY -#define CHECK_UNARY DOCTEST_CHECK_UNARY -#define REQUIRE_UNARY DOCTEST_REQUIRE_UNARY -#define WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE -#define CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE -#define REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE +#define REGISTER_EXCEPTION_TRANSLATOR(signature) DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) +#define REGISTER_REPORTER(name, priority, reporter) DOCTEST_REGISTER_REPORTER(name, priority, reporter) +#define REGISTER_LISTENER(name, priority, reporter) DOCTEST_REGISTER_LISTENER(name, priority, reporter) +#define INFO(...) DOCTEST_INFO(__VA_ARGS__) +#define CAPTURE(x) DOCTEST_CAPTURE(x) +#define ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_MESSAGE_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_FAIL_CHECK_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_FAIL_AT(file, line, __VA_ARGS__) +#define MESSAGE(...) DOCTEST_MESSAGE(__VA_ARGS__) +#define FAIL_CHECK(...) DOCTEST_FAIL_CHECK(__VA_ARGS__) +#define FAIL(...) DOCTEST_FAIL(__VA_ARGS__) +#define TO_LVALUE(...) DOCTEST_TO_LVALUE(__VA_ARGS__) + +#define WARN(...) DOCTEST_WARN(__VA_ARGS__) +#define WARN_FALSE(...) DOCTEST_WARN_FALSE(__VA_ARGS__) +#define WARN_THROWS(...) DOCTEST_WARN_THROWS(__VA_ARGS__) +#define WARN_THROWS_AS(expr, ...) DOCTEST_WARN_THROWS_AS(expr, __VA_ARGS__) +#define WARN_THROWS_WITH(expr, ...) DOCTEST_WARN_THROWS_WITH(expr, __VA_ARGS__) +#define WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_WARN_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define WARN_NOTHROW(...) DOCTEST_WARN_NOTHROW(__VA_ARGS__) +#define CHECK(...) DOCTEST_CHECK(__VA_ARGS__) +#define CHECK_FALSE(...) DOCTEST_CHECK_FALSE(__VA_ARGS__) +#define CHECK_THROWS(...) DOCTEST_CHECK_THROWS(__VA_ARGS__) +#define CHECK_THROWS_AS(expr, ...) DOCTEST_CHECK_THROWS_AS(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH(expr, ...) DOCTEST_CHECK_THROWS_WITH(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define CHECK_NOTHROW(...) DOCTEST_CHECK_NOTHROW(__VA_ARGS__) +#define REQUIRE(...) DOCTEST_REQUIRE(__VA_ARGS__) +#define REQUIRE_FALSE(...) DOCTEST_REQUIRE_FALSE(__VA_ARGS__) +#define REQUIRE_THROWS(...) DOCTEST_REQUIRE_THROWS(__VA_ARGS__) +#define REQUIRE_THROWS_AS(expr, ...) DOCTEST_REQUIRE_THROWS_AS(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH(expr, ...) DOCTEST_REQUIRE_THROWS_WITH(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define REQUIRE_NOTHROW(...) DOCTEST_REQUIRE_NOTHROW(__VA_ARGS__) + +#define WARN_MESSAGE(cond, ...) DOCTEST_WARN_MESSAGE(cond, __VA_ARGS__) +#define WARN_FALSE_MESSAGE(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__) +#define WARN_THROWS_MESSAGE(expr, ...) DOCTEST_WARN_THROWS_MESSAGE(expr, __VA_ARGS__) +#define WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_WARN_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define CHECK_MESSAGE(cond, ...) DOCTEST_CHECK_MESSAGE(cond, __VA_ARGS__) +#define CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__) +#define CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_CHECK_THROWS_MESSAGE(expr, __VA_ARGS__) +#define CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_CHECK_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_MESSAGE(cond, ...) DOCTEST_REQUIRE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_REQUIRE_THROWS_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, __VA_ARGS__) + +#define SCENARIO(name) DOCTEST_SCENARIO(name) +#define SCENARIO_CLASS(name) DOCTEST_SCENARIO_CLASS(name) +#define SCENARIO_TEMPLATE(name, T, ...) DOCTEST_SCENARIO_TEMPLATE(name, T, __VA_ARGS__) +#define SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) +#define GIVEN(name) DOCTEST_GIVEN(name) +#define WHEN(name) DOCTEST_WHEN(name) +#define AND_WHEN(name) DOCTEST_AND_WHEN(name) +#define THEN(name) DOCTEST_THEN(name) +#define AND_THEN(name) DOCTEST_AND_THEN(name) + +#define WARN_EQ(...) DOCTEST_WARN_EQ(__VA_ARGS__) +#define CHECK_EQ(...) DOCTEST_CHECK_EQ(__VA_ARGS__) +#define REQUIRE_EQ(...) DOCTEST_REQUIRE_EQ(__VA_ARGS__) +#define WARN_NE(...) DOCTEST_WARN_NE(__VA_ARGS__) +#define CHECK_NE(...) DOCTEST_CHECK_NE(__VA_ARGS__) +#define REQUIRE_NE(...) DOCTEST_REQUIRE_NE(__VA_ARGS__) +#define WARN_GT(...) DOCTEST_WARN_GT(__VA_ARGS__) +#define CHECK_GT(...) DOCTEST_CHECK_GT(__VA_ARGS__) +#define REQUIRE_GT(...) DOCTEST_REQUIRE_GT(__VA_ARGS__) +#define WARN_LT(...) DOCTEST_WARN_LT(__VA_ARGS__) +#define CHECK_LT(...) DOCTEST_CHECK_LT(__VA_ARGS__) +#define REQUIRE_LT(...) DOCTEST_REQUIRE_LT(__VA_ARGS__) +#define WARN_GE(...) DOCTEST_WARN_GE(__VA_ARGS__) +#define CHECK_GE(...) DOCTEST_CHECK_GE(__VA_ARGS__) +#define REQUIRE_GE(...) DOCTEST_REQUIRE_GE(__VA_ARGS__) +#define WARN_LE(...) DOCTEST_WARN_LE(__VA_ARGS__) +#define CHECK_LE(...) DOCTEST_CHECK_LE(__VA_ARGS__) +#define REQUIRE_LE(...) DOCTEST_REQUIRE_LE(__VA_ARGS__) +#define WARN_UNARY(...) DOCTEST_WARN_UNARY(__VA_ARGS__) +#define CHECK_UNARY(...) DOCTEST_CHECK_UNARY(__VA_ARGS__) +#define REQUIRE_UNARY(...) DOCTEST_REQUIRE_UNARY(__VA_ARGS__) +#define WARN_UNARY_FALSE(...) DOCTEST_WARN_UNARY_FALSE(__VA_ARGS__) +#define CHECK_UNARY_FALSE(...) DOCTEST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define REQUIRE_UNARY_FALSE(...) DOCTEST_REQUIRE_UNARY_FALSE(__VA_ARGS__) // KEPT FOR BACKWARDS COMPATIBILITY -#define FAST_WARN_EQ DOCTEST_FAST_WARN_EQ -#define FAST_CHECK_EQ DOCTEST_FAST_CHECK_EQ -#define FAST_REQUIRE_EQ DOCTEST_FAST_REQUIRE_EQ -#define FAST_WARN_NE DOCTEST_FAST_WARN_NE -#define FAST_CHECK_NE DOCTEST_FAST_CHECK_NE -#define FAST_REQUIRE_NE DOCTEST_FAST_REQUIRE_NE -#define FAST_WARN_GT DOCTEST_FAST_WARN_GT -#define FAST_CHECK_GT DOCTEST_FAST_CHECK_GT -#define FAST_REQUIRE_GT DOCTEST_FAST_REQUIRE_GT -#define FAST_WARN_LT DOCTEST_FAST_WARN_LT -#define FAST_CHECK_LT DOCTEST_FAST_CHECK_LT -#define FAST_REQUIRE_LT DOCTEST_FAST_REQUIRE_LT -#define FAST_WARN_GE DOCTEST_FAST_WARN_GE -#define FAST_CHECK_GE DOCTEST_FAST_CHECK_GE -#define FAST_REQUIRE_GE DOCTEST_FAST_REQUIRE_GE -#define FAST_WARN_LE DOCTEST_FAST_WARN_LE -#define FAST_CHECK_LE DOCTEST_FAST_CHECK_LE -#define FAST_REQUIRE_LE DOCTEST_FAST_REQUIRE_LE - -#define FAST_WARN_UNARY DOCTEST_FAST_WARN_UNARY -#define FAST_CHECK_UNARY DOCTEST_FAST_CHECK_UNARY -#define FAST_REQUIRE_UNARY DOCTEST_FAST_REQUIRE_UNARY -#define FAST_WARN_UNARY_FALSE DOCTEST_FAST_WARN_UNARY_FALSE -#define FAST_CHECK_UNARY_FALSE DOCTEST_FAST_CHECK_UNARY_FALSE -#define FAST_REQUIRE_UNARY_FALSE DOCTEST_FAST_REQUIRE_UNARY_FALSE - -#define TEST_CASE_TEMPLATE_INSTANTIATE DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE +#define FAST_WARN_EQ(...) DOCTEST_FAST_WARN_EQ(__VA_ARGS__) +#define FAST_CHECK_EQ(...) DOCTEST_FAST_CHECK_EQ(__VA_ARGS__) +#define FAST_REQUIRE_EQ(...) DOCTEST_FAST_REQUIRE_EQ(__VA_ARGS__) +#define FAST_WARN_NE(...) DOCTEST_FAST_WARN_NE(__VA_ARGS__) +#define FAST_CHECK_NE(...) DOCTEST_FAST_CHECK_NE(__VA_ARGS__) +#define FAST_REQUIRE_NE(...) DOCTEST_FAST_REQUIRE_NE(__VA_ARGS__) +#define FAST_WARN_GT(...) DOCTEST_FAST_WARN_GT(__VA_ARGS__) +#define FAST_CHECK_GT(...) DOCTEST_FAST_CHECK_GT(__VA_ARGS__) +#define FAST_REQUIRE_GT(...) DOCTEST_FAST_REQUIRE_GT(__VA_ARGS__) +#define FAST_WARN_LT(...) DOCTEST_FAST_WARN_LT(__VA_ARGS__) +#define FAST_CHECK_LT(...) DOCTEST_FAST_CHECK_LT(__VA_ARGS__) +#define FAST_REQUIRE_LT(...) DOCTEST_FAST_REQUIRE_LT(__VA_ARGS__) +#define FAST_WARN_GE(...) DOCTEST_FAST_WARN_GE(__VA_ARGS__) +#define FAST_CHECK_GE(...) DOCTEST_FAST_CHECK_GE(__VA_ARGS__) +#define FAST_REQUIRE_GE(...) DOCTEST_FAST_REQUIRE_GE(__VA_ARGS__) +#define FAST_WARN_LE(...) DOCTEST_FAST_WARN_LE(__VA_ARGS__) +#define FAST_CHECK_LE(...) DOCTEST_FAST_CHECK_LE(__VA_ARGS__) +#define FAST_REQUIRE_LE(...) DOCTEST_FAST_REQUIRE_LE(__VA_ARGS__) + +#define FAST_WARN_UNARY(...) DOCTEST_FAST_WARN_UNARY(__VA_ARGS__) +#define FAST_CHECK_UNARY(...) DOCTEST_FAST_CHECK_UNARY(__VA_ARGS__) +#define FAST_REQUIRE_UNARY(...) DOCTEST_FAST_REQUIRE_UNARY(__VA_ARGS__) +#define FAST_WARN_UNARY_FALSE(...) DOCTEST_FAST_WARN_UNARY_FALSE(__VA_ARGS__) +#define FAST_CHECK_UNARY_FALSE(...) DOCTEST_FAST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define FAST_REQUIRE_UNARY_FALSE(...) DOCTEST_FAST_REQUIRE_UNARY_FALSE(__VA_ARGS__) + +#define TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, __VA_ARGS__) #endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES @@ -2689,6 +2746,7 @@ DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") @@ -2794,11 +2852,7 @@ DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN #ifdef __AFXDLL #include <AfxWin.h> #else -#if defined(__MINGW32__) || defined(__MINGW64__) #include <windows.h> -#else // MINGW -#include <Windows.h> -#endif // MINGW #endif #include <io.h> @@ -2834,12 +2888,24 @@ DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END #define DOCTEST_THREAD_LOCAL thread_local #endif +#ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES +#define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32 +#endif + +#ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE +#define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64 +#endif + #ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS #define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX #else #define DOCTEST_OPTIONS_PREFIX_DISPLAY "" #endif +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS +#endif + namespace doctest { bool is_running_in_test = false; @@ -2972,18 +3038,105 @@ typedef timer_large_integer::type ticks_t; ticks_t m_ticks = 0; }; +#ifdef DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + template <typename T> + using AtomicOrMultiLaneAtomic = std::atomic<T>; +#else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + // Provides a multilane implementation of an atomic variable that supports add, sub, load, + // store. Instead of using a single atomic variable, this splits up into multiple ones, + // each sitting on a separate cache line. The goal is to provide a speedup when most + // operations are modifying. It achieves this with two properties: + // + // * Multiple atomics are used, so chance of congestion from the same atomic is reduced. + // * Each atomic sits on a separate cache line, so false sharing is reduced. + // + // The disadvantage is that there is a small overhead due to the use of TLS, and load/store + // is slower because all atomics have to be accessed. + template <typename T> + class MultiLaneAtomic + { + struct CacheLineAlignedAtomic + { + std::atomic<T> atomic{}; + char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(std::atomic<T>)]; + }; + CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES]; + + static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE, + "guarantee one atomic takes exactly one cache line"); + + public: + T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; } + + T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); } + + T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_add(arg, order); + } + + T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_sub(arg, order); + } + + operator T() const DOCTEST_NOEXCEPT { return load(); } + + T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT { + auto result = T(); + for(auto const& c : m_atomics) { + result += c.atomic.load(order); + } + return result; + } + + T operator=(T desired) DOCTEST_NOEXCEPT { + store(desired); + return desired; + } + + void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + // first value becomes desired", all others become 0. + for(auto& c : m_atomics) { + c.atomic.store(desired, order); + desired = {}; + } + } + + private: + // Each thread has a different atomic that it operates on. If more than NumLanes threads + // use this, some will use the same atomic. So performance will degrate a bit, but still + // everything will work. + // + // The logic here is a bit tricky. The call should be as fast as possible, so that there + // is minimal to no overhead in determining the correct atomic for the current thread. + // + // 1. A global static counter laneCounter counts continuously up. + // 2. Each successive thread will use modulo operation of that counter so it gets an atomic + // assigned in a round-robin fashion. + // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with + // little overhead. + std::atomic<T>& myAtomic() DOCTEST_NOEXCEPT { + static std::atomic<size_t> laneCounter; + DOCTEST_THREAD_LOCAL size_t tlsLaneIdx = + laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES; + + return m_atomics[tlsLaneIdx].atomic; + } + }; + + template <typename T> + using AtomicOrMultiLaneAtomic = MultiLaneAtomic<T>; +#endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + // this holds both parameters from the command line and runtime data for tests struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats { - std::atomic<int> numAssertsCurrentTest_atomic; - std::atomic<int> numAssertsFailedCurrentTest_atomic; + AtomicOrMultiLaneAtomic<int> numAssertsCurrentTest_atomic; + AtomicOrMultiLaneAtomic<int> numAssertsFailedCurrentTest_atomic; std::vector<std::vector<String>> filters = decltype(filters)(9); // 9 different filters std::vector<IReporter*> reporters_currently_used; - const TestCase* currentTest = nullptr; - assert_handler ah = nullptr; Timer timer; @@ -3093,14 +3246,16 @@ String::String(const char* in) String::String(const char* in, unsigned in_size) { using namespace std; if(in_size <= last) { - memcpy(buf, in, in_size + 1); + memcpy(buf, in, in_size); + buf[in_size] = '\0'; setLast(last - in_size); } else { setOnHeap(); data.size = in_size; data.capacity = data.size + 1; data.ptr = new char[data.capacity]; - memcpy(data.ptr, in, in_size + 1); + memcpy(data.ptr, in, in_size); + data.ptr[in_size] = '\0'; } } @@ -3471,7 +3626,7 @@ int registerReporter(const char*, int, IReporter*) { return 0; } namespace doctest_detail_test_suite_ns { // holds the current test suite doctest::detail::TestSuite& getCurrentTestSuite() { - static doctest::detail::TestSuite data; + static doctest::detail::TestSuite data{}; return data; } } // namespace doctest_detail_test_suite_ns @@ -3583,7 +3738,7 @@ namespace detail { Subcase::Subcase(const String& name, const char* file, int line) : m_signature({name, file, line}) { - ContextState* s = g_cs; + auto* s = g_cs; // check subcase filters if(s->subcasesStack.size() < size_t(s->subcase_filter_levels)) { @@ -3625,7 +3780,7 @@ namespace detail { g_cs->subcasesPassed.insert(g_cs->subcasesStack); g_cs->subcasesStack.pop_back(); -#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0 #else if(std::uncaught_exception() @@ -3660,6 +3815,8 @@ namespace detail { // clear state m_description = nullptr; m_skip = false; + m_no_breaks = false; + m_no_output = false; m_may_fail = false; m_should_fail = false; m_expected_failures = 0; @@ -3675,6 +3832,8 @@ namespace detail { m_test_suite = test_suite.m_test_suite; m_description = test_suite.m_description; m_skip = test_suite.m_skip; + m_no_breaks = test_suite.m_no_breaks; + m_no_output = test_suite.m_no_output; m_may_fail = test_suite.m_may_fail; m_should_fail = test_suite.m_should_fail; m_expected_failures = test_suite.m_expected_failures; @@ -3721,14 +3880,20 @@ namespace detail { // this will be used only to differentiate between test cases - not relevant for sorting if(m_line != other.m_line) return m_line < other.m_line; - const int file_cmp = m_file.compare(other.m_file); - if(file_cmp != 0) - return file_cmp < 0; const int name_cmp = strcmp(m_name, other.m_name); if(name_cmp != 0) return name_cmp < 0; + const int file_cmp = m_file.compare(other.m_file); + if(file_cmp != 0) + return file_cmp < 0; return m_template_id < other.m_template_id; } + + // all the registered tests + std::set<TestCase>& getRegisteredTests() { + static std::set<TestCase> data; + return data; + } } // namespace detail namespace { using namespace detail; @@ -3760,12 +3925,6 @@ namespace { return suiteOrderComparator(lhs, rhs); } - // all the registered tests - std::set<TestCase>& getRegisteredTests() { - static std::set<TestCase> data; - return data; - } - #ifdef DOCTEST_CONFIG_COLORS_WINDOWS HANDLE g_stdoutHandle; WORD g_origFgAttrs; @@ -3994,7 +4153,7 @@ namespace detail { // ContextScope has been destroyed (base class destructors run after derived class destructors). // Instead, ContextScope calls this method directly from its destructor. void ContextScopeBase::destroy() { -#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0) { #else if(std::uncaught_exception()) { @@ -4016,7 +4175,9 @@ namespace { #if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) struct FatalConditionHandler { - void reset() {} + static void reset() {} + static void allocateAltStackMem() {} + static void freeAltStackMem() {} }; #else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH @@ -4069,6 +4230,9 @@ namespace { std::exit(EXIT_FAILURE); } + static void allocateAltStackMem() {} + static void freeAltStackMem() {} + FatalConditionHandler() { isSet = true; // 32k seems enough for doctest to handle stack overflow, @@ -4086,7 +4250,7 @@ namespace { // - std::terminate is called FROM THE TEST RUNNER THREAD // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD original_terminate_handler = std::get_terminate(); - std::set_terminate([]() noexcept { + std::set_terminate([]() DOCTEST_NOEXCEPT { reportFatal("Terminate handler called"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); @@ -4097,7 +4261,7 @@ namespace { // - std::terminate is called FROM A DIFFERENT THREAD // - an exception is thrown from a destructor FROM A DIFFERENT THREAD // - an uncaught exception is thrown FROM A DIFFERENT THREAD - prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) noexcept { + prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT { if(signal == SIGABRT) { reportFatal("SIGABRT - Abort (abnormal termination) signal"); if(isDebuggerActive() && !g_cs->no_breaks) @@ -4135,8 +4299,8 @@ namespace { SetErrorMode(prev_error_mode_1); _set_error_mode(prev_error_mode_2); _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); - _CrtSetReportMode(_CRT_ASSERT, prev_report_mode); - _CrtSetReportFile(_CRT_ASSERT, prev_report_file); + static_cast<void>(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode)); + static_cast<void>(_CrtSetReportFile(_CRT_ASSERT, prev_report_file)); isSet = false; } } @@ -4186,7 +4350,8 @@ namespace { static bool isSet; static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; static stack_t oldSigStack; - static char altStackMem[4 * SIGSTKSZ]; + static size_t altStackSize; + static char* altStackMem; static void handleSignal(int sig) { const char* name = "<unknown signal>"; @@ -4202,11 +4367,19 @@ namespace { raise(sig); } + static void allocateAltStackMem() { + altStackMem = new char[altStackSize]; + } + + static void freeAltStackMem() { + delete[] altStackMem; + } + FatalConditionHandler() { isSet = true; stack_t sigStack; sigStack.ss_sp = altStackMem; - sigStack.ss_size = sizeof(altStackMem); + sigStack.ss_size = altStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); struct sigaction sa = {}; @@ -4231,10 +4404,11 @@ namespace { } }; - bool FatalConditionHandler::isSet = false; + bool FatalConditionHandler::isSet = false; struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; - stack_t FatalConditionHandler::oldSigStack = {}; - char FatalConditionHandler::altStackMem[] = {}; + stack_t FatalConditionHandler::oldSigStack = {}; + size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ; + char* FatalConditionHandler::altStackMem = nullptr; #endif // DOCTEST_PLATFORM_WINDOWS #endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH @@ -4336,8 +4510,8 @@ namespace detail { failed_out_of_a_testing_context(*this); } - return m_failed && isDebuggerActive() && - !getContextOptions()->no_breaks; // break into debugger + return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void ResultBuilder::react() const { @@ -4387,7 +4561,8 @@ namespace detail { addFailedAssert(m_severity); } - return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn; // break + return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void MessageBuilder::react() { @@ -5495,7 +5670,7 @@ namespace { << Whitespace(sizePrefixDisplay*1) << "output filename\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by=<string> " << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; - s << Whitespace(sizePrefixDisplay*3) << " <string> - by [file/suite/name/rand]\n"; + s << Whitespace(sizePrefixDisplay*3) << " <string> - [file/suite/name/rand/none]\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed=<int> " << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first=<int> " @@ -5668,6 +5843,9 @@ namespace { } void test_case_end(const CurrentTestCaseStats& st) override { + if(tc->m_no_output) + return; + // log the preamble of the test case only if there is something // else to print - something other than that an assert has failed if(opt.duration || @@ -5702,6 +5880,9 @@ namespace { } void test_case_exception(const TestCaseException& e) override { + if(tc->m_no_output) + return; + logTestStart(); file_line_to_stream(tc->m_file.c_str(), tc->m_line, " "); @@ -5736,7 +5917,7 @@ namespace { } void log_assert(const AssertData& rb) override { - if(!rb.m_failed && !opt.success) + if((!rb.m_failed && !opt.success) || tc->m_no_output) return; std::lock_guard<std::mutex> lock(mutex); @@ -5752,6 +5933,9 @@ namespace { } void log_message(const MessageData& mb) override { + if(tc->m_no_output) + return; + std::lock_guard<std::mutex> lock(mutex); logTestStart(); @@ -5782,8 +5966,10 @@ namespace { bool with_col = g_no_colors; \ g_no_colors = false; \ ConsoleReporter::func(arg); \ - DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ - oss.str(""); \ + if(oss.tellp() != std::streampos{}) { \ + DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ + oss.str(""); \ + } \ g_no_colors = with_col; \ } @@ -5970,7 +6156,7 @@ void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { #define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ - p->var = !!intRes; \ + p->var = static_cast<bool>(intRes); \ else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ p->var = true; \ @@ -6115,7 +6301,11 @@ int Context::run() { p->cout = &fstr; } + FatalConditionHandler::allocateAltStackMem(); + auto cleanup_and_return = [&]() { + FatalConditionHandler::freeAltStackMem(); + if(fstr.is_open()) fstr.close(); @@ -6187,6 +6377,9 @@ int Context::run() { first[i] = first[idxToSwap]; first[idxToSwap] = temp; } + } else if(p->order_by.compare("none", true) == 0) { + // means no sorting - beneficial for death tests which call into the executable + // with a specific test case in mind - we don't want to slow down the startup times } } @@ -6286,10 +6479,13 @@ int Context::run() { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS try { #endif // DOCTEST_CONFIG_NO_EXCEPTIONS +// MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method) +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable FatalConditionHandler fatalConditionHandler; // Handle signals // execute the test tc.m_test(); fatalConditionHandler.reset(); +DOCTEST_MSVC_SUPPRESS_WARNING_POP #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS } catch(const TestFailureException&) { p->failure_flags |= TestCaseFailureReason::AssertFailure; diff --git a/thirdparty/fonts/Tamsyn10x20.png b/thirdparty/fonts/Tamsyn10x20.png Binary files differdeleted file mode 100644 index b2d3b5cb5c..0000000000 --- a/thirdparty/fonts/Tamsyn10x20.png +++ /dev/null diff --git a/thirdparty/fonts/Tamsyn5x9.png b/thirdparty/fonts/Tamsyn5x9.png Binary files differdeleted file mode 100644 index ac42b32641..0000000000 --- a/thirdparty/fonts/Tamsyn5x9.png +++ /dev/null |