diff options
237 files changed, 3548 insertions, 766 deletions
diff --git a/.gitignore b/.gitignore index 52937b8679..3a05ed9e7d 100644 --- a/.gitignore +++ b/.gitignore @@ -238,6 +238,7 @@ ClientBin/ *.pfx *.publishsettings node_modules/ +__pycache__/ # KDE .directory diff --git a/.travis.yml b/.travis.yml index a5217c1d9c..a8bc8289e4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ matrix: - mono packages: - &linux_deps [libasound2-dev, libfreetype6-dev, libgl1-mesa-dev, libglu1-mesa-dev, libx11-dev, libxcursor-dev, libxi-dev, libxinerama-dev, libxrandr-dev] - - &linux_mono_deps [mono-devel, msbuild] + - &linux_mono_deps [mono-devel, msbuild, nuget] coverity_scan: project: diff --git a/SConstruct b/SConstruct index f8c1c82961..628aac42af 100644 --- a/SConstruct +++ b/SConstruct @@ -349,7 +349,10 @@ if selected_platform in platform_list: else: # always enable those errors env.Append(CCFLAGS=['-Werror=return-type']) - suffix = "." + selected_platform + if (hasattr(detect, 'get_program_suffix')): + suffix = "." + detect.get_program_suffix() + else: + suffix = "." + selected_platform if (env["target"] == "release"): if env["tools"]: @@ -544,7 +547,7 @@ if 'env' in locals(): [os.remove(f) for f in files] def file_list(self): - if self.path == None: + if self.path is None: # Nothing to do return [] # Gather a list of (filename, (size, atime)) within the @@ -569,7 +572,7 @@ if 'env' in locals(): if sum > self.limit: mark = i break - if mark == None: + if mark is None: return [] else: return [x[0] for x in file_stat[mark:]] diff --git a/core/color.cpp b/core/color.cpp index 55dd1ec6b9..ac314417ec 100644 --- a/core/color.cpp +++ b/core/color.cpp @@ -468,7 +468,7 @@ String Color::to_html(bool p_alpha) const { return txt; } -Color Color::from_hsv(float p_h, float p_s, float p_v, float p_a) { +Color Color::from_hsv(float p_h, float p_s, float p_v, float p_a) const { p_h = Math::fmod(p_h * 360.0f, 360.0f); if (p_h < 0.0) diff --git a/core/color.h b/core/color.h index add61343ff..d6ad5f91c5 100644 --- a/core/color.h +++ b/core/color.h @@ -194,7 +194,7 @@ struct Color { static bool html_is_valid(const String &p_color); static Color named(const String &p_name); String to_html(bool p_alpha = true) const; - Color from_hsv(float p_h, float p_s, float p_v, float p_a); + Color from_hsv(float p_h, float p_s, float p_v, float p_a) const; static Color from_rgbe9995(uint32_t p_color); _FORCE_INLINE_ bool operator<(const Color &p_color) const; //used in set keys diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp index 6b6856dcc8..b9544ac166 100644 --- a/core/io/file_access_network.cpp +++ b/core/io/file_access_network.cpp @@ -500,8 +500,9 @@ uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) { void FileAccessNetwork::configure() { GLOBAL_DEF("network/remote_fs/page_size", 65536); + ProjectSettings::get_singleton()->set_custom_property_info("network/remote_fs/page_size", PropertyInfo(Variant::INT, "network/remote_fs/page_size", PROPERTY_HINT_RANGE, "1,65536,1,or_greater")); //is used as denominator and can't be zero GLOBAL_DEF("network/remote_fs/page_read_ahead", 4); - GLOBAL_DEF("network/remote_fs/max_pages", 20); + ProjectSettings::get_singleton()->set_custom_property_info("network/remote_fs/page_read_ahead", PropertyInfo(Variant::INT, "network/remote_fs/page_read_ahead", PROPERTY_HINT_RANGE, "0,8,1,or_greater")); } FileAccessNetwork::FileAccessNetwork() { @@ -519,7 +520,6 @@ FileAccessNetwork::FileAccessNetwork() { nc->unlock_mutex(); page_size = GLOBAL_GET("network/remote_fs/page_size"); read_ahead = GLOBAL_GET("network/remote_fs/page_read_ahead"); - max_pages = GLOBAL_GET("network/remote_fs/max_pages"); last_activity_val = 0; waiting_on_page = -1; last_page = -1; diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h index e32dcea990..c929e8446d 100644 --- a/core/io/file_access_network.h +++ b/core/io/file_access_network.h @@ -98,7 +98,6 @@ class FileAccessNetwork : public FileAccess { int page_size; int read_ahead; - int max_pages; mutable int waiting_on_page; mutable int last_activity_val; diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index d156a9f4bd..71b01aa94a 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -259,6 +259,10 @@ RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p } #endif + if (_loaded_callback) { + _loaded_callback(res, p_path); + } + return res; } @@ -635,6 +639,12 @@ void ResourceLoader::clear_path_remaps() { path_remaps.clear(); } +void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) { + _loaded_callback = p_callback; +} + +ResourceLoadedCallback ResourceLoader::_loaded_callback = NULL; + ResourceLoadErrorNotify ResourceLoader::err_notify = NULL; void *ResourceLoader::err_notify_ud = NULL; diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h index 96bc6fa8dd..7ade4a2dfc 100644 --- a/core/io/resource_loader.h +++ b/core/io/resource_loader.h @@ -78,6 +78,7 @@ typedef void (*ResourceLoadErrorNotify)(void *p_ud, const String &p_text); typedef void (*DependencyErrorNotify)(void *p_ud, const String &p_loading, const String &p_which, const String &p_type); typedef Error (*ResourceLoaderImport)(const String &p_path); +typedef void (*ResourceLoadedCallback)(RES p_resource, const String &p_path); class ResourceLoader { @@ -106,6 +107,8 @@ class ResourceLoader { //internal load function static RES _load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error); + static ResourceLoadedCallback _loaded_callback; + public: static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); static RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); @@ -150,6 +153,7 @@ public: static void load_translation_remaps(); static void clear_translation_remaps(); + static void set_load_callback(ResourceLoadedCallback p_callback); static ResourceLoaderImport import; }; diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp index 5c8188f735..097e81e308 100644 --- a/core/io/resource_saver.cpp +++ b/core/io/resource_saver.cpp @@ -90,7 +90,7 @@ Error ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t rwcopy->set_path(old_path); if (save_callback && p_path.begins_with("res://")) - save_callback(p_path); + save_callback(p_resource, p_path); return OK; } else { diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h index 7ed580f2d6..6134d9db57 100644 --- a/core/io/resource_saver.h +++ b/core/io/resource_saver.h @@ -46,7 +46,7 @@ public: virtual ~ResourceFormatSaver() {} }; -typedef void (*ResourceSavedCallback)(const String &p_path); +typedef void (*ResourceSavedCallback)(Ref<Resource> p_resource, const String &p_path); class ResourceSaver { diff --git a/core/message_queue.cpp b/core/message_queue.cpp index 7f788c90a7..abfc73407a 100644 --- a/core/message_queue.cpp +++ b/core/message_queue.cpp @@ -338,6 +338,7 @@ MessageQueue::MessageQueue() { buffer_end = 0; buffer_max_used = 0; buffer_size = GLOBAL_DEF_RST("memory/limits/message_queue/max_size_kb", DEFAULT_QUEUE_SIZE_KB); + ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/message_queue/max_size_kb", PropertyInfo(Variant::INT, "memory/limits/message_queue/max_size_kb", PROPERTY_HINT_RANGE, "0,2048,1,or_greater")); buffer_size *= 1024; buffer = memnew_arr(uint8_t, buffer_size); } diff --git a/core/object.cpp b/core/object.cpp index 946040ba34..374e10726a 100644 --- a/core/object.cpp +++ b/core/object.cpp @@ -440,16 +440,6 @@ void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid if (r_valid) *r_valid = true; return; -#ifdef TOOLS_ENABLED - } else if (p_name == CoreStringNames::get_singleton()->_sections_unfolded) { - Array arr = p_value; - for (int i = 0; i < arr.size(); i++) { - editor_section_folding.insert(arr[i]); - } - if (r_valid) - *r_valid = true; - return; -#endif } //something inside the object... :| @@ -520,16 +510,7 @@ Variant Object::get(const StringName &p_name, bool *r_valid) const { if (r_valid) *r_valid = true; return ret; -#ifdef TOOLS_ENABLED - } else if (p_name == CoreStringNames::get_singleton()->_sections_unfolded) { - Array array; - for (Set<String>::Element *E = editor_section_folding.front(); E; E = E->next()) { - array.push_back(E->get()); - } - if (r_valid) - *r_valid = true; - return array; -#endif + } else { //something inside the object... :| bool success = _getv(p_name, ret); @@ -657,11 +638,6 @@ void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) cons #endif p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NONZERO)); } -#ifdef TOOLS_ENABLED - if (editor_section_folding.size()) { - p_list->push_back(PropertyInfo(Variant::ARRAY, CoreStringNames::get_singleton()->_sections_unfolded, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); - } -#endif if (!metadata.empty()) p_list->push_back(PropertyInfo(Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_STORE_IF_NONZERO)); if (script_instance && !p_reversed) { diff --git a/core/object.h b/core/object.h index b23160c1df..0fee7c2157 100644 --- a/core/object.h +++ b/core/object.h @@ -723,6 +723,9 @@ public: #ifdef TOOLS_ENABLED void editor_set_section_unfold(const String &p_section, bool p_unfolded); bool editor_is_section_unfolded(const String &p_section); + const Set<String> &editor_get_section_folding() const { return editor_section_folding; } + void editor_clear_section_folding() { editor_section_folding.clear(); } + #endif //used by script languages to store binding data diff --git a/core/project_settings.cpp b/core/project_settings.cpp index 99a23bbee1..407bb78375 100644 --- a/core/project_settings.cpp +++ b/core/project_settings.cpp @@ -288,9 +288,28 @@ void ProjectSettings::_convert_to_last_version() { } } +/* + * This method is responsible for loading a project.godot file and/or data file + * using the following merit order: + * - If using NetworkClient, try to lookup project file or fail. + * - If --main-pack was passed by the user (`p_main_pack`), load it or fail. + * - Search for .pck file matching binary name. There are two possibilities: + * o exec_path.get_basename() + '.pck' (e.g. 'win_game.exe' -> 'win_game.pck') + * o exec_path + '.pck' (e.g. 'linux_game' -> 'linux_game.pck') + * For each tentative, if the file exists, load it or fail. + * - On relevant platforms (Android/iOS), lookup project file in OS resource path. + * If found, load it or fail. + * - Lookup project file in passed `p_path` (--path passed by the user), i.e. we + * are running from source code. + * If not found and `p_upwards` is true (--upwards passed by the user), look for + * project files in parent folders up to the system root (used to run a game + * from command line while in a subfolder). + * If a project file is found, load it or fail. + * If nothing was found, error out. + */ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bool p_upwards) { - //If looking for files in network, just use network! + // If looking for files in a network client, use it directly if (FileAccessNetworkClient::get_singleton()) { @@ -302,9 +321,7 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo return err; } - String exec_path = OS::get_singleton()->get_executable_path(); - - //Attempt with a passed main pack first + // Attempt with a user-defined main pack first if (p_main_pack != "") { @@ -320,25 +337,39 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo return err; } - //Attempt with execname.pck + // Attempt with exec_name.pck + // (This is the usual case when distributing a Godot game.) + + // Based on the OS, it can be the exec path + '.pck' (Linux w/o extension, macOS in .app bundle) + // or the exec path's basename + '.pck' (Windows). + // We need to test both possibilities as extensions for Linux binaries are optional + // (so both 'mygame.bin' and 'mygame' should be able to find 'mygame.pck'). + + String exec_path = OS::get_singleton()->get_executable_path(); + if (exec_path != "") { bool found = false; - // get our filename without our path (note, using exec_path.get_file before get_basename anymore because not all file systems have dots in their file names!) - String filebase_name = exec_path.get_file().get_basename(); + String exec_dir = exec_path.get_base_dir(); + String exec_filename = exec_path.get_file(); + String exec_basename = exec_filename.get_basename(); + + // Try to load data pack at the location of the executable + // As mentioned above, we have two potential names to attempt - // try to open at the location of executable - String datapack_name = exec_path.get_base_dir().plus_file(filebase_name) + ".pck"; - if (_load_resource_pack(datapack_name)) { + if (_load_resource_pack(exec_dir.plus_file(exec_basename + ".pck")) || + _load_resource_pack(exec_dir.plus_file(exec_filename + ".pck"))) { found = true; } else { - datapack_name = filebase_name + ".pck"; - if (_load_resource_pack(datapack_name)) { + // If we couldn't find them next to the executable, we attempt + // the current working directory. Same story, two tests. + if (_load_resource_pack(exec_basename + ".pck") || + _load_resource_pack(exec_filename + ".pck")) { found = true; } } - // if we opened our package, try and load our project... + // If we opened our package, try and load our project if (found) { Error err = _load_settings_text_or_binary("res://project.godot", "res://project.binary"); if (err == OK) { @@ -350,17 +381,15 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo } } - //Try to use the filesystem for files, according to OS. (only Android -when reading from pck- and iOS use this) - if (OS::get_singleton()->get_resource_dir() != "") { - //OS will call Globals->get_resource_path which will be empty if not overridden! - //if the OS would rather use somewhere else, then it will not be empty. + // Try to use the filesystem for files, according to OS. (only Android -when reading from pck- and iOS use this) + if (OS::get_singleton()->get_resource_dir() != "") { + // OS will call ProjectSettings->get_resource_path which will be empty if not overridden! + // If the OS would rather use a specific location, then it will not be empty. resource_path = OS::get_singleton()->get_resource_dir().replace("\\", "/"); - if (resource_path.length() && resource_path[resource_path.length() - 1] == '/') + if (resource_path != "" && resource_path[resource_path.length() - 1] == '/') { resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end - - // data.pck and data.zip are deprecated and no longer supported, apologies. - // make sure this is loaded from the resource path + } Error err = _load_settings_text_or_binary("res://project.godot", "res://project.binary"); if (err == OK) { @@ -371,21 +400,19 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo return err; } - //Nothing was found, try to find a project.godot somewhere! + // Nothing was found, try to find a project file in provided path (`p_path`) + // or, if requested (`p_upwards`) in parent directories. DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND_V(!d, ERR_CANT_CREATE); - d->change_dir(p_path); - String candidate = d->get_current_dir(); String current_dir = d->get_current_dir(); - + String candidate = current_dir; bool found = false; Error err; while (true) { - err = _load_settings_text_or_binary(current_dir.plus_file("project.godot"), current_dir.plus_file("project.binary")); if (err == OK) { // Optional, we don't mind if it fails @@ -396,10 +423,10 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo } if (p_upwards) { - // Try to load settings ascending through dirs shape! + // Try to load settings ascending through parent directories d->change_dir(".."); if (d->get_current_dir() == current_dir) - break; //not doing anything useful + break; // not doing anything useful current_dir = d->get_current_dir(); } else { break; @@ -416,6 +443,8 @@ Error ProjectSettings::setup(const String &p_path, const String &p_main_pack, bo if (resource_path.length() && resource_path[resource_path.length() - 1] == '/') resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end + // If we're loading a project.godot from source code, we can operate some + // ProjectSettings conversions if need be. _convert_to_last_version(); return OK; @@ -1133,6 +1162,7 @@ ProjectSettings::ProjectSettings() { custom_prop_info["rendering/quality/intended_usage/framebuffer_allocation"] = PropertyInfo(Variant::INT, "rendering/quality/intended_usage/framebuffer_allocation", PROPERTY_HINT_ENUM, "2D,2D Without Sampling,3D,3D Without Effects"); GLOBAL_DEF("debug/settings/profiler/max_functions", 16384); + custom_prop_info["debug/settings/profiler/max_functions"] = PropertyInfo(Variant::INT, "debug/settings/profiler/max_functions", PROPERTY_HINT_RANGE, "128,65535,1"); //assigning here, because using GLOBAL_GET on every block for compressing can be slow Compression::zstd_long_distance_matching = GLOBAL_DEF("compression/formats/zstd/long_distance_matching", false); diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index b0023b4c26..430004bb96 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -199,6 +199,7 @@ void register_core_types() { void register_core_settings() { //since in register core types, globals may not e present GLOBAL_DEF_RST("network/limits/packet_peer_stream/max_buffer_po2", (16)); + ProjectSettings::get_singleton()->set_custom_property_info("network/limits/packet_peer_stream/max_buffer_po2", PropertyInfo(Variant::INT, "network/limits/packet_peer_stream/max_buffer_po2", PROPERTY_HINT_RANGE, "0,64,1,or_greater")); } void register_core_singletons() { diff --git a/core/script_debugger_remote.cpp b/core/script_debugger_remote.cpp index 3e984fae32..621a94ab1a 100644 --- a/core/script_debugger_remote.cpp +++ b/core/script_debugger_remote.cpp @@ -1100,7 +1100,7 @@ ScriptDebuggerRemote::ScriptDebuggerRemote() : eh.userdata = this; add_error_handler(&eh); - profile_info.resize(CLAMP(int(ProjectSettings::get_singleton()->get("debug/settings/profiler/max_functions")), 128, 65535)); + profile_info.resize(GLOBAL_GET("debug/settings/profiler/max_functions")); profile_info_ptrs.resize(profile_info.size()); } diff --git a/core/set.h b/core/set.h index 744019d5b4..59aa54128e 100644 --- a/core/set.h +++ b/core/set.h @@ -595,6 +595,7 @@ public: return e; } + inline bool empty() const { return _data.size_cache == 0; } inline int size() const { return _data.size_cache; } int calculate_depth() const { diff --git a/core/ustring.cpp b/core/ustring.cpp index 1195cd0719..2191bb5e23 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -2774,16 +2774,13 @@ String String::format(const Variant &values, String placeholder) const { if (value_arr.size() == 2) { Variant v_key = value_arr[0]; - String key; - - key = v_key.get_construct_string(); + String key = v_key; if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") { key = key.substr(1, key.length() - 2); } Variant v_val = value_arr[1]; - String val; - val = v_val.get_construct_string(); + String val = v_val; if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") { val = val.substr(1, val.length() - 2); @@ -2795,8 +2792,7 @@ String String::format(const Variant &values, String placeholder) const { } } else { //Array structure ["RobotGuy","Logis","rookie"] Variant v_val = values_arr[i]; - String val; - val = v_val.get_construct_string(); + String val = v_val; if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") { val = val.substr(1, val.length() - 2); @@ -2815,8 +2811,8 @@ String String::format(const Variant &values, String placeholder) const { d.get_key_list(&keys); for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - String key = E->get().get_construct_string(); - String val = d[E->get()].get_construct_string(); + String key = E->get(); + String val = d[E->get()]; if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") { key = key.substr(1, key.length() - 2); diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml index 6dc91a234a..a5be8ffc53 100644 --- a/doc/classes/AnimationPlayer.xml +++ b/doc/classes/AnimationPlayer.xml @@ -238,7 +238,7 @@ The default time in which to blend animations. Ranges from 0 to 4096 with 0.01 precision. Default value: [code]0[/code]. </member> <member name="playback_process_mode" type="int" setter="set_animation_process_mode" getter="get_animation_process_mode" enum="AnimationPlayer.AnimationProcessMode"> - The process notification in which to update animations. Default value: [enum ANIMATION_PROCESS_IDLE]. + The process notification in which to update animations. Default value: [code]ANIMATION_PROCESS_IDLE[/code]. </member> <member name="playback_speed" type="float" setter="set_speed_scale" getter="get_speed_scale"> The speed scaling ratio. For instance, if this value is 1 then the animation plays at normal speed. If it's 0.5 then it plays at half speed. If it's 2 then it plays at double speed. Default value: [code]1[/code]. diff --git a/doc/classes/AnimationTreePlayer.xml b/doc/classes/AnimationTreePlayer.xml index 8c32d5f6a3..a081c64f6d 100644 --- a/doc/classes/AnimationTreePlayer.xml +++ b/doc/classes/AnimationTreePlayer.xml @@ -618,7 +618,7 @@ Once set, Animation nodes can be added to the AnimationTreePlayer. </member> <member name="playback_process_mode" type="int" setter="set_animation_process_mode" getter="get_animation_process_mode" enum="AnimationTreePlayer.AnimationProcessMode"> - The thread in which to update animations. Default value: [enum ANIMATION_PROCESS_IDLE]. + The thread in which to update animations. Default value: [code]ANIMATION_PROCESS_IDLE[/code]. </member> </members> <constants> diff --git a/doc/classes/AudioServer.xml b/doc/classes/AudioServer.xml index 37756bcfd8..8f654441b2 100644 --- a/doc/classes/AudioServer.xml +++ b/doc/classes/AudioServer.xml @@ -385,6 +385,8 @@ <constant name="SPEAKER_MODE_STEREO" value="0" enum="SpeakerMode"> Two or fewer speakers are detected. </constant> + <constant name="SPEAKER_SURROUND_31" value="1" enum="SpeakerMode"> + </constant> <constant name="SPEAKER_SURROUND_51" value="2" enum="SpeakerMode"> A 5.1 channel surround setup detected. </constant> diff --git a/doc/classes/GridContainer.xml b/doc/classes/GridContainer.xml index 8a8a9a2d24..346ab9d357 100644 --- a/doc/classes/GridContainer.xml +++ b/doc/classes/GridContainer.xml @@ -11,16 +11,6 @@ <demos> </demos> <methods> - <method name="get_child_control_at_cell"> - <return type="Control"> - </return> - <argument index="0" name="row" type="int"> - </argument> - <argument index="1" name="column" type="int"> - </argument> - <description> - </description> - </method> </methods> <members> <member name="columns" type="int" setter="set_columns" getter="get_columns"> diff --git a/doc/classes/Input.xml b/doc/classes/Input.xml index 10ec15b99d..0e6e54c8fd 100644 --- a/doc/classes/Input.xml +++ b/doc/classes/Input.xml @@ -123,7 +123,7 @@ <argument index="0" name="button_index" type="int"> </argument> <description> - Receives a [code]JOY_BUTTON_*[/code] Enum and returns it's equivalent name as a string. + Receives a [code]JOY_BUTTON_*[/code] Enum and returns its equivalent name as a string. </description> </method> <method name="get_joy_guid" qualifiers="const"> diff --git a/doc/classes/MeshInstance.xml b/doc/classes/MeshInstance.xml index ef42726ca9..bcc9a7cad9 100644 --- a/doc/classes/MeshInstance.xml +++ b/doc/classes/MeshInstance.xml @@ -41,6 +41,12 @@ Returns the [Material] for a surface of the [Mesh] resource. </description> </method> + <method name="get_surface_material_count" qualifiers="const"> + <return type="int"> + </return> + <description> + </description> + </method> <method name="set_surface_material"> <return type="void"> </return> diff --git a/doc/classes/NavigationPolygon.xml b/doc/classes/NavigationPolygon.xml index b29e19e5d8..4ede80b98c 100644 --- a/doc/classes/NavigationPolygon.xml +++ b/doc/classes/NavigationPolygon.xml @@ -1,8 +1,27 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="NavigationPolygon" inherits="Resource" category="Core" version="3.1"> <brief_description> + A node that has methods to draw outlines or use indices of vertices to create navigation polygons. </brief_description> <description> + There are two ways to create polygons. Either by using the [method add_outline] method or using the [method add_polygon] method. + Using [method add_outline]: + [code] + var polygon = NavigationPolygon.new() + var outline = PoolVector2Array([Vector2(0, 0), Vector2(0, 50), Vector2(50, 50), Vector2(50, 0)]) + polygon.add_outline(outline) + polygon.make_polygons_from_outlines() + $NavigationPolygonInstance.navpoly = polygon + [/code] + Using [method add_polygon] and indices of the vertices array. + [code] + var polygon = NavigationPolygon.new() + var vertices = PoolVector2Array([Vector2(0, 0), Vector2(0, 50), Vector2(50, 50), Vector2(50, 0)]) + polygon.set_vertices(vertices) + var indices = PoolIntArray(0, 3, 1) + polygon.add_polygon(indices) + $NavigationPolygonInstance.navpoly = polygon + [/code] </description> <tutorials> </tutorials> @@ -15,6 +34,7 @@ <argument index="0" name="outline" type="PoolVector2Array"> </argument> <description> + Appends a [PoolVector2Array] that contains the vertices of an outline to the internal array that contains all the outlines. You have to call [method make_polygons_from_outlines] in order for this array to be converted to polygons that the engine will use. </description> </method> <method name="add_outline_at_index"> @@ -25,6 +45,7 @@ <argument index="1" name="index" type="int"> </argument> <description> + Adds a [PoolVector2Array] that contains the vertices of an outline to the internal array that contains all the outlines at a fixed position. You have to call [method make_polygons_from_outlines] in order for this array to be converted to polygons that the engine will use. </description> </method> <method name="add_polygon"> @@ -33,18 +54,21 @@ <argument index="0" name="polygon" type="PoolIntArray"> </argument> <description> + Adds a polygon using the indices of the vertices you get when calling [method get_vertices]. </description> </method> <method name="clear_outlines"> <return type="void"> </return> <description> + Clears the array of the outlines, but it doesn't clear the vertices and the polygons that were created by them. </description> </method> <method name="clear_polygons"> <return type="void"> </return> <description> + Clears the array of polygons, but it doesn't clear the array of outlines and vertices. </description> </method> <method name="get_outline" qualifiers="const"> @@ -53,12 +77,14 @@ <argument index="0" name="idx" type="int"> </argument> <description> + Returns a [PoolVector2Array] containing the vertices of an outline that was created in the editor or by script. </description> </method> <method name="get_outline_count" qualifiers="const"> <return type="int"> </return> <description> + Returns the number of outlines that were created in the editor or by script. </description> </method> <method name="get_polygon"> @@ -67,24 +93,28 @@ <argument index="0" name="idx" type="int"> </argument> <description> + Returns a [PoolIntArray] containing the indices of the vertices of a created polygon. </description> </method> <method name="get_polygon_count" qualifiers="const"> <return type="int"> </return> <description> + Returns the count of all polygons. </description> </method> <method name="get_vertices" qualifiers="const"> <return type="PoolVector2Array"> </return> <description> + Returns a [PoolVector2Array] containing all the vertices being used to create the polygons. </description> </method> <method name="make_polygons_from_outlines"> <return type="void"> </return> <description> + Creates polygons from the outlines added in the editor or by script. </description> </method> <method name="remove_outline"> @@ -93,6 +123,7 @@ <argument index="0" name="idx" type="int"> </argument> <description> + Removes an outline created in the editor or by script. You have to call [method make_polygons_from_outlines] for the polygons to update. </description> </method> <method name="set_outline"> @@ -103,6 +134,7 @@ <argument index="1" name="outline" type="PoolVector2Array"> </argument> <description> + Changes an outline created in the editor or by script. You have to call [method make_polygons_from_outlines] for the polygons to update. </description> </method> <method name="set_vertices"> @@ -111,6 +143,7 @@ <argument index="0" name="vertices" type="PoolVector2Array"> </argument> <description> + Sets the vertices that can be then indexed to create polygons with the [method add_polygon] method. </description> </method> </methods> diff --git a/doc/classes/NetworkedMultiplayerPeer.xml b/doc/classes/NetworkedMultiplayerPeer.xml index ea6fe6d11c..3b76861afd 100644 --- a/doc/classes/NetworkedMultiplayerPeer.xml +++ b/doc/classes/NetworkedMultiplayerPeer.xml @@ -92,7 +92,7 @@ </signals> <constants> <constant name="TRANSFER_MODE_UNRELIABLE" value="0" enum="TransferMode"> - Packets are not acknowledged, no resend attempts are made for lost packets. Packets may arrive in any order. Potentially faster than [code]TRANSFER_MODE_UNRELIABLE_ORDERED[/code]. Use for non-critical data, and always consider whether the order matters. + Packets are not acknowledged, no resend attempts are made for lost packets. Packets may arrive in any order. Potentially faster than [code]TRANSFER_MODE_UNRELIABLE_ORDERED[/code]. Use for non-critical data, and always consider whether the order matters. </constant> <constant name="TRANSFER_MODE_UNRELIABLE_ORDERED" value="1" enum="TransferMode"> Packets are not acknowledged, no resend attempts are made for lost packets. Packets are received in the order they were sent in. Potentially faster than [code]TRANSFER_MODE_RELIABLE[/code]. Use for non-critical data or data that would be outdated if received late due to resend attempt(s) anyway, for example movement and positional data. diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index a33ee5c363..19aa2e9f5e 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -179,6 +179,15 @@ If [code]owned[/code] is [code]true[/code], this method only finds nodes whose owner is this node. This is especially important for scenes instantiated through script, because those scenes don't have an owner. </description> </method> + <method name="find_parent" qualifiers="const"> + <return type="Node"> + </return> + <argument index="0" name="mask" type="String"> + </argument> + <description> + Finds the first parent of the current node whose name matches [code]mask[/code] as in [method String.match] (i.e. case sensitive, but '*' matches zero or more characters and '?' matches any single character except '.'). Note that it does not match against the full path, just against individual node names. + </description> + </method> <method name="get_child" qualifiers="const"> <return type="Node"> </return> @@ -267,15 +276,6 @@ Returns the parent node of the current node, or an empty [code]Node[/code] if the node lacks a parent. </description> </method> - <method name="find_parent" qualifiers="const"> - <return type="Node"> - </return> - <argument index="0" name="mask" type="String"> - </argument> - <description> - Finds the first parent of the current node whose name matches [code]mask[/code] as in [method String.match] (i.e. case sensitive, but '*' matches zero or more characters and '?' matches any single character except '.'). Note that it does not match against the full path, just against individual node names. - </description> - </method> <method name="get_path" qualifiers="const"> <return type="NodePath"> </return> diff --git a/doc/classes/PackedScene.xml b/doc/classes/PackedScene.xml index 08df3f0ad6..aa4459752e 100644 --- a/doc/classes/PackedScene.xml +++ b/doc/classes/PackedScene.xml @@ -6,10 +6,23 @@ <description> A simplified interface to a scene file. Provides access to operations and checks that can be performed on the scene resource itself. Can be used to save a node to a file. When saving, the node as well as all the node it owns get saved (see [code]owner[/code] property on [Node]). Note that the node doesn't need to own itself. - Example of saving a node: + Example of saving a node with different owners: The following example creates 3 objects: [code]Node2D[/code] ([code]node[/code]), [code]RigidBody2D[/code] ([code]rigid[/code]) and [code]CollisionObject2D[/code] ([code]collision[/code]). [code]collision[/code] is a child of [code]rigid[/code] which is a child of [code]node[/code]. Only [code]rigid[/code] is owned by [code]node[/code] and [code]pack[/code] will therefore only save those two nodes, but not [code]collision[/code]. [codeblock] + # create the objects + var node = Node2D.new() + var rigid = RigidBody2D.new() + var collision = CollisionShape2D.new() + + # create the object hierachy + rigid.add_child(collision) + node.add_child(rigid) + + # change owner of rigid, but not of collision + rigid.set_owner(node) + var scene = PackedScene.new() - var result = scene.pack(child) + # only node and rigid are now packed + var result = scene.pack(node) if result == OK: ResourceSaver.save("res://path/name.scn", scene) # or user://... [/codeblock] @@ -39,7 +52,7 @@ <argument index="0" name="edit_state" type="int" enum="PackedScene.GenEditState" default="0"> </argument> <description> - Instantiates the scene's node hierarchy. Triggers child scene instantiation(s). Triggers the [enum Node.NOTIFICATION_INSTANCED] notification on the root node. + Instantiates the scene's node hierarchy. Triggers child scene instantiation(s). Triggers [Node]'s [code]NOTIFICATION_INSTANCED[/code] notification on the root node. </description> </method> <method name="pack"> diff --git a/doc/classes/PathFollow2D.xml b/doc/classes/PathFollow2D.xml index f9940dab2f..515c921d0d 100644 --- a/doc/classes/PathFollow2D.xml +++ b/doc/classes/PathFollow2D.xml @@ -23,6 +23,7 @@ The node's offset along the curve. </member> <member name="lookahead" type="float" setter="set_lookahead" getter="get_lookahead"> + How far to look ahead of the curve to calculate the tangent if the node is rotating. E.g. shorter lookaheads will lead to faster rotations. Default value: [code]4[/code]. </member> <member name="loop" type="bool" setter="set_loop" getter="has_loop"> If [code]true[/code], any offset outside the path's length will wrap around, instead of stopping at the ends. Use it for cyclic paths. diff --git a/doc/classes/PhysicsBody.xml b/doc/classes/PhysicsBody.xml index af00027ed3..fb145f9de9 100644 --- a/doc/classes/PhysicsBody.xml +++ b/doc/classes/PhysicsBody.xml @@ -21,6 +21,13 @@ Adds a body to the list of bodies that this body can't collide with. </description> </method> + <method name="get_collision_exceptions"> + <return type="Array"> + </return> + <description> + Returns an array of nodes that were added as collision exceptions for this body. + </description> + </method> <method name="get_collision_layer_bit" qualifiers="const"> <return type="bool"> </return> diff --git a/doc/classes/PhysicsBody2D.xml b/doc/classes/PhysicsBody2D.xml index 4278979049..440caf61e5 100644 --- a/doc/classes/PhysicsBody2D.xml +++ b/doc/classes/PhysicsBody2D.xml @@ -21,6 +21,13 @@ Adds a body to the list of bodies that this body can't collide with. </description> </method> + <method name="get_collision_exceptions"> + <return type="Array"> + </return> + <description> + Returns an array of nodes that were added as collision exceptions for this body. + </description> + </method> <method name="get_collision_layer_bit" qualifiers="const"> <return type="bool"> </return> diff --git a/doc/classes/PhysicsServer.xml b/doc/classes/PhysicsServer.xml index f79baea0be..c836414dd2 100644 --- a/doc/classes/PhysicsServer.xml +++ b/doc/classes/PhysicsServer.xml @@ -1260,7 +1260,7 @@ The higher, the stronger. </constant> <constant name="PIN_JOINT_IMPULSE_CLAMP" value="2" enum="PinJointParam"> - If above 0, this value is the maximum value for an impulse that this Joint puts on it's ends. + If above 0, this value is the maximum value for an impulse that this Joint puts on its ends. </constant> <constant name="HINGE_JOINT_BIAS" value="0" enum="HingeJointParam"> The speed with which the two bodies get pulled together when they move in different directions. diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml index 4516fc522a..3b7356ab39 100644 --- a/doc/classes/ProjectSettings.xml +++ b/doc/classes/ProjectSettings.xml @@ -182,7 +182,7 @@ Name of the project. It is used from both project manager and by the exporters. Overriding this as name.locale allows setting it in multiple languages. </member> <member name="application/config/use_custom_user_dir" type="bool" setter="" getter=""> - Allow the project to save to it's own custom user dir (in AppData on windows or ~/.config on unixes). This setting only works for desktop exporters. A name must be set in the "custom_user_dir_name" setting for this to take effect. + Allow the project to save to its own custom user dir (in AppData on windows or ~/.config on unixes). This setting only works for desktop exporters. A name must be set in the "custom_user_dir_name" setting for this to take effect. </member> <member name="application/run/disable_stderr" type="bool" setter="" getter=""> Disable printing to stderr on exported build. @@ -213,6 +213,8 @@ <member name="audio/mix_rate" type="int" setter="" getter=""> Mix rate used for audio. In general, it's better to not touch this and leave it to the host operating system. </member> + <member name="audio/output_latency" type="int" setter="" getter=""> + </member> <member name="audio/video_delay_compensation_ms" type="int" setter="" getter=""> Setting to hardcode audio delay when playing video. Best to leave this untouched unless you know what you are doing. </member> @@ -230,6 +232,8 @@ </member> <member name="compression/formats/zstd/window_log_size" type="int" setter="" getter=""> </member> + <member name="debug/gdscript/completion/autocomplete_setters_and_getters" type="bool" setter="" getter=""> + </member> <member name="debug/gdscript/warnings/constant_used_as_function" type="bool" setter="" getter=""> </member> <member name="debug/gdscript/warnings/deprecated_keyword" type="bool" setter="" getter=""> @@ -372,7 +376,7 @@ <member name="gui/timers/incremental_search_max_interval_msec" type="int" setter="" getter=""> Timer setting for incremental search in Tree, IntemList, etc. controls. </member> - <member name="gui/timers/text_edit_idle_detect_sec" type="int" setter="" getter=""> + <member name="gui/timers/text_edit_idle_detect_sec" type="float" setter="" getter=""> Timer for detecting idle in the editor. </member> <member name="input/ui_accept" type="Dictionary" setter="" getter=""> @@ -604,9 +608,6 @@ <member name="network/limits/packet_peer_stream/max_buffer_po2" type="int" setter="" getter=""> Default size of packet peer stream for deserializing godot data. Over this size, data is dropped. </member> - <member name="network/remote_fs/max_pages" type="int" setter="" getter=""> - Maximum amount of pages used for remote filesystem (used by debugging). - </member> <member name="network/remote_fs/page_read_ahead" type="int" setter="" getter=""> Amount of read ahead used by remote filesystem. Improves latency. </member> @@ -652,7 +653,7 @@ <member name="rendering/limits/rendering/max_renderable_elements" type="int" setter="" getter=""> Max amount of elements renderable in a frame. If more than this are visible per frame, they will be dropped. Keep in mind elements refer to mesh surfaces and not mesh themselves. </member> - <member name="rendering/limits/time/time_rollover_secs" type="int" setter="" getter=""> + <member name="rendering/limits/time/time_rollover_secs" type="float" setter="" getter=""> Shaders have a time variable that constantly increases. At some point it needs to be rolled back to zero to avoid numerical errors on shader animations. This setting specifies when. </member> <member name="rendering/quality/2d/use_pixel_snap" type="bool" setter="" getter=""> @@ -691,7 +692,7 @@ <member name="rendering/quality/reflections/high_quality_ggx.mobile" type="bool" setter="" getter=""> </member> <member name="rendering/quality/reflections/texture_array_reflections" type="bool" setter="" getter=""> - For reflection probes and panorama backgrounds (sky), use a texure array instead of mipmaps. This reduces jitter noise on reflections, but costs more performance and memory. + For reflection probes and panorama backgrounds (sky), use a texture array instead of mipmaps. This reduces jitter noise on reflections, but costs more performance and memory. </member> <member name="rendering/quality/reflections/texture_array_reflections.mobile" type="bool" setter="" getter=""> </member> @@ -704,7 +705,7 @@ <member name="rendering/quality/shading/force_lambert_over_burley.mobile" type="bool" setter="" getter=""> </member> <member name="rendering/quality/shading/force_vertex_shading" type="bool" setter="" getter=""> - Force vertex shading for all rendering. This can increase performance a lot, but also reduces quality inmensely. Can work to optimize on very low end mobile. + Force vertex shading for all rendering. This can increase performance a lot, but also reduces quality immensely. Can work to optimize on very low end mobile. </member> <member name="rendering/quality/shading/force_vertex_shading.mobile" type="bool" setter="" getter=""> </member> diff --git a/doc/classes/ResourceSaver.xml b/doc/classes/ResourceSaver.xml index bf3ea95bce..f388667891 100644 --- a/doc/classes/ResourceSaver.xml +++ b/doc/classes/ResourceSaver.xml @@ -47,5 +47,7 @@ </constant> <constant name="FLAG_COMPRESS" value="32" enum="SaverFlags"> </constant> + <constant name="FLAG_REPLACE_SUBRESOURCE_PATHS" value="64" enum="SaverFlags"> + </constant> </constants> </class> diff --git a/doc/classes/RichTextLabel.xml b/doc/classes/RichTextLabel.xml index 357d2e7a15..3371e4d66f 100644 --- a/doc/classes/RichTextLabel.xml +++ b/doc/classes/RichTextLabel.xml @@ -111,7 +111,7 @@ <argument index="0" name="align" type="int" enum="RichTextLabel.Align"> </argument> <description> - Adds a [code][right][/code] tag to the tag stack. + Adds an alignment tag based on the given [code]align[/code] value. See [enum Align] for possible values. </description> </method> <method name="push_cell"> @@ -170,6 +170,7 @@ <return type="void"> </return> <description> + Adds a [code][s][/code] tag to the tag stack. </description> </method> <method name="push_table"> diff --git a/doc/classes/SoftBody.xml b/doc/classes/SoftBody.xml index 196d29fc60..6c3929d65b 100644 --- a/doc/classes/SoftBody.xml +++ b/doc/classes/SoftBody.xml @@ -20,6 +20,13 @@ Adds a body to the list of bodies that this body can't collide with. </description> </method> + <method name="get_collision_exceptions"> + <return type="Array"> + </return> + <description> + Returns an array of nodes that were added as collision exceptions for this body. + </description> + </method> <method name="get_collision_layer_bit" qualifiers="const"> <return type="bool"> </return> diff --git a/doc/classes/StreamPeerTCP.xml b/doc/classes/StreamPeerTCP.xml index 664ffc60c3..9a0fceddab 100644 --- a/doc/classes/StreamPeerTCP.xml +++ b/doc/classes/StreamPeerTCP.xml @@ -4,7 +4,7 @@ TCP Stream peer. </brief_description> <description> - TCP Stream peer. This object can be used to connect to TCP servers, or also is returned by a tcp server. + TCP Stream peer. This object can be used to connect to TCP servers, or also is returned by a TCP server. </description> <tutorials> </tutorials> @@ -54,6 +54,7 @@ <return type="bool"> </return> <description> + Returns [code]true[/code] if this peer is currently connected to a host, [code]false[code] otherwise. </description> </method> <method name="set_no_delay"> diff --git a/doc/classes/SurfaceTool.xml b/doc/classes/SurfaceTool.xml index 4f9ac68e47..2e5d5d81c9 100644 --- a/doc/classes/SurfaceTool.xml +++ b/doc/classes/SurfaceTool.xml @@ -149,7 +149,7 @@ <argument index="2" name="transform" type="Transform"> </argument> <description> - Append vertices from a given [Mesh] surface onto the current vertex array with specified [Transform]. + Append vertices from a given [Mesh] surface onto the current vertex array with specified [Transform]. </description> </method> <method name="begin"> @@ -187,7 +187,7 @@ <argument index="1" name="surface" type="int"> </argument> <description> - Creates a vertex array from an existing [Mesh]. + Creates a vertex array from an existing [Mesh]. </description> </method> <method name="deindex"> diff --git a/doc/classes/Tween.xml b/doc/classes/Tween.xml index 1dc03ed314..e792835605 100644 --- a/doc/classes/Tween.xml +++ b/doc/classes/Tween.xml @@ -14,7 +14,7 @@ tween.start() [/codeblock] Many methods require a property name, such as "position" above. You can find the correct property name by hovering over the property in the Inspector. - Many of the methods accept [code]trans_type[/code] and [code]ease_type[/code]. The first accepts an [enum TransitionType] constant, and refers to the way the timing of the animation is handled (see [code]http://easings.net/[/code] for some examples). The second accepts an [enum EaseType] constant, and controls the where [code]trans_type[/code] is applied to the interpolation (in the beginning, the end, or both). If you don't know which transition and easing to pick, you can try different [enum TransitionType] constants with [enum EASE_IN_OUT], and use the one that looks best. + Many of the methods accept [code]trans_type[/code] and [code]ease_type[/code]. The first accepts an [enum TransitionType] constant, and refers to the way the timing of the animation is handled (see [code]http://easings.net/[/code] for some examples). The second accepts an [enum EaseType] constant, and controls the where [code]trans_type[/code] is applied to the interpolation (in the beginning, the end, or both). If you don't know which transition and easing to pick, you can try different [enum TransitionType] constants with [code]EASE_IN_OUT[/code], and use the one that looks best. </description> <tutorials> </tutorials> diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml index c323cf6992..1f8eb47044 100644 --- a/doc/classes/Vector2.xml +++ b/doc/classes/Vector2.xml @@ -259,10 +259,10 @@ </methods> <members> <member name="x" type="float" setter="" getter=""> - The vector's x component. + The vector's x component. Also accessible by using the index position [code][0][/code]. </member> <member name="y" type="float" setter="" getter=""> - The vector's y component. + The vector's y component. Also accessible by using the index position [code][1][/code]. </member> </members> <constants> diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml index 8c4e08778d..2499ba75ff 100644 --- a/doc/classes/Vector3.xml +++ b/doc/classes/Vector3.xml @@ -260,13 +260,13 @@ </methods> <members> <member name="x" type="float" setter="" getter=""> - The vector's x component. + The vector's x component. Also accessible by using the index position [code][0][/code]. </member> <member name="y" type="float" setter="" getter=""> - The vector's y component. + The vector's y component. Also accessible by using the index position [code][1][/code]. </member> <member name="z" type="float" setter="" getter=""> - The vector's z component. + The vector's z component. Also accessible by using the index position [code][2][/code]. </member> </members> <constants> diff --git a/doc/classes/YSort.xml b/doc/classes/YSort.xml index 12b9cb623f..45ae8645b1 100644 --- a/doc/classes/YSort.xml +++ b/doc/classes/YSort.xml @@ -14,6 +14,7 @@ </methods> <members> <member name="sort_enabled" type="bool" setter="set_sort_enabled" getter="is_sort_enabled"> + If [code]true[/code] child nodes are sorted, otherwise sorting is disabled. Default: [code]true[/code]. </member> </members> <constants> diff --git a/doc/tools/doc_merge.py b/doc/tools/doc_merge.py index 57ac4bdcdd..496d5dcb74 100644 --- a/doc/tools/doc_merge.py +++ b/doc/tools/doc_merge.py @@ -82,7 +82,7 @@ def find_signal_descr(old_class, name): def find_constant_descr(old_class, name): - if (old_class == None): + if (old_class is None): return None constants = old_class.find("constants") if(constants != None and len(list(constants)) > 0): diff --git a/doc/tools/makerst.py b/doc/tools/makerst.py index b3d6d32c26..7b7cc52547 100755 --- a/doc/tools/makerst.py +++ b/doc/tools/makerst.py @@ -375,7 +375,7 @@ def make_method( event=False, pp=None ): - if (declare or pp == None): + if (declare or pp is None): t = '- ' else: t = "" @@ -405,7 +405,7 @@ def make_method( t += 'void' t += ' ' - if declare or pp == None: + if declare or pp is None: s = '**' + method_data.attrib['name'] + '** ' else: @@ -577,7 +577,7 @@ def make_rst_class(node): make_method(f, name, m, True, True) f.write('\n') d = m.find('description') - if d == None or d.text.strip() == '': + if d is None or d.text.strip() == '': continue f.write(rstize_text(d.text.strip(), name)) f.write("\n\n") @@ -676,7 +676,7 @@ def make_rst_class(node): make_method(f, name, m, True) f.write('\n') d = m.find('description') - if d == None or d.text.strip() == '': + if d is None or d.text.strip() == '': continue f.write(rstize_text(d.text.strip(), name)) f.write("\n\n") diff --git a/drivers/coreaudio/audio_driver_coreaudio.cpp b/drivers/coreaudio/audio_driver_coreaudio.cpp index aaec63d7ff..850b90d59b 100644 --- a/drivers/coreaudio/audio_driver_coreaudio.cpp +++ b/drivers/coreaudio/audio_driver_coreaudio.cpp @@ -145,9 +145,6 @@ Error AudioDriverCoreAudio::init() { unsigned int buffer_size = buffer_frames * channels; samples_in.resize(buffer_size); input_buf.resize(buffer_size); - input_buffer.resize(buffer_size * 8); - input_position = 0; - input_size = 0; print_verbose("CoreAudio: detected " + itos(channels) + " channels"); print_verbose("CoreAudio: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms"); @@ -487,6 +484,8 @@ void AudioDriverCoreAudio::capture_finish() { Error AudioDriverCoreAudio::capture_start() { + input_buffer_init(buffer_frames); + OSStatus result = AudioOutputUnitStart(input_unit); if (result != noErr) { ERR_PRINTS("AudioOutputUnitStart failed, code: " + itos(result)); diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp index 18b5dd3483..9227c04e71 100644 --- a/drivers/gles2/rasterizer_canvas_gles2.cpp +++ b/drivers/gles2/rasterizer_canvas_gles2.cpp @@ -1111,6 +1111,7 @@ void RasterizerCanvasGLES2::initialize() { // polygon buffer { uint32_t poly_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); poly_size *= 1024; poly_size = MAX(poly_size, (2 + 2 + 4) * 4 * sizeof(float)); glGenBuffers(1, &data.polygon_buffer); @@ -1122,6 +1123,7 @@ void RasterizerCanvasGLES2::initialize() { glBindBuffer(GL_ARRAY_BUFFER, 0); uint32_t index_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_index_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_index_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_index_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); index_size *= 1024; // kb glGenBuffers(1, &data.polygon_index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); diff --git a/drivers/gles2/rasterizer_scene_gles2.cpp b/drivers/gles2/rasterizer_scene_gles2.cpp index fbcbebc88c..c4b6c607a2 100644 --- a/drivers/gles2/rasterizer_scene_gles2.cpp +++ b/drivers/gles2/rasterizer_scene_gles2.cpp @@ -2455,13 +2455,20 @@ void RasterizerSceneGLES2::_draw_sky(RasterizerStorageGLES2::Sky *p_sky, const C glEnableVertexAttribArray(VS::ARRAY_VERTEX); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_ASYM_PANO, asymmetrical); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, !asymmetrical); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, true); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); - storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, true); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, false); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, false); storage->shaders.copy.bind(); storage->shaders.copy.set_uniform(CopyShaderGLES2::MULTIPLIER, p_energy); + if (asymmetrical) { + // pack the bits we need from our projection matrix + storage->shaders.copy.set_uniform(CopyShaderGLES2::ASYM_PROJ, camera.matrix[2][0], camera.matrix[0][0], camera.matrix[2][1], camera.matrix[1][1]); + ///@TODO I couldn't get mat3 + p_transform.basis to work, that would be better here. + storage->shaders.copy.set_uniform(CopyShaderGLES2::PANO_TRANSFORM, p_transform); + } glDrawArrays(GL_TRIANGLE_FAN, 0, 4); @@ -2469,6 +2476,8 @@ void RasterizerSceneGLES2::_draw_sky(RasterizerStorageGLES2::Sky *p_sky, const C glDisableVertexAttribArray(VS::ARRAY_TEX_UV); glBindBuffer(GL_ARRAY_BUFFER, 0); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_ASYM_PANO, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, false); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, false); storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); } @@ -3037,6 +3046,7 @@ void RasterizerSceneGLES2::initialize() { { uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/limits/buffers/immediate_buffer_size_kb", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/immediate_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/immediate_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); glGenBuffers(1, &state.immediate_buffer); glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); diff --git a/drivers/gles2/rasterizer_storage_gles2.cpp b/drivers/gles2/rasterizer_storage_gles2.cpp index d5865064cf..c4c5093540 100644 --- a/drivers/gles2/rasterizer_storage_gles2.cpp +++ b/drivers/gles2/rasterizer_storage_gles2.cpp @@ -613,8 +613,72 @@ Ref<Image> RasterizerStorageGLES2::texture_get_data(RID p_texture, int p_layer) return Ref<Image>(img); #else - ERR_EXPLAIN("Sorry, It's not possible to obtain images back in OpenGL ES"); - ERR_FAIL_V(Ref<Image>()); + Image::Format real_format; + GLenum gl_format; + GLenum gl_internal_format; + GLenum gl_type; + bool compressed; + _get_gl_image_and_format(Ref<Image>(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed); + + PoolVector<uint8_t> data; + + int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, Image::FORMAT_RGBA8, false); + + data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers + PoolVector<uint8_t>::Write wb = data.write(); + + GLuint temp_framebuffer; + glGenFramebuffers(1, &temp_framebuffer); + + GLuint temp_color_texture; + glGenTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, temp_framebuffer); + + glBindTexture(GL_TEXTURE_2D, temp_color_texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->alloc_width, texture->alloc_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_color_texture, 0); + + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glColorMask(1, 1, 1, 1); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture->tex_id); + + glViewport(0, 0, texture->alloc_width, texture->alloc_height); + + shaders.copy.bind(); + + glClearColor(0.0, 0.0, 0.0, 0.0); + glClear(GL_COLOR_BUFFER_BIT); + bind_quad_array(); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + glReadPixels(0, 0, texture->alloc_width, texture->alloc_height, GL_RGBA, GL_UNSIGNED_BYTE, &wb[0]); + + glDeleteTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &temp_framebuffer); + + wb = PoolVector<uint8_t>::Write(); + + data.resize(data_size); + + Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, false, Image::FORMAT_RGBA8, data)); + if (!texture->compressed) { + img->convert(real_format); + } + + return Ref<Image>(img); + #endif } diff --git a/drivers/gles2/shaders/canvas.glsl b/drivers/gles2/shaders/canvas.glsl index b990384949..79d4eb2243 100644 --- a/drivers/gles2/shaders/canvas.glsl +++ b/drivers/gles2/shaders/canvas.glsl @@ -148,7 +148,10 @@ void main() { vec4 color = color_interp; +#if !defined(COLOR_USED) + //default behavior, texture by color color *= texture2D(color_texture, uv_interp); +#endif #ifdef SCREEN_UV_USED vec2 screen_uv = gl_FragCoord.xy * screen_pixel_size; diff --git a/drivers/gles2/shaders/copy.glsl b/drivers/gles2/shaders/copy.glsl index 16bbde196d..0b8da4f875 100644 --- a/drivers/gles2/shaders/copy.glsl +++ b/drivers/gles2/shaders/copy.glsl @@ -35,6 +35,8 @@ void main() { #if defined(USE_CUBEMAP) || defined(USE_PANORAMA) cube_interp = cube_in; +#elif defined(USE_ASYM_PANO) + uv_interp = vertex_attrib.xy; #else uv_interp = uv_in; #endif @@ -68,6 +70,11 @@ varying vec2 uv_interp; #endif /* clang-format on */ +#ifdef USE_ASYM_PANO +uniform highp mat4 pano_transform; +uniform highp vec4 asym_proj; +#endif + #ifdef USE_CUBEMAP uniform samplerCube source_cube; // texunit:0 #else @@ -108,6 +115,21 @@ void main() { vec4 color = texturePanorama(source, normalize(cube_interp)); +#elif defined(USE_ASYM_PANO) + + // When an asymmetrical projection matrix is used (applicable for stereoscopic rendering i.e. VR) we need to do this calculation per fragment to get a perspective correct result. + // Note that we're ignoring the x-offset for IPD, with Z sufficiently in the distance it becomes neglectible, as a result we could probably just set cube_normal.z to -1. + // The Matrix[2][0] (= asym_proj.x) and Matrix[2][1] (= asym_proj.z) values are what provide the right shift in the image. + + vec3 cube_normal; + cube_normal.z = -1000000.0; + cube_normal.x = (cube_normal.z * (-uv_interp.x - asym_proj.x)) / asym_proj.y; + cube_normal.y = (cube_normal.z * (-uv_interp.y - asym_proj.z)) / asym_proj.a; + cube_normal = mat3(pano_transform) * cube_normal; + cube_normal.z = -cube_normal.z; + + vec4 color = texturePanorama(source, normalize(cube_normal.xyz)); + #elif defined(USE_CUBEMAP) vec4 color = textureCube(source_cube, normalize(cube_interp)); #else diff --git a/drivers/gles2/shaders/scene.glsl b/drivers/gles2/shaders/scene.glsl index 7b57f5d497..2a781605d1 100644 --- a/drivers/gles2/shaders/scene.glsl +++ b/drivers/gles2/shaders/scene.glsl @@ -359,7 +359,7 @@ void main() { normal = normalize((world_matrix * vec4(normal, 0.0)).xyz); #if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) - tangent = normalize((world_matrix * vec4(tangent, 0.0)), xyz); + tangent = normalize((world_matrix * vec4(tangent, 0.0)).xyz); binormal = normalize((world_matrix * vec4(binormal, 0.0)).xyz); #endif #endif @@ -1307,8 +1307,7 @@ LIGHT_SHADER_CODE #define SAMPLE_SHADOW_TEXEL(p_shadow, p_pos, p_depth) step(p_depth, texture2D(p_shadow, p_pos).r) #define SAMPLE_SHADOW_TEXEL_PROJ(p_shadow, p_pos) step(p_pos.z, texture2DProj(p_shadow, p_pos).r) -float sample_shadow( - highp sampler2D shadow, highp vec4 spos) { +float sample_shadow(highp sampler2D shadow, highp vec4 spos) { #ifdef SHADOW_MODE_PCF_13 @@ -1923,12 +1922,12 @@ FRAGMENT_SHADER_CODE highp vec4 splane = shadow_coord; splane.xyz /= splane.w; - float shadow = sample_shadow(light_shadow_atlas, splane.xy, splane.z); + float shadow = sample_shadow(light_shadow_atlas, splane); light_att *= shadow; } #endif -#endif +#endif // LIGHT_MODE_SPOT #ifdef USE_VERTEX_LIGHTING //vertex lighting diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp index a9b46baf53..f0932c2f80 100644 --- a/drivers/gles3/rasterizer_canvas_gles3.cpp +++ b/drivers/gles3/rasterizer_canvas_gles3.cpp @@ -2027,6 +2027,7 @@ void RasterizerCanvasGLES3::initialize() { { uint32_t poly_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); poly_size *= 1024; //kb poly_size = MAX(poly_size, (2 + 2 + 4) * 4 * sizeof(float)); glGenBuffers(1, &data.polygon_buffer); @@ -2074,6 +2075,7 @@ void RasterizerCanvasGLES3::initialize() { glGenVertexArrays(1, &data.polygon_buffer_pointer_array); uint32_t index_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); index_size *= 1024; //kb glGenBuffers(1, &data.polygon_index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); diff --git a/drivers/gles3/rasterizer_gles3.cpp b/drivers/gles3/rasterizer_gles3.cpp index d3cd01a903..2f6a556773 100644 --- a/drivers/gles3/rasterizer_gles3.cpp +++ b/drivers/gles3/rasterizer_gles3.cpp @@ -436,6 +436,7 @@ void RasterizerGLES3::register_config() { GLOBAL_DEF("rendering/quality/filters/anisotropic_filter_level", 4); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/filters/anisotropic_filter_level", PropertyInfo(Variant::INT, "rendering/quality/filters/anisotropic_filter_level", PROPERTY_HINT_RANGE, "1,16,1")); GLOBAL_DEF("rendering/limits/time/time_rollover_secs", 3600); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/time/time_rollover_secs", PropertyInfo(Variant::REAL, "rendering/limits/time/time_rollover_secs", PROPERTY_HINT_RANGE, "0,10000,1,or_greater")); } RasterizerGLES3::RasterizerGLES3() { diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp index fcb68f44fe..792e9eb238 100644 --- a/drivers/gles3/rasterizer_scene_gles3.cpp +++ b/drivers/gles3/rasterizer_scene_gles3.cpp @@ -1428,7 +1428,16 @@ void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e, const Transfo if (particles->draw_order == VS::PARTICLES_DRAW_ORDER_VIEW_DEPTH && particles->particle_valid_histories[1]) { glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[1]); //modify the buffer, this was used 2 frames ago so it should be good enough for flushing - RasterizerGLES3Particle *particle_array = (RasterizerGLES3Particle *)glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 24 * sizeof(float), GL_MAP_READ_BIT | GL_MAP_WRITE_BIT); + RasterizerGLES3Particle *particle_array; +#ifndef __EMSCRIPTEN__ + particle_array = static_cast<RasterizerGLES3Particle *>(glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 24 * sizeof(float), GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); +#else + PoolVector<RasterizerGLES3Particle> particle_vector; + particle_vector.resize(particles->amount); + PoolVector<RasterizerGLES3Particle>::Write w = particle_vector.write(); + particle_array = w.ptr(); + glGetBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), particle_array); +#endif SortArray<RasterizerGLES3Particle, RasterizerGLES3ParticleSort> sorter; @@ -1440,7 +1449,17 @@ void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e, const Transfo sorter.sort(particle_array, particles->amount); +#ifndef __EMSCRIPTEN__ glUnmapBuffer(GL_ARRAY_BUFFER); +#else + w = PoolVector<RasterizerGLES3Particle>::Write(); + particle_array = NULL; + { + PoolVector<RasterizerGLES3Particle>::Read r = particle_vector.read(); + glBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), r.ptr()); + } + particle_vector = PoolVector<RasterizerGLES3Particle>(); +#endif #ifdef DEBUG_ENABLED if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) { glBindVertexArray(s->instancing_array_wireframe_id); // use the wireframe instancing array ID @@ -4852,10 +4871,7 @@ void RasterizerSceneGLES3::initialize() { glBindBuffer(GL_UNIFORM_BUFFER, 0); render_list.max_elements = GLOBAL_DEF_RST("rendering/limits/rendering/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS); - if (render_list.max_elements > 1000000) - render_list.max_elements = 1000000; - if (render_list.max_elements < 1024) - render_list.max_elements = 1024; + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_elements", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_elements", PROPERTY_HINT_RANGE, "1024,1000000,1")); { //quad buffers @@ -5054,6 +5070,7 @@ void RasterizerSceneGLES3::initialize() { { uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/limits/buffers/immediate_buffer_size_kb", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/immediate_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/immediate_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); glGenBuffers(1, &state.immediate_buffer); glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp index a9aa152f10..c06ef805a6 100644 --- a/drivers/gles3/rasterizer_storage_gles3.cpp +++ b/drivers/gles3/rasterizer_storage_gles3.cpp @@ -101,6 +101,28 @@ #define _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E #define _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#ifdef __EMSCRIPTEN__ +#include <emscripten/emscripten.h> + +void glGetBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data) { + + /* clang-format off */ + EM_ASM({ + GLctx.getBufferSubData($0, $1, HEAPU8, $2, $3); + }, target, offset, data, size); + /* clang-format on */ +} + +void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data) { + + /* clang-format off */ + EM_ASM({ + GLctx.bufferSubData($0, $1, HEAPU8, $2, $3); + }, target, offset, data, size); + /* clang-format on */ +} +#endif + void glTexStorage2DCustom(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type) { #ifdef GLES_OVER_GL @@ -1094,8 +1116,78 @@ Ref<Image> RasterizerStorageGLES3::texture_get_data(RID p_texture, int p_layer) return Ref<Image>(img); #else - ERR_EXPLAIN("Sorry, It's not possible to obtain images back in OpenGL ES"); - ERR_FAIL_V(Ref<Image>()); + Image::Format real_format; + GLenum gl_format; + GLenum gl_internal_format; + GLenum gl_type; + bool compressed; + bool srgb; + _get_gl_image_and_format(Ref<Image>(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed, srgb); + + PoolVector<uint8_t> data; + + int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, Image::FORMAT_RGBA8, false); + + data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers + PoolVector<uint8_t>::Write wb = data.write(); + + GLuint temp_framebuffer; + glGenFramebuffers(1, &temp_framebuffer); + + GLuint temp_color_texture; + glGenTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, temp_framebuffer); + + glBindTexture(GL_TEXTURE_2D, temp_color_texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->alloc_width, texture->alloc_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + + print_line(itos(texture->alloc_width) + " xx " + itos(texture->alloc_height) + " -> " + itos(real_format)); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_color_texture, 0); + + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glColorMask(1, 1, 1, 1); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture->tex_id); + + glViewport(0, 0, texture->alloc_width, texture->alloc_height); + + shaders.copy.bind(); + + shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, !srgb); + + glClearColor(0.0, 0.0, 0.0, 0.0); + glClear(GL_COLOR_BUFFER_BIT); + glBindVertexArray(resources.quadie_array); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glBindVertexArray(0); + + glReadPixels(0, 0, texture->alloc_width, texture->alloc_height, GL_RGBA, GL_UNSIGNED_BYTE, &wb[0]); + + shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false); + + glDeleteTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &temp_framebuffer); + + wb = PoolVector<uint8_t>::Write(); + + data.resize(data_size); + + Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, false, Image::FORMAT_RGBA8, data)); + if (!texture->compressed) { + img->convert(real_format); + } + + return Ref<Image>(img); #endif } @@ -3494,21 +3586,26 @@ PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, i Surface *surface = mesh->surfaces[p_surface]; - glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id); - void *data = glMapBufferRange(GL_ARRAY_BUFFER, 0, surface->array_byte_size, GL_MAP_READ_BIT); - - ERR_FAIL_COND_V(!data, PoolVector<uint8_t>()); - PoolVector<uint8_t> ret; ret.resize(surface->array_byte_size); + glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id); +#if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__) + { + PoolVector<uint8_t>::Write w = ret.write(); + glGetBufferSubData(GL_ARRAY_BUFFER, 0, surface->array_byte_size, w.ptr()); + } +#else + void *data = glMapBufferRange(GL_ARRAY_BUFFER, 0, surface->array_byte_size, GL_MAP_READ_BIT); + ERR_FAIL_NULL_V(data, PoolVector<uint8_t>()); { - PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(), data, surface->array_byte_size); } glUnmapBuffer(GL_ARRAY_BUFFER); +#endif + glBindBuffer(GL_ARRAY_BUFFER, 0); return ret; } @@ -3521,22 +3618,26 @@ PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_m ERR_FAIL_COND_V(surface->index_array_len == 0, PoolVector<uint8_t>()); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id); - void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, GL_MAP_READ_BIT); - - ERR_FAIL_COND_V(!data, PoolVector<uint8_t>()); - PoolVector<uint8_t> ret; ret.resize(surface->index_array_byte_size); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id); +#if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__) + { + PoolVector<uint8_t>::Write w = ret.write(); + glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, w.ptr()); + } +#else + void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, GL_MAP_READ_BIT); + ERR_FAIL_NULL_V(data, PoolVector<uint8_t>()); { - PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(), data, surface->index_array_byte_size); } - glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); +#endif + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return ret; } @@ -3577,23 +3678,26 @@ Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shap for (int i = 0; i < mesh->surfaces[p_surface]->blend_shapes.size(); i++) { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->surfaces[p_surface]->blend_shapes[i].vertex_id); - void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, GL_MAP_READ_BIT); - - ERR_FAIL_COND_V(!data, Vector<PoolVector<uint8_t> >()); - PoolVector<uint8_t> ret; ret.resize(mesh->surfaces[p_surface]->array_byte_size); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->surfaces[p_surface]->blend_shapes[i].vertex_id); +#if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__) + { + PoolVector<uint8_t>::Write w = ret.write(); + glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, w.ptr()); + } +#else + void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, GL_MAP_READ_BIT); + ERR_FAIL_COND_V(!data, Vector<PoolVector<uint8_t> >()); { - PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(), data, mesh->surfaces[p_surface]->array_byte_size); } + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); +#endif bsarr.push_back(ret); - - glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); } return bsarr; @@ -6001,9 +6105,21 @@ AABB RasterizerStorageGLES3::particles_get_current_aabb(RID p_particles) { const Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND_V(!particles, AABB()); + const float *data; glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]); - float *data = (float *)glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 16 * 6, GL_MAP_READ_BIT); +#if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__) + PoolVector<uint8_t> vector; + vector.resize(particles->amount * 16 * 6); + { + PoolVector<uint8_t>::Write w = vector.write(); + glGetBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * 16 * 6, w.ptr()); + } + PoolVector<uint8_t>::Read r = vector.read(); + data = reinterpret_cast<const float *>(r.ptr()); +#else + data = (float *)glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 16 * 6, GL_MAP_READ_BIT); +#endif AABB aabb; Transform inv = particles->emission_transform.affine_inverse(); @@ -6020,7 +6136,13 @@ AABB RasterizerStorageGLES3::particles_get_current_aabb(RID p_particles) { aabb.expand_to(pos); } +#if defined(GLES_OVER_GL) || defined(__EMSCRIPTEN__) + r = PoolVector<uint8_t>::Read(); + vector = PoolVector<uint8_t>(); +#else glUnmapBuffer(GL_ARRAY_BUFFER); +#endif + glBindBuffer(GL_ARRAY_BUFFER, 0); float longest_axis = 0; @@ -7686,6 +7808,8 @@ void RasterizerStorageGLES3::initialize() { { //transform feedback buffers uint32_t xf_feedback_size = GLOBAL_DEF_RST("rendering/limits/buffers/blend_shape_max_buffer_size_kb", 4096); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/blend_shape_max_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/blend_shape_max_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); + for (int i = 0; i < 2; i++) { glGenBuffers(1, &resources.transform_feedback_buffers[i]); diff --git a/drivers/gles3/rasterizer_storage_gles3.h b/drivers/gles3/rasterizer_storage_gles3.h index 9a4798ac2a..8c26e09037 100644 --- a/drivers/gles3/rasterizer_storage_gles3.h +++ b/drivers/gles3/rasterizer_storage_gles3.h @@ -43,6 +43,12 @@ #include "shaders/cubemap_filter.glsl.gen.h" #include "shaders/particles.glsl.gen.h" +// WebGL 2.0 has no MapBufferRange/UnmapBuffer, but offers a non-ES style BufferSubData API instead. +#ifdef __EMSCRIPTEN__ +void glGetBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data); +void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); +#endif + class RasterizerCanvasGLES3; class RasterizerSceneGLES3; diff --git a/drivers/gles3/shaders/scene.glsl b/drivers/gles3/shaders/scene.glsl index 8388b15edb..91ab34f775 100644 --- a/drivers/gles3/shaders/scene.glsl +++ b/drivers/gles3/shaders/scene.glsl @@ -2053,7 +2053,7 @@ FRAGMENT_SHADER_CODE emission = emission * rev_amount + fog_color * fog_amount; ambient_light *= rev_amount; - specular_light *rev_amount; + specular_light *= rev_amount; diffuse_light *= rev_amount; } diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp index 9c02549e39..d78316945f 100644 --- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp +++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp @@ -613,20 +613,18 @@ Error AudioDriverPulseAudio::capture_init_device() { break; } - print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels"); - pa_sample_spec spec; spec.format = PA_SAMPLE_S16LE; spec.channels = pa_rec_map.channels; spec.rate = mix_rate; - int latency = 30; - input_buffer_frames = closest_power_of_2(latency * mix_rate / 1000); - int buffer_size = input_buffer_frames * spec.channels; + int input_latency = 30; + int input_buffer_frames = closest_power_of_2(input_latency * mix_rate / 1000); + int input_buffer_size = input_buffer_frames * spec.channels; pa_buffer_attr attr; - attr.fragsize = buffer_size * sizeof(int16_t); + attr.fragsize = input_buffer_size * sizeof(int16_t); pa_rec_str = pa_stream_new(pa_ctx, "Record", &spec, &pa_rec_map); if (pa_rec_str == NULL) { @@ -642,9 +640,10 @@ Error AudioDriverPulseAudio::capture_init_device() { ERR_FAIL_V(ERR_CANT_OPEN); } - input_buffer.resize(input_buffer_frames * 8); - input_position = 0; - input_size = 0; + input_buffer_init(input_buffer_frames); + + print_verbose("PulseAudio: detected " + itos(pa_rec_map.channels) + " input channels"); + print_verbose("PulseAudio: input buffer frames: " + itos(input_buffer_frames) + " calculated latency: " + itos(input_buffer_frames * 1000 / mix_rate) + "ms"); return OK; } @@ -760,7 +759,6 @@ AudioDriverPulseAudio::AudioDriverPulseAudio() { mix_rate = 0; buffer_frames = 0; - input_buffer_frames = 0; pa_buffer_size = 0; channels = 0; pa_ready = 0; diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.h b/drivers/pulseaudio/audio_driver_pulseaudio.h index f8358a452b..d8bab841ff 100644 --- a/drivers/pulseaudio/audio_driver_pulseaudio.h +++ b/drivers/pulseaudio/audio_driver_pulseaudio.h @@ -64,7 +64,6 @@ class AudioDriverPulseAudio : public AudioDriver { unsigned int mix_rate; unsigned int buffer_frames; - unsigned int input_buffer_frames; unsigned int pa_buffer_size; int channels; int pa_ready; diff --git a/drivers/rtaudio/audio_driver_rtaudio.cpp b/drivers/rtaudio/audio_driver_rtaudio.cpp index 9353128333..bc6ceb1e7e 100644 --- a/drivers/rtaudio/audio_driver_rtaudio.cpp +++ b/drivers/rtaudio/audio_driver_rtaudio.cpp @@ -114,11 +114,12 @@ Error AudioDriverRtAudio::init() { unsigned int buffer_frames = closest_power_of_2(latency * mix_rate / 1000); print_verbose("Audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms"); - short int tries = 2; + short int tries = 4; - while (tries >= 0) { + while (tries > 0) { switch (speaker_mode) { case SPEAKER_MODE_STEREO: parameters.nChannels = 2; break; + case SPEAKER_SURROUND_31: parameters.nChannels = 4; break; case SPEAKER_SURROUND_51: parameters.nChannels = 6; break; case SPEAKER_SURROUND_71: parameters.nChannels = 8; break; }; @@ -133,7 +134,9 @@ Error AudioDriverRtAudio::init() { ERR_PRINT("Unable to open audio, retrying with fewer channels..."); switch (speaker_mode) { - case SPEAKER_SURROUND_51: speaker_mode = SPEAKER_MODE_STEREO; break; + case SPEAKER_MODE_STEREO: break; // Required to silence unhandled enum value warning. + case SPEAKER_SURROUND_31: speaker_mode = SPEAKER_MODE_STEREO; break; + case SPEAKER_SURROUND_51: speaker_mode = SPEAKER_SURROUND_31; break; case SPEAKER_SURROUND_71: speaker_mode = SPEAKER_SURROUND_51; break; } diff --git a/drivers/unix/net_socket_posix.cpp b/drivers/unix/net_socket_posix.cpp index 2cc2032cbb..f981be66ce 100644 --- a/drivers/unix/net_socket_posix.cpp +++ b/drivers/unix/net_socket_posix.cpp @@ -55,7 +55,7 @@ #include <netinet/tcp.h> -#if defined(OSX_ENABLED) || defined(IPHONE_ENABLED) +#if defined(__APPLE__) #define MSG_NOSIGNAL SO_NOSIGPIPE #endif diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp index 7ff27be501..279274734f 100644 --- a/drivers/unix/os_unix.cpp +++ b/drivers/unix/os_unix.cpp @@ -288,6 +288,11 @@ uint64_t OS_Unix::get_ticks_usec() const { Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr) { +#ifdef __EMSCRIPTEN__ + // Don't compile this code at all to avoid undefined references. + // Actual virtual call goes to OS_JavaScript. + ERR_FAIL_V(ERR_BUG); +#else if (p_blocking && r_pipe) { String argss; @@ -354,6 +359,7 @@ Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, bo } return OK; +#endif } Error OS_Unix::kill(const ProcessID &p_pid) { diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp index a91e41b008..8665f701b1 100644 --- a/drivers/wasapi/audio_driver_wasapi.cpp +++ b/drivers/wasapi/audio_driver_wasapi.cpp @@ -336,10 +336,7 @@ Error AudioDriverWASAPI::init_capture_device(bool reinit) { HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames); ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN); - // Set the buffer size - input_buffer.resize(max_frames * CAPTURE_BUFFER_CHANNELS); - input_position = 0; - input_size = 0; + input_buffer_init(max_frames); return OK; } diff --git a/editor/editor_about.cpp b/editor/editor_about.cpp index cdf0e4b829..2f2840192a 100644 --- a/editor/editor_about.cpp +++ b/editor/editor_about.cpp @@ -47,7 +47,9 @@ void EditorAbout::_notification(int p_what) { Control *base = EditorNode::get_singleton()->get_gui_base(); Ref<Font> font = base->get_font("source", "EditorFonts"); _tpl_text->add_font_override("normal_font", font); + _tpl_text->add_constant_override("line_separation", 6 * EDSCALE); _license_text->add_font_override("normal_font", font); + _license_text->add_constant_override("line_separation", 6 * EDSCALE); _logo->set_texture(base->get_icon("Logo", "EditorIcons")); } break; } diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp index 1a6188862f..218063566a 100644 --- a/editor/editor_export.cpp +++ b/editor/editor_export.cpp @@ -144,6 +144,17 @@ String EditorExportPreset::get_include_filter() const { return include_filter; } +void EditorExportPreset::set_export_path(const String &p_path) { + + export_path = p_path; + EditorExport::singleton->save_presets(); +} + +String EditorExportPreset::get_export_path() const { + + return export_path; +} + void EditorExportPreset::set_exclude_filter(const String &p_exclude) { exclude_filter = p_exclude; @@ -213,6 +224,7 @@ String EditorExportPreset::get_custom_features() const { EditorExportPreset::EditorExportPreset() { + export_path = ""; export_filter = EXPORT_ALL_RESOURCES; runnable = false; } @@ -1034,6 +1046,7 @@ void EditorExport::_save() { } config->set_value(section, "include_filter", preset->get_include_filter()); config->set_value(section, "exclude_filter", preset->get_exclude_filter()); + config->set_value(section, "export_path", preset->get_export_path()); config->set_value(section, "patch_list", preset->get_patches()); String option_section = "preset." + itos(i) + ".options"; @@ -1189,6 +1202,7 @@ void EditorExport::load_config() { preset->set_include_filter(config->get_value(section, "include_filter")); preset->set_exclude_filter(config->get_value(section, "exclude_filter")); + preset->set_export_path(config->get_value(section, "export_path", "")); Vector<String> patch_list = config->get_value(section, "patch_list"); diff --git a/editor/editor_export.h b/editor/editor_export.h index b4ee5b89e7..d1165fd042 100644 --- a/editor/editor_export.h +++ b/editor/editor_export.h @@ -57,6 +57,7 @@ private: ExportFilter export_filter; String include_filter; String exclude_filter; + String export_path; String exporter; Set<String> selected_files; @@ -114,6 +115,9 @@ public: void set_custom_features(const String &p_custom_features); String get_custom_features() const; + void set_export_path(const String &p_path); + String get_export_path() const; + const List<PropertyInfo> &get_properties() const { return properties; } EditorExportPreset(); diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp index f425d0a995..438d7ea306 100644 --- a/editor/editor_file_dialog.cpp +++ b/editor/editor_file_dialog.cpp @@ -1135,14 +1135,10 @@ void EditorFileDialog::_update_drives() { } void EditorFileDialog::_favorite_selected(int p_idx) { - - Vector<String> favorited = EditorSettings::get_singleton()->get_favorites(); - ERR_FAIL_INDEX(p_idx, favorited.size()); - - dir_access->change_dir(favorited[p_idx]); + dir_access->change_dir(favorites->get_item_metadata(p_idx)); file->set_text(""); - invalidate(); update_dir(); + invalidate(); _push_history(); } @@ -1192,7 +1188,7 @@ void EditorFileDialog::_update_favorites() { bool res = access == ACCESS_RESOURCES; String current = get_current_dir(); - Ref<Texture> star = get_icon("Favorites", "EditorIcons"); + Ref<Texture> folder_icon = get_icon("Folder", "EditorIcons"); favorites->clear(); favorite->set_pressed(false); @@ -1203,16 +1199,23 @@ void EditorFileDialog::_update_favorites() { if (cres != res) continue; String name = favorited[i]; - - bool setthis = name == current; + bool setthis = false; if (res && name == "res://") { + if (name == current) + setthis = true; name = "/"; + } else if (name.ends_with("/")) { + if (name == current) + setthis = true; + name = name.substr(0, name.length() - 1); + name = name.get_file(); + + favorites->add_item(name, folder_icon); } else { - name = name.get_file() + "/"; + continue; // We don't handle favorite files here } - favorites->add_item(name, star); favorites->set_item_metadata(favorites->get_item_count() - 1, favorited[i]); if (setthis) { diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp index d73bf86f64..a99c9656ba 100644 --- a/editor/editor_file_system.cpp +++ b/editor/editor_file_system.cpp @@ -1305,11 +1305,6 @@ void EditorFileSystem::_save_late_updated_files() { } } -void EditorFileSystem::_resource_saved(const String &p_path) { - - EditorFileSystem::get_singleton()->update_file(p_path); -} - Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) { List<String> deps; @@ -1772,7 +1767,6 @@ EditorFileSystem::EditorFileSystem() { abort_scan = false; scanning_changes = false; scanning_changes_done = false; - ResourceSaver::set_save_callback(_resource_saved); DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir("res://.import") != OK) { diff --git a/editor/editor_file_system.h b/editor/editor_file_system.h index 47077425a1..f6eef2a152 100644 --- a/editor/editor_file_system.h +++ b/editor/editor_file_system.h @@ -204,8 +204,6 @@ class EditorFileSystem : public Node { bool _update_scan_actions(); - static void _resource_saved(const String &p_path); - void _update_extensions(); void _reimport_file(const String &p_file); diff --git a/editor/editor_folding.cpp b/editor/editor_folding.cpp new file mode 100644 index 0000000000..eec4438f96 --- /dev/null +++ b/editor/editor_folding.cpp @@ -0,0 +1,175 @@ +#include "editor_folding.h" + +#include "core/os/file_access.h" +#include "editor_settings.h" + +PoolVector<String> EditorFolding::_get_unfolds(const Object *p_object) { + + PoolVector<String> sections; + sections.resize(p_object->editor_get_section_folding().size()); + if (sections.size()) { + PoolVector<String>::Write w = sections.write(); + int idx = 0; + for (const Set<String>::Element *E = p_object->editor_get_section_folding().front(); E; E = E->next()) { + w[idx++] = E->get(); + } + } + + return sections; +} + +void EditorFolding::save_resource_folding(const RES &p_resource, const String &p_path) { + Ref<ConfigFile> config; + config.instance(); + PoolVector<String> unfolds = _get_unfolds(p_resource.ptr()); + config->set_value("folding", "sections_unfolded", unfolds); + + String path = EditorSettings::get_singleton()->get_project_settings_dir(); + String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg"; + file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file); + config->save(file); +} + +void EditorFolding::_set_unfolds(Object *p_object, const PoolVector<String> &p_unfolds) { + + int uc = p_unfolds.size(); + PoolVector<String>::Read r = p_unfolds.read(); + p_object->editor_clear_section_folding(); + for (int i = 0; i < uc; i++) { + p_object->editor_set_section_unfold(r[i], true); + } +} + +void EditorFolding::load_resource_folding(RES p_resource, const String &p_path) { + + Ref<ConfigFile> config; + config.instance(); + + String path = EditorSettings::get_singleton()->get_project_settings_dir(); + String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg"; + file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file); + + if (config->load(file) != OK) { + return; + } + + PoolVector<String> unfolds; + + if (config->has_section_key("folding", "sections_unfolded")) { + unfolds = config->get_value("folding", "sections_unfolded"); + } + _set_unfolds(p_resource.ptr(), unfolds); +} + +void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Set<RES> &resources) { + if (p_root != p_node) { + if (!p_node->get_owner()) { + return; //not owned, bye + } + if (p_node->get_owner() != p_root && !p_root->is_editable_instance(p_node)) { + return; + } + } + + PoolVector<String> unfolds = _get_unfolds(p_node); + + if (unfolds.size()) { + p_folds.push_back(p_root->get_path_to(p_node)); + p_folds.push_back(unfolds); + } + + List<PropertyInfo> plist; + p_node->get_property_list(&plist); + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { + if (E->get().type == Variant::OBJECT) { + RES res = p_node->get(E->get().name); + if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) { + + PoolVector<String> res_unfolds = _get_unfolds(res.ptr()); + resource_folds.push_back(res->get_path()); + resource_folds.push_back(res_unfolds); + resources.insert(res); + } + } + } + + for (int i = 0; i < p_node->get_child_count(); i++) { + _fill_folds(p_root, p_node->get_child(i), p_folds, resource_folds, resources); + } +} +void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path) { + + Ref<ConfigFile> config; + config.instance(); + + Array unfolds, res_unfolds; + Set<RES> resources; + _fill_folds(p_scene, p_scene, unfolds, res_unfolds, resources); + + config->set_value("folding", "node_unfolds", unfolds); + config->set_value("folding", "resource_unfolds", res_unfolds); + + String path = EditorSettings::get_singleton()->get_project_settings_dir(); + String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg"; + file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file); + config->save(file); +} +void EditorFolding::load_scene_folding(Node *p_scene, const String &p_path) { + + Ref<ConfigFile> config; + config.instance(); + + String path = EditorSettings::get_singleton()->get_project_settings_dir(); + String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg"; + file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file); + + if (config->load(file) != OK) { + return; + } + + Array unfolds; + if (config->has_section_key("folding", "node_unfolds")) { + unfolds = config->get_value("folding", "node_unfolds"); + } + Array res_unfolds; + if (config->has_section_key("folding", "resource_unfolds")) { + res_unfolds = config->get_value("folding", "resource_unfolds"); + } + + ERR_FAIL_COND(unfolds.size() & 1); + ERR_FAIL_COND(res_unfolds.size() & 1); + + for (int i = 0; i < unfolds.size(); i += 2) { + NodePath path = unfolds[i]; + PoolVector<String> un = unfolds[i + 1]; + Node *node = p_scene->get_node(path); + if (!node) { + continue; + } + _set_unfolds(node, un); + } + + for (int i = 0; i < res_unfolds.size(); i += 2) { + String path = res_unfolds[i]; + RES res; + if (ResourceCache::has(path)) { + res = RES(ResourceCache::get(path)); + } + if (res.is_null()) { + continue; + } + + PoolVector<String> unfolds = res_unfolds[i + 1]; + _set_unfolds(res.ptr(), unfolds); + } +} + +bool EditorFolding::has_folding_data(const String &p_path) { + String path = EditorSettings::get_singleton()->get_project_settings_dir(); + String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg"; + file = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(file); + return FileAccess::exists(file); +} + +EditorFolding::EditorFolding() { +} diff --git a/editor/editor_folding.h b/editor/editor_folding.h new file mode 100644 index 0000000000..cfd4b5466d --- /dev/null +++ b/editor/editor_folding.h @@ -0,0 +1,25 @@ +#ifndef EDITOR_FOLDING_H +#define EDITOR_FOLDING_H + +#include "scene/main/node.h" + +class EditorFolding { + + PoolVector<String> _get_unfolds(const Object *p_object); + void _set_unfolds(Object *p_object, const PoolVector<String> &p_unfolds); + + void _fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Set<RES> &resources); + +public: + void save_resource_folding(const RES &p_resource, const String &p_path); + void load_resource_folding(RES p_resource, const String &p_path); + + void save_scene_folding(const Node *p_scene, const String &p_path); + void load_scene_folding(Node *p_scene, const String &p_path); + + bool has_folding_data(const String &p_path); + + EditorFolding(); +}; + +#endif // EDITOR_FOLDING_H diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index a90f15004a..1230588016 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -36,6 +36,50 @@ #include "multi_node_edit.h" #include "scene/resources/packed_scene.h" +EditorDefaultClassValueCache *EditorDefaultClassValueCache::singleton = NULL; + +EditorDefaultClassValueCache *EditorDefaultClassValueCache::get_singleton() { + return singleton; +} + +Variant EditorDefaultClassValueCache::get_default_value(const StringName &p_class, const StringName &p_property) { + + if (!default_values.has(p_class)) { + + default_values[p_class] = Map<StringName, Variant>(); + + if (ClassDB::can_instance(p_class)) { + + Object *c = ClassDB::instance(p_class); + List<PropertyInfo> plist; + c->get_property_list(&plist); + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { + if (E->get().usage & PROPERTY_USAGE_EDITOR) { + + Variant v = c->get(E->get().name); + default_values[p_class][E->get().name] = v; + } + } + memdelete(c); + } + } + + if (!default_values.has(p_class)) { + return Variant(); + } + + if (!default_values[p_class].has(p_property)) { + return Variant(); + } + + return default_values[p_class][p_property]; +} + +EditorDefaultClassValueCache::EditorDefaultClassValueCache() { + ERR_FAIL_COND(singleton != NULL); + singleton = this; +} + Size2 EditorProperty::get_minimum_size() const { Size2 ms; @@ -458,6 +502,12 @@ void EditorProperty::update_reload_status() { bool has_reload = false; + if (EditorDefaultClassValueCache::get_singleton()) { + Variant default_value = EditorDefaultClassValueCache::get_singleton()->get_default_value(object->get_class_name(), property); + if (default_value != Variant() && default_value != object->get(property)) { + has_reload = true; + } + } if (_is_instanced_node_with_original_property_different()) { has_reload = true; } @@ -651,6 +701,7 @@ void EditorProperty::_gui_input(const Ref<InputEvent> &p_event) { Variant rev = object->call("property_get_revert", property); emit_signal("property_changed", property, rev); update_property(); + return; } if (!object->get_script().is_null()) { @@ -659,6 +710,16 @@ void EditorProperty::_gui_input(const Ref<InputEvent> &p_event) { if (scr->get_property_default_value(property, orig_value)) { emit_signal("property_changed", property, orig_value); update_property(); + return; + } + } + + if (EditorDefaultClassValueCache::get_singleton()) { + Variant default_value = EditorDefaultClassValueCache::get_singleton()->get_default_value(object->get_class_name(), property); + if (default_value != Variant()) { + emit_signal("property_changed", property, default_value); + update_property(); + return; } } } @@ -738,9 +799,9 @@ Control *EditorProperty::make_custom_tooltip(const String &p_text) const { tooltip_text = p_text; EditorHelpBit *help_bit = memnew(EditorHelpBit); help_bit->add_style_override("panel", get_stylebox("panel", "TooltipPanel")); - help_bit->get_rich_text()->set_fixed_size_to_width(300); + help_bit->get_rich_text()->set_fixed_size_to_width(360 * EDSCALE); - String text = TTR("Property: ") + "[u][b]" + p_text.get_slice("::", 0) + "[/b][/u]\n"; + String text = TTR("Property:") + " [u][b]" + p_text.get_slice("::", 0) + "[/b][/u]\n"; text += p_text.get_slice("::", 1).strip_edges(); help_bit->set_text(text); help_bit->call_deferred("set_text", text); //hack so it uses proper theme once inside scene @@ -960,7 +1021,7 @@ Control *EditorInspectorCategory::make_custom_tooltip(const String &p_text) cons tooltip_text = p_text; EditorHelpBit *help_bit = memnew(EditorHelpBit); help_bit->add_style_override("panel", get_stylebox("panel", "TooltipPanel")); - help_bit->get_rich_text()->set_fixed_size_to_width(300); + help_bit->get_rich_text()->set_fixed_size_to_width(360 * EDSCALE); String text = "[u][b]" + p_text.get_slice("::", 0) + "[/b][/u]\n"; text += p_text.get_slice("::", 1).strip_edges(); @@ -1370,6 +1431,28 @@ void EditorInspector::update_tree() { // TreeItem *current_category = NULL; + bool unfold_if_edited = false; + + if (use_folding && auto_unfold_edited && get_tree()->get_edited_scene_root()) { + String path; + Node *node = Object::cast_to<Node>(object); + if (node) { + path = get_tree()->get_edited_scene_root()->get_filename(); + } + Resource *res = Object::cast_to<Resource>(object); + if (res) { + if (res->get_path().is_resource_file()) { + path = res->get_path(); + } else if (res->get_path().begins_with("res://")) { //internal resource + path = get_tree()->get_edited_scene_root()->get_filename(); + } + } + + if (!EditorNode::get_singleton()->get_editor_folding().has_folding_data(path)) { + unfold_if_edited = true; + } + } + String filter = search_box ? search_box->get_text() : ""; String group; String group_base; @@ -1380,6 +1463,8 @@ void EditorInspector::update_tree() { object->get_property_list(&plist, true); HashMap<String, VBoxContainer *> item_path; + Map<VBoxContainer *, EditorInspectorSection *> section_map; + item_path[""] = main_vbox; Color sscolor = get_color("prop_subsection", "Editor"); @@ -1542,7 +1627,9 @@ void EditorInspector::update_tree() { c.a /= level; section->setup(acc_path, path_name, object, c, use_folding); - item_path[acc_path] = section->get_vbox(); + VBoxContainer *vb = section->get_vbox(); + item_path[acc_path] = vb; + section_map[vb] = section; } current_vbox = item_path[acc_path]; level = (MIN(level + 1, 4)); @@ -1685,6 +1772,13 @@ void EditorInspector::update_tree() { if (current_selected && ep->property == current_selected) { ep->select(current_focusable); } + + if (unfold_if_edited && ep->can_revert_to_default()) { + //if edited and there is a parent section, unfold it. + if (current_vbox && section_map.has(current_vbox)) { + section_map[current_vbox]->unfold(); + } + } } } @@ -2181,6 +2275,10 @@ String EditorInspector::get_object_class() const { return object_class; } +void EditorInspector::set_auto_unfold_edited(bool p_enable) { + auto_unfold_edited = p_enable; +} + void EditorInspector::_bind_methods() { ClassDB::bind_method("_property_changed", &EditorInspector::_property_changed, DEFVAL(false)); @@ -2205,6 +2303,7 @@ void EditorInspector::_bind_methods() { ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "res"), PropertyInfo(Variant::STRING, "prop"))); ADD_SIGNAL(MethodInfo("object_id_selected", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("property_edited", PropertyInfo(Variant::STRING, "property"))); + ADD_SIGNAL(MethodInfo("property_toggled", PropertyInfo(Variant::STRING, "property"), PropertyInfo(Variant::BOOL, "checked"))); ADD_SIGNAL(MethodInfo("restart_requested")); } @@ -2236,6 +2335,7 @@ EditorInspector::EditorInspector() { set_process(true); property_focusable = -1; use_sub_inspector_bg = false; + auto_unfold_edited = false; get_v_scrollbar()->connect("value_changed", this, "_vscroll_changed"); update_scroll_request = -1; diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index dccbdb9a73..350debcb7b 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -37,6 +37,20 @@ class UndoRedo; +class EditorDefaultClassValueCache : public Object { + GDCLASS(EditorDefaultClassValueCache, Object) + + Map<StringName, Map<StringName, Variant> > default_values; + + static EditorDefaultClassValueCache *singleton; + +public: + static EditorDefaultClassValueCache *get_singleton(); + + Variant get_default_value(const StringName &p_class, const StringName &p_property); + EditorDefaultClassValueCache(); +}; + class EditorProperty : public Container { GDCLASS(EditorProperty, Container) @@ -152,6 +166,8 @@ public: void set_draw_top_bg(bool p_draw) { draw_top_bg = p_draw; } + bool can_revert_to_default() const { return can_revert; } + EditorProperty(); }; @@ -271,6 +287,7 @@ class EditorInspector : public ScrollContainer { bool read_only; bool keying; bool use_sub_inspector_bg; + bool auto_unfold_edited; float refresh_countdown; bool update_tree_pending; @@ -365,6 +382,7 @@ public: String get_object_class() const; void set_use_sub_inspector_bg(bool p_enable); + void set_auto_unfold_edited(bool p_enable); EditorInspector(); }; diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index d01543198a..e9ce2cb8ae 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -1061,6 +1061,9 @@ void EditorNode::_save_scene(String p_file, int idx) { set_current_version(editor_data.get_undo_redo().get_version()); else editor_data.set_edited_scene_version(0, idx); + + editor_folding.save_scene_folding(scene, p_file); + _update_title(); _update_scene_tabs(); } else { @@ -2907,6 +2910,8 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b _update_scene_tabs(); _add_to_recent_scenes(lpath); + editor_folding.load_scene_folding(new_scene, lpath); + prev_scene->set_disabled(previous_scenes.size() == 0); opening_prev = false; @@ -4544,6 +4549,19 @@ void EditorNode::_video_driver_selected(int p_which) { _update_video_driver_color(); } +void EditorNode::_resource_saved(RES p_resource, const String &p_path) { + if (EditorFileSystem::get_singleton()) { + EditorFileSystem::get_singleton()->update_file(p_path); + } + + singleton->editor_folding.save_resource_folding(p_resource, p_path); +} + +void EditorNode::_resource_loaded(RES p_resource, const String &p_path) { + + singleton->editor_folding.load_resource_folding(p_resource, p_path); +} + void EditorNode::_bind_methods() { ClassDB::bind_method("_menu_option", &EditorNode::_menu_option); @@ -4733,6 +4751,8 @@ EditorNode::EditorNode() { ResourceLoader::set_timestamp_on_load(true); ResourceSaver::set_timestamp_on_save(true); + default_value_cache = memnew(EditorDefaultClassValueCache); + { //register importers at the beginning, so dialogs are created with the right extensions Ref<ResourceImporterTexture> import_texture; import_texture.instance(); @@ -4844,6 +4864,7 @@ EditorNode::EditorNode() { EDITOR_DEF_RST("interface/scene_tabs/show_thumbnail_on_hover", true); EDITOR_DEF_RST("interface/inspector/capitalize_properties", true); EDITOR_DEF_RST("interface/inspector/disable_folding", false); + EDITOR_DEF_RST("interface/inspector/auto_unfold_edited", true); EDITOR_DEF("interface/inspector/horizontal_vector2_editing", false); EDITOR_DEF("interface/inspector/horizontal_vector_types_editing", true); EDITOR_DEF("interface/inspector/open_resources_in_current_inspector", true); @@ -4983,7 +5004,7 @@ EditorNode::EditorNode() { dock_select_rect_over = -1; dock_popup_selected = -1; for (int i = 0; i < DOCK_SLOT_MAX; i++) { - dock_slot[i]->set_custom_minimum_size(Size2(230, 220) * EDSCALE); + dock_slot[i]->set_custom_minimum_size(Size2(170, 0) * EDSCALE); dock_slot[i]->set_v_size_flags(Control::SIZE_EXPAND_FILL); dock_slot[i]->set_popup(dock_select_popup); dock_slot[i]->connect("pre_popup_pressed", this, "_dock_pre_popup", varray(i)); @@ -5499,8 +5520,8 @@ EditorNode::EditorNode() { right_r_vsplit->hide(); // Add some offsets to left_r and main hsplits to make LEFT_R and RIGHT_L docks wider than minsize - left_r_hsplit->set_split_offset(40 * EDSCALE); - main_hsplit->set_split_offset(-40 * EDSCALE); + left_r_hsplit->set_split_offset(70 * EDSCALE); + main_hsplit->set_split_offset(-70 * EDSCALE); // Define corresponding default layout @@ -5515,8 +5536,8 @@ EditorNode::EditorNode() { for (int i = 0; i < vsplits.size(); i++) default_layout->set_value(docks_section, "dock_split_" + itos(i + 1), 0); default_layout->set_value(docks_section, "dock_hsplit_1", 0); - default_layout->set_value(docks_section, "dock_hsplit_2", 40 * EDSCALE); - default_layout->set_value(docks_section, "dock_hsplit_3", -40 * EDSCALE); + default_layout->set_value(docks_section, "dock_hsplit_2", 70 * EDSCALE); + default_layout->set_value(docks_section, "dock_hsplit_3", -70 * EDSCALE); default_layout->set_value(docks_section, "dock_hsplit_4", 0); _update_layouts_menu(); @@ -5829,6 +5850,9 @@ EditorNode::EditorNode() { print_handler.userdata = this; add_print_handler(&print_handler); + ResourceSaver::set_save_callback(_resource_saved); + ResourceLoader::set_load_callback(_resource_loaded); + #ifdef OSX_ENABLED ED_SHORTCUT("editor/editor_2d", TTR("Open 2D Editor"), KEY_MASK_ALT | KEY_1); ED_SHORTCUT("editor/editor_3d", TTR("Open 3D Editor"), KEY_MASK_ALT | KEY_2); @@ -5857,6 +5881,7 @@ EditorNode::~EditorNode() { memdelete(editor_plugins_force_input_forwarding); memdelete(file_server); memdelete(progress_hb); + memdelete(default_value_cache); EditorSettings::destroy(); } diff --git a/editor/editor_node.h b/editor/editor_node.h index 0096748ed1..33af473de3 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -38,6 +38,7 @@ #include "editor/editor_about.h" #include "editor/editor_data.h" #include "editor/editor_export.h" +#include "editor/editor_folding.h" #include "editor/editor_inspector.h" #include "editor/editor_log.h" #include "editor/editor_name_dialog.h" @@ -271,6 +272,7 @@ private: Ref<Theme> theme; + EditorDefaultClassValueCache *default_value_cache; PopupMenu *recent_scenes; SceneTreeDock *scene_tree_dock; InspectorDock *inspector_dock; @@ -385,6 +387,7 @@ private: EditorSelection *editor_selection; ProjectExportDialog *project_export; EditorResourcePreview *resource_preview; + EditorFolding editor_folding; EditorFileServer *file_server; @@ -600,6 +603,9 @@ private: PrintHandlerList print_handler; static void _print_handler(void *p_this, const String &p_string, bool p_error); + static void _resource_saved(RES p_resource, const String &p_path); + static void _resource_loaded(RES p_resource, const String &p_path); + protected: void _notification(int p_what); static void _bind_methods(); @@ -690,6 +696,7 @@ public: void set_current_scene(int p_idx); static EditorData &get_editor_data() { return singleton->editor_data; } + static EditorFolding &get_editor_folding() { return singleton->editor_folding; } EditorHistory *get_editor_history() { return &editor_history; } static VSplitContainer *get_top_split() { return singleton->top_split; } diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp index b53767ba62..7c3e6dc386 100644 --- a/editor/editor_properties.cpp +++ b/editor/editor_properties.cpp @@ -1865,6 +1865,12 @@ void EditorPropertyNodePath::update_property() { Node *target_node = base_node->get_node(p); ERR_FAIL_COND(!target_node); + if (String(target_node->get_name()).find("@") != -1) { + assign->set_icon(Ref<Texture>()); + assign->set_text(p); + return; + } + assign->set_text(target_node->get_name()); assign->set_icon(EditorNode::get_singleton()->get_object_icon(target_node, "Node")); } diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index 1e97920f7e..34c273fbae 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -357,7 +357,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _initial_set("text_editor/theme/color_theme", "Adaptive"); hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Adaptive,Default,Custom"); - _initial_set("text_editor/theme/line_spacing", 4); + _initial_set("text_editor/theme/line_spacing", 6); _initial_set("text_editor/theme/selection_color", Color::html("40808080")); _load_default_text_editor_theme(); @@ -410,7 +410,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _initial_set("text_editor/completion/add_type_hints", false); _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); - _initial_set("docks/scene_tree/draw_relationship_lines", false); + _initial_set("docks/scene_tree/draw_relationship_lines", true); _initial_set("docks/scene_tree/relationship_line_color", Color::html("464646")); _initial_set("editors/grid_map/pick_distance", 5000.0); diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp index 26bc43c540..2136211faa 100644 --- a/editor/filesystem_dock.cpp +++ b/editor/filesystem_dock.cpp @@ -225,7 +225,7 @@ void FileSystemDock::_update_tree(const Vector<String> p_uncollapsed_paths, bool updating_tree = false; } -void FileSystemDock::_update_display_mode() { +void FileSystemDock::_update_display_mode(bool p_force) { // Compute the new display mode DisplayMode new_display_mode; if (display_mode_setting == DISPLAY_MODE_SETTING_TREE_ONLY) { @@ -234,7 +234,7 @@ void FileSystemDock::_update_display_mode() { new_display_mode = DISPLAY_MODE_SPLIT; } - if (new_display_mode != display_mode || old_display_mode_setting != display_mode_setting) { + if (p_force || new_display_mode != display_mode || old_display_mode_setting != display_mode_setting) { display_mode = new_display_mode; old_display_mode_setting = display_mode_setting; button_toggle_display_mode->set_pressed(display_mode_setting == DISPLAY_MODE_SETTING_SPLIT ? true : false); @@ -352,6 +352,11 @@ void FileSystemDock::_notification(int p_what) { tree->set_drop_mode_flags(0); } break; + case NOTIFICATION_THEME_CHANGED: { + if (is_visible_in_tree()) { + _update_display_mode(true); + } + } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { // Update icons String ei = "EditorIcons"; @@ -360,6 +365,11 @@ void FileSystemDock::_notification(int p_what) { button_tree->set_icon(get_icon("Filesystem", ei)); button_hist_next->set_icon(get_icon("Forward", ei)); button_hist_prev->set_icon(get_icon("Back", ei)); + if (button_file_list_display_mode->is_pressed()) { + button_file_list_display_mode->set_icon(get_icon("FileThumbnail", "EditorIcons")); + } else { + button_file_list_display_mode->set_icon(get_icon("FileList", "EditorIcons")); + } tree_search_box->set_right_icon(get_icon("Search", ei)); tree_search_box->set_clear_button_enabled(true); diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h index d964515572..2aa79b1ddd 100644 --- a/editor/filesystem_dock.h +++ b/editor/filesystem_dock.h @@ -268,7 +268,7 @@ private: void _file_list_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Ref<Texture> &p_small_preview, const Variant &p_udata); void _tree_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Ref<Texture> &p_small_preview, const Variant &p_udata); - void _update_display_mode(); + void _update_display_mode(bool p_force = false); Vector<String> _tree_get_selected(bool remove_self_inclusion = true); diff --git a/editor/import_dock.cpp b/editor/import_dock.cpp index 31eb193461..2e68609a56 100644 --- a/editor/import_dock.cpp +++ b/editor/import_dock.cpp @@ -38,11 +38,17 @@ public: List<PropertyInfo> properties; Ref<ResourceImporter> importer; Vector<String> paths; + Set<StringName> checked; + bool checking; bool _set(const StringName &p_name, const Variant &p_value) { if (values.has(p_name)) { values[p_name] = p_value; + if (checking) { + checked.insert(p_name); + _change_notify(String(p_name).utf8().get_data()); + } return true; } @@ -63,13 +69,24 @@ public: for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { if (!importer->get_option_visibility(E->get().name, values)) continue; - p_list->push_back(E->get()); + PropertyInfo pi = E->get(); + if (checking) { + pi.usage |= PROPERTY_USAGE_CHECKABLE; + if (checked.has(E->get().name)) { + pi.usage |= PROPERTY_USAGE_CHECKED; + } + } + p_list->push_back(pi); } } void update() { _change_notify(); } + + ImportDockParameters() { + checking = false; + } }; void ImportDock::set_edit_path(const String &p_path) { @@ -125,6 +142,8 @@ void ImportDock::_update_options(const Ref<ConfigFile> &p_config) { params->properties.clear(); params->values.clear(); + params->checking = false; + params->checked.clear(); for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) { @@ -205,6 +224,8 @@ void ImportDock::set_edit_multiple_paths(const Vector<String> &p_paths) { params->properties.clear(); params->values.clear(); + params->checking = true; + params->checked.clear(); for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) { @@ -360,11 +381,21 @@ void ImportDock::_reimport() { Error err = config->load(params->paths[i] + ".import"); ERR_CONTINUE(err != OK); - config->set_value("remap", "importer", params->importer->get_importer_name()); - config->erase_section("params"); + if (params->checking) { + //update only what edited (checkboxes) + for (List<PropertyInfo>::Element *E = params->properties.front(); E; E = E->next()) { + if (params->checked.has(E->get().name)) { + config->set_value("params", E->get().name, params->values[E->get().name]); + } + } + } else { + //override entirely + config->set_value("remap", "importer", params->importer->get_importer_name()); + config->erase_section("params"); - for (List<PropertyInfo>::Element *E = params->properties.front(); E; E = E->next()) { - config->set_value("params", E->get().name, params->values[E->get().name]); + for (List<PropertyInfo>::Element *E = params->properties.front(); E; E = E->next()) { + config->set_value("params", E->get().name, params->values[E->get().name]); + } } config->save(params->paths[i] + ".import"); @@ -388,11 +419,20 @@ void ImportDock::_notification(int p_what) { } break; } } + +void ImportDock::_property_toggled(const StringName &p_prop, bool p_checked) { + if (p_checked) { + params->checked.insert(p_prop); + } else { + params->checked.erase(p_prop); + } +} void ImportDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_reimport"), &ImportDock::_reimport); ClassDB::bind_method(D_METHOD("_preset_selected"), &ImportDock::_preset_selected); ClassDB::bind_method(D_METHOD("_importer_selected"), &ImportDock::_importer_selected); + ClassDB::bind_method(D_METHOD("_property_toggled"), &ImportDock::_property_toggled); } void ImportDock::initialize_import_options() const { @@ -423,6 +463,7 @@ ImportDock::ImportDock() { import_opts = memnew(EditorInspector); add_child(import_opts); import_opts->set_v_size_flags(SIZE_EXPAND_FILL); + import_opts->connect("property_toggled", this, "_property_toggled"); hb = memnew(HBoxContainer); add_child(hb); diff --git a/editor/import_dock.h b/editor/import_dock.h index 41c7298d9a..632fd39700 100644 --- a/editor/import_dock.h +++ b/editor/import_dock.h @@ -60,6 +60,7 @@ class ImportDock : public VBoxContainer { void _importer_selected(int i_idx); void _update_options(const Ref<ConfigFile> &p_config = Ref<ConfigFile>()); + void _property_toggled(const StringName &p_prop, bool p_checked); void _reimport(); enum { diff --git a/editor/inspector_dock.cpp b/editor/inspector_dock.cpp index 750fca2852..2a8885c0a4 100644 --- a/editor/inspector_dock.cpp +++ b/editor/inspector_dock.cpp @@ -593,6 +593,7 @@ InspectorDock::InspectorDock(EditorNode *p_editor, EditorData &p_editor_data) { inspector->set_undo_redo(&editor_data->get_undo_redo()); inspector->set_use_filter(true); // TODO: check me + inspector->set_auto_unfold_edited(bool(EDITOR_GET("interface/inspector/auto_unfold_edited"))); inspector->connect("resource_selected", this, "_resource_selected"); inspector->connect("property_keyed", this, "_property_keyed"); diff --git a/editor/plugins/baked_lightmap_editor_plugin.cpp b/editor/plugins/baked_lightmap_editor_plugin.cpp index e65a697857..40e3bb5be2 100644 --- a/editor/plugins/baked_lightmap_editor_plugin.cpp +++ b/editor/plugins/baked_lightmap_editor_plugin.cpp @@ -108,7 +108,7 @@ void BakedLightmapEditorPlugin::_bind_methods() { BakedLightmapEditorPlugin::BakedLightmapEditorPlugin(EditorNode *p_node) { editor = p_node; - bake = memnew(Button); + bake = memnew(ToolButton); bake->set_icon(editor->get_gui_base()->get_icon("Bake", "EditorIcons")); bake->set_text(TTR("Bake Lightmaps")); bake->hide(); diff --git a/editor/plugins/baked_lightmap_editor_plugin.h b/editor/plugins/baked_lightmap_editor_plugin.h index a32b573851..8d3b5b1dd6 100644 --- a/editor/plugins/baked_lightmap_editor_plugin.h +++ b/editor/plugins/baked_lightmap_editor_plugin.h @@ -42,7 +42,7 @@ class BakedLightmapEditorPlugin : public EditorPlugin { BakedLightmap *lightmap; - Button *bake; + ToolButton *bake; EditorNode *editor; static EditorProgress *tmp_progress; diff --git a/editor/plugins/gi_probe_editor_plugin.cpp b/editor/plugins/gi_probe_editor_plugin.cpp index 06da64b181..5fc5cad1ef 100644 --- a/editor/plugins/gi_probe_editor_plugin.cpp +++ b/editor/plugins/gi_probe_editor_plugin.cpp @@ -90,7 +90,7 @@ void GIProbeEditorPlugin::_bind_methods() { GIProbeEditorPlugin::GIProbeEditorPlugin(EditorNode *p_node) { editor = p_node; - bake = memnew(Button); + bake = memnew(ToolButton); bake->set_icon(editor->get_gui_base()->get_icon("Bake", "EditorIcons")); bake->set_text(TTR("Bake GI Probe")); bake->hide(); diff --git a/editor/plugins/gi_probe_editor_plugin.h b/editor/plugins/gi_probe_editor_plugin.h index 017e9bd743..1b3b63f227 100644 --- a/editor/plugins/gi_probe_editor_plugin.h +++ b/editor/plugins/gi_probe_editor_plugin.h @@ -42,7 +42,7 @@ class GIProbeEditorPlugin : public EditorPlugin { GIProbe *gi_probe; - Button *bake; + ToolButton *bake; EditorNode *editor; static EditorProgress *tmp_progress; diff --git a/editor/plugins/item_list_editor_plugin.cpp b/editor/plugins/item_list_editor_plugin.cpp index 186e66f980..8df40232b0 100644 --- a/editor/plugins/item_list_editor_plugin.cpp +++ b/editor/plugins/item_list_editor_plugin.cpp @@ -350,8 +350,6 @@ ItemListEditor::ItemListEditor() { selected_idx = -1; - add_child(memnew(VSeparator)); - toolbar_button = memnew(ToolButton); toolbar_button->set_text(TTR("Items")); add_child(toolbar_button); diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index 080d3ff894..ac69cc0df1 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -490,7 +490,7 @@ void ScriptEditor::_open_recent_script(int p_idx) { edit(text_file, true); return; } - // if it's a path then its most likely a deleted file not help + // if it's a path then it's most likely a deleted file not help } else if (path.find("::") != -1) { // built-in script Ref<Script> script = ResourceLoader::load(path); @@ -1363,7 +1363,9 @@ void ScriptEditor::_notification(int p_what) { if (is_visible()) { find_in_files_button->show(); } else { - find_in_files->hide(); + if (find_in_files->is_visible_in_tree()) { + editor->hide_bottom_panel(); + } find_in_files_button->hide(); } @@ -2806,8 +2808,7 @@ void ScriptEditor::_start_find_in_files(bool with_replace) { find_in_files->set_with_replace(with_replace); find_in_files->start_search(); - find_in_files_button->set_pressed(true); - find_in_files->show(); + editor->make_bottom_panel_item_visible(find_in_files); } void ScriptEditor::_on_find_in_files_modified_files(PoolStringArray paths) { @@ -3174,7 +3175,6 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { add_child(find_in_files_dialog); find_in_files = memnew(FindInFilesPanel); find_in_files_button = editor->add_bottom_panel_item(TTR("Search Results"), find_in_files); - find_in_files_button->set_tooltip(TTR("Search in files")); find_in_files->set_custom_minimum_size(Size2(0, 200) * EDSCALE); find_in_files->connect(FindInFilesPanel::SIGNAL_RESULT_SELECTED, this, "_on_find_in_files_result_selected"); find_in_files->connect(FindInFilesPanel::SIGNAL_FILES_MODIFIED, this, "_on_find_in_files_modified_files"); diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp index 362b8543d4..27f5910d94 100644 --- a/editor/plugins/script_text_editor.cpp +++ b/editor/plugins/script_text_editor.cpp @@ -179,7 +179,7 @@ void ScriptTextEditor::_load_theme_settings() { text_edit->add_color_override("search_result_border_color", search_result_border_color); text_edit->add_color_override("symbol_color", symbol_color); - text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 4)); + text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 6)); colors_cache.symbol_color = symbol_color; colors_cache.keyword_color = keyword_color; diff --git a/editor/plugins/spatial_editor_plugin.cpp b/editor/plugins/spatial_editor_plugin.cpp index b0d405daab..ab89d170da 100644 --- a/editor/plugins/spatial_editor_plugin.cpp +++ b/editor/plugins/spatial_editor_plugin.cpp @@ -952,8 +952,10 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { if (b->is_pressed()) { int mod = _get_key_modifier(b); - if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) { - set_freelook_active(true); + if (!orthogonal) { + if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) { + set_freelook_active(true); + } } } else { set_freelook_active(false); @@ -1134,7 +1136,7 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { } if (clicked) { _select_clicked(clicked_wants_append, true); - //clickd processing was deferred + // Processing was deferred. clicked = 0; } @@ -1241,7 +1243,7 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { if (!clicked_includes_current) { _select_clicked(clicked_wants_append, true); - //clickd processing was deferred + // Processing was deferred. } _compute_edit(_edit.mouse_pos); @@ -1339,7 +1341,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { List<Node *> &selection = editor_selection->get_selected_node_list(); - bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW + // Disable local transformation for TRANSFORM_VIEW + bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); float snap = 0; if (_edit.snap || spatial_editor->is_snap_enabled()) { @@ -1468,7 +1471,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { List<Node *> &selection = editor_selection->get_selected_node_list(); - bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW + // Disable local transformation for TRANSFORM_VIEW + bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); float snap = 0; if (_edit.snap || spatial_editor->is_snap_enabled()) { @@ -1643,6 +1647,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { nav_mode = NAVIGATION_ZOOM; } else if (freelook_active) { nav_mode = NAVIGATION_LOOK; + } else if (orthogonal) { + nav_mode = NAVIGATION_PAN; } } else if (m->get_button_mask() & BUTTON_MASK_MIDDLE) { @@ -1793,7 +1799,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) { _menu_option(VIEW_CENTER_TO_SELECTION); } - if (ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) { + // Orthgonal mode doesn't work in freelook. + if (!freelook_active && ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) { _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL); _update_name(); } @@ -1823,7 +1830,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { set_message(TTR("Animation Key Inserted.")); } - if (ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) { + // Freelook doesn't work in orthogonal mode. + if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) { set_freelook_active(!is_freelook_active()); } else if (k->get_scancode() == KEY_ESCAPE) { @@ -1911,37 +1919,38 @@ void SpatialEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, con void SpatialEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) { - // Freelook only works properly in perspective. - // It could technically work in ortho, but it's terrible for a user due to FOV being a fixed width. - if (!orthogonal) { - real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity"); - real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); - bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y-axis"); - - // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag". - Transform prev_camera_transform = to_camera_transform(cursor); + if (orthogonal) { + _nav_pan(p_event, p_relative); + return; + } - if (invert_y_axis) { - cursor.x_rot -= p_relative.y * radians_per_pixel; - } else { - cursor.x_rot += p_relative.y * radians_per_pixel; - } - cursor.y_rot += p_relative.x * radians_per_pixel; - if (cursor.x_rot > Math_PI / 2.0) - cursor.x_rot = Math_PI / 2.0; - if (cursor.x_rot < -Math_PI / 2.0) - cursor.x_rot = -Math_PI / 2.0; + real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity"); + real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); + bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y-axis"); - // Look is like the opposite of Orbit: the focus point rotates around the camera - Transform camera_transform = to_camera_transform(cursor); - Vector3 pos = camera_transform.xform(Vector3(0, 0, 0)); - Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0)); - Vector3 diff = prev_pos - pos; - cursor.pos += diff; + // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag". + Transform prev_camera_transform = to_camera_transform(cursor); - name = ""; - _update_name(); + if (invert_y_axis) { + cursor.x_rot -= p_relative.y * radians_per_pixel; + } else { + cursor.x_rot += p_relative.y * radians_per_pixel; } + cursor.y_rot += p_relative.x * radians_per_pixel; + if (cursor.x_rot > Math_PI / 2.0) + cursor.x_rot = Math_PI / 2.0; + if (cursor.x_rot < -Math_PI / 2.0) + cursor.x_rot = -Math_PI / 2.0; + + // Look is like the opposite of Orbit: the focus point rotates around the camera + Transform camera_transform = to_camera_transform(cursor); + Vector3 pos = camera_transform.xform(Vector3(0, 0, 0)); + Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0)); + Vector3 diff = prev_pos - pos; + cursor.pos += diff; + + name = ""; + _update_name(); } void SpatialEditorViewport::set_freelook_active(bool active_now) { @@ -2535,8 +2544,14 @@ void SpatialEditorViewport::_menu_option(int p_option) { if (!se) continue; - Transform xform = camera_transform; - xform.scale_basis(sp->get_scale()); + Transform xform; + if (orthogonal) { + xform = sp->get_global_transform(); + xform.basis.set_euler(camera_transform.basis.get_euler()); + } else { + xform = camera_transform; + xform.scale_basis(sp->get_scale()); + } undo_redo->add_do_method(sp, "set_global_transform", xform); undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform()); @@ -3489,7 +3504,7 @@ SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, Ed ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), KEY_SHIFT); preview_camera = memnew(CheckBox); - preview_camera->set_position(Point2(10 * EDSCALE, 15 * EDSCALE + view_menu->get_size().height)); + preview_camera->set_position(Point2(10, 38) * EDSCALE); // Below the 'view_menu' MenuButton. preview_camera->set_text(TTR("Preview")); surface->add_child(preview_camera); preview_camera->hide(); diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp index 30246147c2..40781908fd 100644 --- a/editor/plugins/sprite_frames_editor_plugin.cpp +++ b/editor/plugins/sprite_frames_editor_plugin.cpp @@ -548,7 +548,6 @@ void SpriteFramesEditor::edit(SpriteFrames *p_frames) { } else { hide(); - //set_physics_process(false); } } @@ -816,16 +815,26 @@ SpriteFramesEditor::SpriteFramesEditor() { void SpriteFramesEditorPlugin::edit(Object *p_object) { frames_editor->set_undo_redo(&get_undo_redo()); - SpriteFrames *s = Object::cast_to<SpriteFrames>(p_object); - if (!s) - return; + + SpriteFrames *s; + AnimatedSprite *animated_sprite = Object::cast_to<AnimatedSprite>(p_object); + if (animated_sprite) { + s = *animated_sprite->get_sprite_frames(); + } else { + s = Object::cast_to<SpriteFrames>(p_object); + } frames_editor->edit(s); } bool SpriteFramesEditorPlugin::handles(Object *p_object) const { - return p_object->is_class("SpriteFrames"); + AnimatedSprite *animated_sprite = Object::cast_to<AnimatedSprite>(p_object); + if (animated_sprite && *animated_sprite->get_sprite_frames()) { + return true; + } else { + return p_object->is_class("SpriteFrames"); + } } void SpriteFramesEditorPlugin::make_visible(bool p_visible) { @@ -833,14 +842,11 @@ void SpriteFramesEditorPlugin::make_visible(bool p_visible) { if (p_visible) { button->show(); editor->make_bottom_panel_item_visible(frames_editor); - //frames_editor->set_process(true); } else { button->hide(); if (frames_editor->is_visible_in_tree()) editor->hide_bottom_panel(); - - //frames_editor->set_process(false); } } diff --git a/editor/plugins/text_editor.cpp b/editor/plugins/text_editor.cpp index 4ff7046a35..1a43b16f3e 100644 --- a/editor/plugins/text_editor.cpp +++ b/editor/plugins/text_editor.cpp @@ -131,7 +131,7 @@ void TextEditor::_load_theme_settings() { text_edit->add_color_override("search_result_border_color", search_result_border_color); text_edit->add_color_override("symbol_color", symbol_color); - text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 4)); + text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 6)); colors_cache.font_color = text_color; colors_cache.symbol_color = symbol_color; diff --git a/editor/plugins/tile_set_editor_plugin.cpp b/editor/plugins/tile_set_editor_plugin.cpp index 9988d82fb8..7936b2a1e7 100644 --- a/editor/plugins/tile_set_editor_plugin.cpp +++ b/editor/plugins/tile_set_editor_plugin.cpp @@ -483,6 +483,11 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { //--------------- helper = memnew(TilesetEditorContext(this)); tile_names_opacity = 0; + + // config scale + max_scale = 10.0f; + min_scale = 0.1f; + scale_ratio = 1.2f; } TileSetEditor::~TileSetEditor() { @@ -972,6 +977,15 @@ void TileSetEditor::_on_workspace_input(const Ref<InputEvent> &p_ie) { } } } + + // Mouse Wheel Event + const int _mouse_button_index = mb->get_button_index(); + if (_mouse_button_index == BUTTON_WHEEL_UP && mb->get_control()) { + _zoom_in(); + + } else if (_mouse_button_index == BUTTON_WHEEL_DOWN && mb->get_control()) { + _zoom_out(); + } } // Drag Middle Mouse if (mm.is_valid()) { @@ -1448,23 +1462,11 @@ void TileSetEditor::_on_tool_clicked(int p_tool) { } } } else if (p_tool == ZOOM_OUT) { - float scale = workspace->get_scale().x; - if (scale > 0.1) { - scale /= 2; - workspace->set_scale(Vector2(scale, scale)); - workspace_container->set_custom_minimum_size(workspace->get_rect().size * scale); - workspace_overlay->set_custom_minimum_size(workspace->get_rect().size * scale); - } + _zoom_out(); } else if (p_tool == ZOOM_1) { - workspace->set_scale(Vector2(1, 1)); - workspace_container->set_custom_minimum_size(workspace->get_rect().size); - workspace_overlay->set_custom_minimum_size(workspace->get_rect().size); + _reset_zoom(); } else if (p_tool == ZOOM_IN) { - float scale = workspace->get_scale().x; - scale *= 2; - workspace->set_scale(Vector2(scale, scale)); - workspace_container->set_custom_minimum_size(workspace->get_rect().size * scale); - workspace_overlay->set_custom_minimum_size(workspace->get_rect().size * scale); + _zoom_in(); } else if (p_tool == TOOL_SELECT) { if (creating_shape) { // Cancel Creation @@ -1503,6 +1505,31 @@ void TileSetEditor::_set_snap_sep(Vector2 p_val) { workspace->update(); } +void TileSetEditor::_zoom_in() { + float scale = workspace->get_scale().x; + if (scale < max_scale) { + scale *= scale_ratio; + workspace->set_scale(Vector2(scale, scale)); + workspace_container->set_custom_minimum_size(workspace->get_rect().size * scale); + workspace_overlay->set_custom_minimum_size(workspace->get_rect().size * scale); + } +} +void TileSetEditor::_zoom_out() { + + float scale = workspace->get_scale().x; + if (scale > min_scale) { + scale /= scale_ratio; + workspace->set_scale(Vector2(scale, scale)); + workspace_container->set_custom_minimum_size(workspace->get_rect().size * scale); + workspace_overlay->set_custom_minimum_size(workspace->get_rect().size * scale); + } +} +void TileSetEditor::_reset_zoom() { + workspace->set_scale(Vector2(1, 1)); + workspace_container->set_custom_minimum_size(workspace->get_rect().size); + workspace_overlay->set_custom_minimum_size(workspace->get_rect().size); +} + void TileSetEditor::draw_highlight_current_tile() { if (get_current_tile() >= 0) { diff --git a/editor/plugins/tile_set_editor_plugin.h b/editor/plugins/tile_set_editor_plugin.h index 23bf68b90f..bd8a2ddb98 100644 --- a/editor/plugins/tile_set_editor_plugin.h +++ b/editor/plugins/tile_set_editor_plugin.h @@ -141,6 +141,10 @@ class TileSetEditor : public Control { EditMode edit_mode; int current_tile; + float max_scale; + float min_scale; + float scale_ratio; + void update_texture_list(); void update_texture_list_icon(); @@ -178,6 +182,10 @@ private: void _set_snap_off(Vector2 p_val); void _set_snap_sep(Vector2 p_val); + void _zoom_in(); + void _zoom_out(); + void _reset_zoom(); + void draw_highlight_current_tile(); void draw_highlight_subtile(Vector2 coord, const Vector<Vector2> &other_highlighted = Vector<Vector2>()); void draw_tile_subdivision(int p_id, Color p_color) const; diff --git a/editor/progress_dialog.cpp b/editor/progress_dialog.cpp index 29a780961e..4a98aa411d 100644 --- a/editor/progress_dialog.cpp +++ b/editor/progress_dialog.cpp @@ -39,7 +39,7 @@ void BackgroundProgress::_add_task(const String &p_task, const String &p_label, _THREAD_SAFE_METHOD_ ERR_FAIL_COND(tasks.has(p_task)); - Task t; + BackgroundProgress::Task t; t.hb = memnew(HBoxContainer); Label *l = memnew(Label); l->set_text(p_label + " "); @@ -112,7 +112,7 @@ void BackgroundProgress::add_task(const String &p_task, const String &p_label, i void BackgroundProgress::task_step(const String &p_task, int p_step) { //this code is weird, but it prevents deadlock. - bool no_updates; + bool no_updates = true; { _THREAD_SAFE_METHOD_ no_updates = updates.empty(); @@ -167,7 +167,7 @@ void ProgressDialog::_popup() { void ProgressDialog::add_task(const String &p_task, const String &p_label, int p_steps, bool p_can_cancel) { ERR_FAIL_COND(tasks.has(p_task)); - Task t; + ProgressDialog::Task t; t.vb = memnew(VBoxContainer); VBoxContainer *vb2 = memnew(VBoxContainer); t.vb->add_margin_child(p_label, vb2); diff --git a/editor/project_export.cpp b/editor/project_export.cpp index 3ec49e187f..d2dccdb425 100644 --- a/editor/project_export.cpp +++ b/editor/project_export.cpp @@ -50,6 +50,7 @@ void ProjectExportDialog::_notification(int p_what) { switch (p_what) { case NOTIFICATION_READY: { + duplicate_preset->set_icon(get_icon("Duplicate", "EditorIcons")); delete_preset->set_icon(get_icon("Remove", "EditorIcons")); connect("confirmed", this, "_export_pck_zip"); custom_feature_display->get_parent_control()->add_style_override("panel", get_stylebox("bg", "Tree")); @@ -58,6 +59,7 @@ void ProjectExportDialog::_notification(int p_what) { EditorSettings::get_singleton()->set("interface/dialogs/export_bounds", get_rect()); } break; case NOTIFICATION_THEME_CHANGED: { + duplicate_preset->set_icon(get_icon("Duplicate", "EditorIcons")); delete_preset->set_icon(get_icon("Remove", "EditorIcons")); Control *panel = custom_feature_display->get_parent_control(); if (panel) @@ -171,6 +173,7 @@ void ProjectExportDialog::_edit_preset(int p_index) { runnable->set_disabled(true); parameters->edit(NULL); presets->unselect_all(); + duplicate_preset->set_disabled(true); delete_preset->set_disabled(true); sections->hide(); patches->clear(); @@ -188,6 +191,7 @@ void ProjectExportDialog::_edit_preset(int p_index) { sections->show(); name->set_editable(true); + duplicate_preset->set_disabled(false); delete_preset->set_disabled(false); name->set_text(current->get_name()); runnable->set_disabled(false); @@ -428,6 +432,61 @@ void ProjectExportDialog::_name_changed(const String &p_string) { _update_presets(); } +void ProjectExportDialog::_duplicate_preset() { + + Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(presets->get_current()); + if (current.is_null()) + return; + + Ref<EditorExportPreset> preset = current->get_platform()->create_preset(); + ERR_FAIL_COND(!preset.is_valid()); + + String name = current->get_name() + "" + itos(1); + bool make_runnable = true; + int attempt = 2; + while (true) { + + bool valid = true; + + for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + Ref<EditorExportPreset> p = EditorExport::get_singleton()->get_export_preset(i); + if (p->get_platform() == preset->get_platform() && p->is_runnable()) { + make_runnable = false; + } + if (p->get_name() == name) { + valid = false; + break; + } + } + + if (valid) + break; + + attempt++; + name = current->get_name() + " " + itos(attempt); + } + + preset->set_name(name); + if (make_runnable) + preset->set_runnable(make_runnable); + preset->set_export_filter(current->get_export_filter()); + preset->set_include_filter(current->get_include_filter()); + preset->set_exclude_filter(current->get_exclude_filter()); + Vector<String> list = current->get_patches(); + for (int i = 0; i < list.size(); i++) { + preset->add_patch(list[i]); + } + preset->set_custom_features(current->get_custom_features()); + + for (const List<PropertyInfo>::Element *E = current->get_properties().front(); E; E = E->next()) { + preset->set(E->get().name, current->get(E->get().name)); + } + + EditorExport::get_singleton()->add_export_preset(preset); + _update_presets(); + _edit_preset(EditorExport::get_singleton()->get_export_preset_count() - 1); +} + void ProjectExportDialog::_delete_preset() { Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(presets->get_current()); @@ -745,12 +804,16 @@ void ProjectExportDialog::_export_project() { export_project->set_access(FileDialog::ACCESS_FILESYSTEM); export_project->clear_filters(); - String extension = platform->get_binary_extension(current); - if (extension != String()) { - export_project->add_filter("*." + extension + " ; " + platform->get_name() + " Export"); - export_project->set_current_file(default_filename + "." + extension); + if (current->get_export_path() != "") { + export_project->set_current_path(current->get_export_path()); } else { - export_project->set_current_file(default_filename); + String extension = platform->get_binary_extension(current); + if (extension != String()) { + export_project->add_filter("*." + extension + " ; " + platform->get_name() + " Export"); + export_project->set_current_file(default_filename + "." + extension); + } else { + export_project->set_current_file(default_filename); + } } // Ensure that signal is connected if previous attempt left it disconnected with _validate_export_path @@ -772,6 +835,7 @@ void ProjectExportDialog::_export_project_to_path(const String &p_path) { ERR_FAIL_COND(current.is_null()); Ref<EditorExportPlatform> platform = current->get_platform(); ERR_FAIL_COND(platform.is_null()); + current->set_export_path(p_path); Error err = platform->export_project(current, export_debug->is_pressed(), p_path, 0); if (err != OK) { @@ -789,6 +853,7 @@ void ProjectExportDialog::_bind_methods() { ClassDB::bind_method("_update_parameters", &ProjectExportDialog::_update_parameters); ClassDB::bind_method("_runnable_pressed", &ProjectExportDialog::_runnable_pressed); ClassDB::bind_method("_name_changed", &ProjectExportDialog::_name_changed); + ClassDB::bind_method("_duplicate_preset", &ProjectExportDialog::_duplicate_preset); ClassDB::bind_method("_delete_preset", &ProjectExportDialog::_delete_preset); ClassDB::bind_method("_delete_preset_confirm", &ProjectExportDialog::_delete_preset_confirm); ClassDB::bind_method("get_drag_data_fw", &ProjectExportDialog::get_drag_data_fw); @@ -842,6 +907,9 @@ ProjectExportDialog::ProjectExportDialog() { presets->set_drag_forwarding(this); mc->add_child(presets); presets->connect("item_selected", this, "_edit_preset"); + duplicate_preset = memnew(ToolButton); + preset_hb->add_child(duplicate_preset); + duplicate_preset->connect("pressed", this, "_duplicate_preset"); delete_preset = memnew(ToolButton); preset_hb->add_child(delete_preset); delete_preset->connect("pressed", this, "_delete_preset"); @@ -949,6 +1017,7 @@ ProjectExportDialog::ProjectExportDialog() { //disable by default name->set_editable(false); runnable->set_disabled(true); + duplicate_preset->set_disabled(true); delete_preset->set_disabled(true); sections->hide(); parameters->edit(NULL); diff --git a/editor/project_export.h b/editor/project_export.h index 552c6d7faf..a4bca843a8 100644 --- a/editor/project_export.h +++ b/editor/project_export.h @@ -61,6 +61,7 @@ private: TabContainer *sections; MenuButton *add_preset; + Button *duplicate_preset; Button *delete_preset; ItemList *presets; @@ -108,6 +109,7 @@ private: void _name_changed(const String &p_string); void _add_preset(int p_platform); void _edit_preset(int p_index); + void _duplicate_preset(); void _delete_preset(); void _delete_preset_confirm(); diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index 45c20121da..fe438236c9 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -53,6 +53,13 @@ void SceneTreeDock::_nodes_drag_begin() { } } +void SceneTreeDock::_quick_open() { + Vector<String> files = quick_open->get_selected_files(); + for (int i = 0; i < files.size(); i++) { + instance(files[i]); + } +} + void SceneTreeDock::_input(Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; @@ -319,16 +326,8 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { break; } - file->set_mode(EditorFileDialog::MODE_OPEN_FILE); - List<String> extensions; - ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions); - file->clear_filters(); - for (int i = 0; i < extensions.size(); i++) { - - file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); - } - - file->popup_centered_ratio(); + quick_open->popup_dialog("PackedScene", true); + quick_open->set_title(TTR("Instance Child Scene")); } break; case TOOL_REPLACE: { @@ -359,15 +358,12 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { ScriptLanguage *l = ScriptServer::get_language(i); if (l->get_type() == existing->get_class()) { String name = l->get_global_class_name(existing->get_path()); - if (ScriptServer::is_global_class(name)) { - if (EDITOR_GET("interface/editors/derive_script_globals_by_name").operator bool()) { - inherits = editor->get_editor_data().script_class_get_base(name); - } else if (l->can_inherit_from_file()) { - inherits = "\"" + existing->get_path() + "\""; - } - } else { + if (ScriptServer::is_global_class(name) && EDITOR_GET("interface/editors/derive_script_globals_by_name").operator bool()) { + inherits = name; + } else if (l->can_inherit_from_file()) { inherits = "\"" + existing->get_path() + "\""; } + break; } } } @@ -1307,6 +1303,13 @@ bool SceneTreeDock::_validate_no_foreign() { return false; } + // When edited_scene inherits from another one the root Node will be the parent Scene, + // we don't want to consider that Node a foreign one otherwise we would not be able to + // delete it + if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene == E->get()) { + continue; + } + if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get())) >= 0) { accept->set_text(TTR("Can't operate on nodes the current scene inherits from!")); @@ -1497,6 +1500,7 @@ void SceneTreeDock::_script_created(Ref<Script> p_script) { editor_data->get_undo_redo().commit_action(); editor->push_item(p_script.operator->()); + _update_script_button(); } void SceneTreeDock::_toggle_editable_children() { @@ -1612,17 +1616,17 @@ void SceneTreeDock::_delete_confirm() { void SceneTreeDock::_update_script_button() { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 1) { - button_create_script->show(); Node *n = EditorNode::get_singleton()->get_editor_selection()->get_selected_node_list()[0]; if (n->get_script().is_null()) { - button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); - button_create_script->set_tooltip(TTR("Attach a new or existing script for the selected node.")); + button_create_script->show(); + button_clear_script->hide(); } else { - button_create_script->set_icon(get_icon("ScriptExtend", "EditorIcons")); - button_create_script->set_tooltip(TTR("Extend the selected node's script with a new or existing script.")); + button_create_script->hide(); + button_clear_script->show(); } } else { - button_create_script->hide(); + button_create_script->show(); + button_clear_script->hide(); } } @@ -2067,9 +2071,12 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { existing_script = selected->get_script(); } - menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); + if (!existing_script.is_valid()) { + menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); + } if (selection.size() > 1 || existing_script.is_valid()) { menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT); + menu->add_icon_shortcut(get_icon("ScriptExtend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/extend_script"), TOOL_ATTACH_SCRIPT); } menu->add_separator(); @@ -2296,6 +2303,7 @@ void SceneTreeDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_new_scene_from"), &SceneTreeDock::_new_scene_from); ClassDB::bind_method(D_METHOD("_nodes_dragged"), &SceneTreeDock::_nodes_dragged); ClassDB::bind_method(D_METHOD("_files_dropped"), &SceneTreeDock::_files_dropped); + ClassDB::bind_method(D_METHOD("_quick_open"), &SceneTreeDock::_quick_open); ClassDB::bind_method(D_METHOD("_script_dropped"), &SceneTreeDock::_script_dropped); ClassDB::bind_method(D_METHOD("_tree_rmb"), &SceneTreeDock::_tree_rmb); ClassDB::bind_method(D_METHOD("_filter_changed"), &SceneTreeDock::_filter_changed); @@ -2332,6 +2340,7 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel ED_SHORTCUT("scene_tree/instance_scene", TTR("Instance Child Scene")); ED_SHORTCUT("scene_tree/change_node_type", TTR("Change Type")); ED_SHORTCUT("scene_tree/attach_script", TTR("Attach Script")); + ED_SHORTCUT("scene_tree/extend_script", TTR("Extend Script")); ED_SHORTCUT("scene_tree/clear_script", TTR("Clear Script")); ED_SHORTCUT("scene_tree/move_up", TTR("Move Up"), KEY_MASK_CMD | KEY_UP); ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN); @@ -2363,10 +2372,12 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel filter->set_h_size_flags(SIZE_EXPAND_FILL); filter->set_placeholder(TTR("Filter nodes")); filter_hbc->add_child(filter); + filter->add_constant_override("minimum_spaces", 0); filter->connect("text_changed", this, "_filter_changed"); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false)); + tb->set_tooltip(TTR("Attach a new or existing script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script")); filter_hbc->add_child(tb); tb->hide(); @@ -2445,9 +2456,9 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel accept = memnew(AcceptDialog); add_child(accept); - file = memnew(EditorFileDialog); - add_child(file); - file->connect("file_selected", this, "instance"); + quick_open = memnew(EditorQuickOpen); + add_child(quick_open); + quick_open->connect("quick_open", this, "_quick_open"); set_process_unhandled_key_input(true); delete_dialog = memnew(ConfirmationDialog); diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h index eea34a3ec5..3939f4f361 100644 --- a/editor/scene_tree_dock.h +++ b/editor/scene_tree_dock.h @@ -36,6 +36,7 @@ #include "editor/editor_data.h" #include "editor/editor_sub_scene.h" #include "editor/groups_editor.h" +#include "editor/quick_open.h" #include "editor/rename_dialog.h" #include "editor/reparent_dialog.h" #include "editor/script_create_dialog.h" @@ -125,7 +126,7 @@ class SceneTreeDock : public VBoxContainer { ConfirmationDialog *editable_instance_remove_dialog; ReparentDialog *reparent_dialog; - EditorFileDialog *file; + EditorQuickOpen *quick_open; EditorSubScene *import_subscene_dialog; EditorFileDialog *new_scene_from_dialog; @@ -194,6 +195,7 @@ class SceneTreeDock : public VBoxContainer { void _nodes_dragged(Array p_nodes, NodePath p_to, int p_type); void _files_dropped(Vector<String> p_files, NodePath p_to, int p_type); void _script_dropped(String p_file, NodePath p_to); + void _quick_open(); void _tree_rmb(const Vector2 &p_menu_pos); diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp index 848e4def6d..6614e24df7 100644 --- a/editor/scene_tree_editor.cpp +++ b/editor/scene_tree_editor.cpp @@ -665,6 +665,13 @@ void SceneTreeEditor::_renamed() { Node *n = get_node(np); ERR_FAIL_COND(!n); + // Empty node names are not allowed, so resets it to previous text and show warning + if (which->get_text(0).strip_edges().empty()) { + which->set_text(0, n->get_name()); + EditorNode::get_singleton()->show_warning(TTR("No name provided")); + return; + } + String new_name = which->get_text(0); if (!Node::_validate_node_name(new_name)) { diff --git a/gles_builders.py b/gles_builders.py index 1e63a53f1a..f9fd6d3fa2 100644 --- a/gles_builders.py +++ b/gles_builders.py @@ -59,11 +59,11 @@ def include_file_in_legacygl_header(filename, header_data, depth): included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline) if not included_file in header_data.vertex_included_files and header_data.reading == "vertex": header_data.vertex_included_files += [included_file] - if include_file_in_legacygl_header(included_file, header_data, depth + 1) == None: + if include_file_in_legacygl_header(included_file, header_data, depth + 1) is None: print("Error in file '" + filename + "': #include " + includeline + "could not be found!") elif not included_file in header_data.fragment_included_files and header_data.reading == "fragment": header_data.fragment_included_files += [included_file] - if include_file_in_legacygl_header(included_file, header_data, depth + 1) == None: + if include_file_in_legacygl_header(included_file, header_data, depth + 1) is None: print("Error in file '" + filename + "': #include " + includeline + "could not be found!") line = fs.readline() diff --git a/main/input_default.cpp b/main/input_default.cpp index 913c143025..e8015400af 100644 --- a/main/input_default.cpp +++ b/main/input_default.cpp @@ -261,6 +261,13 @@ void InputDefault::parse_input_event(const Ref<InputEvent> &p_event) { void InputDefault::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) { + // Notes on mouse-touch emulation: + // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects + // as true mouse events. The only difference is the situation is flagged as emulated so they are not + // emulated back to touch events in an endless loop. + // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't + // require additional handling by this class. + _THREAD_SAFE_METHOD_ Ref<InputEventKey> k = p_event; @@ -316,11 +323,21 @@ void InputDefault::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool } } - if (emulate_mouse_from_touch) { + Ref<InputEventScreenTouch> st = p_event; + + if (st.is_valid()) { + + if (st->is_pressed()) { + SpeedTrack &track = touch_speed_track[st->get_index()]; + track.reset(); + } else { + // Since a pointer index may not occur again (OSs may or may not reuse them), + // imperatively remove it from the map to keep no fossil entries in it + touch_speed_track.erase(st->get_index()); + } - Ref<InputEventScreenTouch> st = p_event; + if (emulate_mouse_from_touch) { - if (st.is_valid()) { bool translate = false; if (st->is_pressed()) { if (mouse_from_touch_index == -1) { @@ -351,10 +368,18 @@ void InputDefault::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool _parse_input_event_impl(button_event, true); } } + } + + Ref<InputEventScreenDrag> sd = p_event; + + if (sd.is_valid()) { + + SpeedTrack &track = touch_speed_track[sd->get_index()]; + track.update(sd->get_relative()); + sd->set_speed(track.speed); - Ref<InputEventScreenDrag> sd = p_event; + if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) { - if (sd.is_valid() && sd->get_index() == mouse_from_touch_index) { Ref<InputEventMouseMotion> motion_event; motion_event.instance(); @@ -404,6 +429,7 @@ void InputDefault::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool action.physics_frame = Engine::get_singleton()->get_physics_frames(); action.idle_frame = Engine::get_singleton()->get_idle_frames(); action.pressed = p_event->is_action_pressed(E->key()); + action.strength = 0.f; action_state[E->key()] = action; } action_state[E->key()].strength = p_event->get_action_strength(E->key()); @@ -537,6 +563,7 @@ void InputDefault::action_press(const StringName &p_action) { action.physics_frame = Engine::get_singleton()->get_physics_frames(); action.idle_frame = Engine::get_singleton()->get_idle_frames(); action.pressed = true; + action.strength = 0.f; action_state[p_action] = action; } @@ -548,6 +575,7 @@ void InputDefault::action_release(const StringName &p_action) { action.physics_frame = Engine::get_singleton()->get_physics_frames(); action.idle_frame = Engine::get_singleton()->get_idle_frames(); action.pressed = false; + action.strength = 0.f; action_state[p_action] = action; } diff --git a/main/input_default.h b/main/input_default.h index b420ec124b..4964b9a83c 100644 --- a/main/input_default.h +++ b/main/input_default.h @@ -117,6 +117,7 @@ class InputDefault : public Input { }; SpeedTrack mouse_speed_track; + Map<int, SpeedTrack> touch_speed_track; Map<int, Joypad> joy_names; int fallback_mapping; diff --git a/main/main.cpp b/main/main.cpp index e9cd183d8a..6310281ff8 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -738,9 +738,13 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph } GLOBAL_DEF("memory/limits/multithreaded_server/rid_pool_prealloc", 60); + ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/multithreaded_server/rid_pool_prealloc", PropertyInfo(Variant::INT, "memory/limits/multithreaded_server/rid_pool_prealloc", PROPERTY_HINT_RANGE, "0,500,1")); // No negative and limit to 500 due to crashes GLOBAL_DEF("network/limits/debugger_stdout/max_chars_per_second", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger_stdout/max_chars_per_second", PropertyInfo(Variant::INT, "network/limits/debugger_stdout/max_chars_per_second", PROPERTY_HINT_RANGE, "0, 4096, 1, or_greater")); GLOBAL_DEF("network/limits/debugger_stdout/max_messages_per_frame", 10); + ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger_stdout/max_messages_per_frame", PropertyInfo(Variant::INT, "network/limits/debugger_stdout/max_messages_per_frame", PROPERTY_HINT_RANGE, "0, 20, 1, or_greater")); GLOBAL_DEF("network/limits/debugger_stdout/max_errors_per_frame", 10); + ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger_stdout/max_errors_per_frame", PropertyInfo(Variant::INT, "network/limits/debugger_stdout/max_errors_per_frame", PROPERTY_HINT_RANGE, "0, 20, 1, or_greater")); if (debug_mode == "remote") { @@ -813,6 +817,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph GLOBAL_DEF("logging/file_logging/enable_file_logging", false); GLOBAL_DEF("logging/file_logging/log_path", "user://logs/log.txt"); GLOBAL_DEF("logging/file_logging/max_log_files", 10); + ProjectSettings::get_singleton()->set_custom_property_info("logging/file_logging/max_log_files", PropertyInfo(Variant::INT, "logging/file_logging/max_log_files", PROPERTY_HINT_RANGE, "0,20,1,or_greater")); //no negative numbers if (FileAccess::get_create_func(FileAccess::ACCESS_USERDATA) && GLOBAL_GET("logging/file_logging/enable_file_logging")) { String base_path = GLOBAL_GET("logging/file_logging/log_path"); int max_files = GLOBAL_GET("logging/file_logging/max_log_files"); @@ -1003,6 +1008,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph Engine::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/common/physics_fps", 60)); Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5)); Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/settings/fps/force_fps", 0)); + ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/fps/force_fps", PropertyInfo(Variant::INT, "debug/settings/fps/force_fps", PROPERTY_HINT_RANGE, "0,120,1,or_greater")); GLOBAL_DEF("debug/settings/stdout/print_fps", false); @@ -1011,10 +1017,12 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph if (frame_delay == 0) { frame_delay = GLOBAL_DEF("application/run/frame_delay_msec", 0); + ProjectSettings::get_singleton()->set_custom_property_info("application/run/frame_delay_msec", PropertyInfo(Variant::INT, "application/run/frame_delay_msec", PROPERTY_HINT_RANGE, "0,100,1,or_greater")); // No negative numbers } OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false)); OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(GLOBAL_DEF("application/run/low_processor_mode_sleep_usec", 8000)); + ProjectSettings::get_singleton()->set_custom_property_info("application/run/low_processor_mode_sleep_usec", PropertyInfo(Variant::INT, "application/run/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "0,33200,1,or_greater")); // No negative numbers Engine::get_singleton()->set_frame_delay(frame_delay); @@ -1643,7 +1651,7 @@ bool Main::start() { GLOBAL_DEF("display/window/stretch/aspect", "ignore"); ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/aspect", PropertyInfo(Variant::STRING, "display/window/stretch/aspect", PROPERTY_HINT_ENUM, "ignore,keep,keep_width,keep_height,expand")); GLOBAL_DEF("display/window/stretch/shrink", 1); - ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/shrink", PropertyInfo(Variant::STRING, "display/window/stretch/shrink", PROPERTY_HINT_RANGE, "1,8,1")); + ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/shrink", PropertyInfo(Variant::REAL, "display/window/stretch/shrink", PROPERTY_HINT_RANGE, "1,8,1")); sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true)); sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true)); GLOBAL_DEF("gui/common/snap_controls_to_pixels", true); diff --git a/methods.py b/methods.py index 0cf05751a8..111a2347be 100644 --- a/methods.py +++ b/methods.py @@ -330,7 +330,7 @@ def split_lib(self, libname, src_list = None, env_lib = None): list = [] lib_list = [] - if src_list == None: + if src_list is None: src_list = getattr(env, libname + "_sources") if type(env_lib) == type(None): diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index d1ef08dc83..44044d2750 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -521,6 +521,11 @@ CSGBrush *CSGMesh::_build_brush() { Array arrays = mesh->surface_get_arrays(i); + if (arrays.size() == 0) { + _make_dirty(); + ERR_FAIL_COND_V(arrays.size() == 0, NULL); + } + PoolVector<Vector3> avertices = arrays[Mesh::ARRAY_VERTEX]; if (avertices.size() == 0) continue; diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp index ecde73ae1c..283e9b3bc8 100644 --- a/modules/gdnative/gdnative.cpp +++ b/modules/gdnative/gdnative.cpp @@ -306,6 +306,13 @@ bool GDNative::initialize() { #elif defined(UWP_ENABLED) // On UWP we use a relative path from the app String path = lib_path.replace("res://", ""); +#elif defined(OSX_ENABLED) + // On OSX the exported libraries are located under the Frameworks directory. + // So we need to replace the library path. + String path = ProjectSettings::get_singleton()->globalize_path(lib_path); + if (!FileAccess::exists(path)) { + path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(lib_path.get_file()); + } #else String path = ProjectSettings::get_singleton()->globalize_path(lib_path); #endif diff --git a/modules/gdnative/gdnative/array.cpp b/modules/gdnative/gdnative/array.cpp index 1fb0ff0500..a30cc09bf6 100644 --- a/modules/gdnative/gdnative/array.cpp +++ b/modules/gdnative/gdnative/array.cpp @@ -318,6 +318,38 @@ void GDAPI godot_array_destroy(godot_array *p_self) { ((Array *)p_self)->~Array(); } +godot_array GDAPI godot_array_duplicate(const godot_array *p_self, const godot_bool p_deep) { + const Array *self = (const Array *)p_self; + godot_array res; + Array *val = (Array *)&res; + memnew_placement(val, Array); + *val = self->duplicate(p_deep); + return res; +} + +godot_variant GDAPI godot_array_max(const godot_array *p_self) { + const Array *self = (const Array *)p_self; + godot_variant v; + Variant *val = (Variant *)&v; + memnew_placement(val, Variant); + *val = self->max(); + return v; +} + +godot_variant GDAPI godot_array_min(const godot_array *p_self) { + const Array *self = (const Array *)p_self; + godot_variant v; + Variant *val = (Variant *)&v; + memnew_placement(val, Variant); + *val = self->min(); + return v; +} + +void GDAPI godot_array_shuffle(godot_array *p_self) { + Array *self = (Array *)p_self; + self->shuffle(); +} + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/gdnative/basis.cpp b/modules/gdnative/gdnative/basis.cpp index 70d2814577..d88499ade1 100644 --- a/modules/gdnative/gdnative/basis.cpp +++ b/modules/gdnative/gdnative/basis.cpp @@ -282,6 +282,15 @@ godot_basis GDAPI godot_basis_operator_multiply_scalar(const godot_basis *p_self return raw_dest; } +godot_basis GDAPI godot_basis_slerp(const godot_basis *p_self, const godot_basis *p_b, const godot_real p_t) { + godot_basis raw_dest; + Basis *dest = (Basis *)&raw_dest; + const Basis *self = (const Basis *)p_self; + const Basis *b = (const Basis *)p_b; + *dest = self->slerp(*b, p_t); + return raw_dest; +} + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/gdnative/color.cpp b/modules/gdnative/gdnative/color.cpp index 4089f4458a..79f0c71b5e 100644 --- a/modules/gdnative/gdnative/color.cpp +++ b/modules/gdnative/gdnative/color.cpp @@ -116,6 +116,26 @@ godot_int GDAPI godot_color_to_rgba32(const godot_color *p_self) { return self->to_rgba32(); } +godot_int GDAPI godot_color_to_abgr32(const godot_color *p_self) { + const Color *self = (const Color *)p_self; + return self->to_abgr32(); +} + +godot_int GDAPI godot_color_to_abgr64(const godot_color *p_self) { + const Color *self = (const Color *)p_self; + return self->to_abgr64(); +} + +godot_int GDAPI godot_color_to_argb64(const godot_color *p_self) { + const Color *self = (const Color *)p_self; + return self->to_argb64(); +} + +godot_int GDAPI godot_color_to_rgba64(const godot_color *p_self) { + const Color *self = (const Color *)p_self; + return self->to_rgba64(); +} + godot_int GDAPI godot_color_to_argb32(const godot_color *p_self) { const Color *self = (const Color *)p_self; return self->to_argb32(); @@ -156,6 +176,27 @@ godot_color GDAPI godot_color_blend(const godot_color *p_self, const godot_color return dest; } +godot_color GDAPI godot_color_darkened(const godot_color *p_self, const godot_real p_amount) { + godot_color dest; + const Color *self = (const Color *)p_self; + *((Color *)&dest) = self->darkened(p_amount); + return dest; +} + +godot_color GDAPI godot_color_from_hsv(const godot_color *p_self, const godot_real p_h, const godot_real p_s, const godot_real p_v, const godot_real p_a) { + godot_color dest; + const Color *self = (const Color *)p_self; + *((Color *)&dest) = self->from_hsv(p_h, p_s, p_v, p_a); + return dest; +} + +godot_color GDAPI godot_color_lightened(const godot_color *p_self, const godot_real p_amount) { + godot_color dest; + const Color *self = (const Color *)p_self; + *((Color *)&dest) = self->lightened(p_amount); + return dest; +} + godot_string GDAPI godot_color_to_html(const godot_color *p_self, const godot_bool p_with_alpha) { godot_string dest; const Color *self = (const Color *)p_self; diff --git a/modules/gdnative/gdnative/node_path.cpp b/modules/gdnative/gdnative/node_path.cpp index f24facaae8..cf82940e09 100644 --- a/modules/gdnative/gdnative/node_path.cpp +++ b/modules/gdnative/gdnative/node_path.cpp @@ -110,6 +110,15 @@ godot_bool GDAPI godot_node_path_operator_equal(const godot_node_path *p_self, c return *self == *b; } +godot_node_path godot_node_path_get_as_property_path(const godot_node_path *p_self) { + const NodePath *self = (const NodePath *)p_self; + godot_node_path res; + NodePath *val = (NodePath *)&res; + memnew_placement(val, NodePath); + *val = self->get_as_property_path(); + return res; +} + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/gdnative/quat.cpp b/modules/gdnative/gdnative/quat.cpp index ddec77edcd..2594759508 100644 --- a/modules/gdnative/gdnative/quat.cpp +++ b/modules/gdnative/gdnative/quat.cpp @@ -225,6 +225,12 @@ godot_quat GDAPI godot_quat_operator_neg(const godot_quat *p_self) { return raw_dest; } +void GDAPI godot_quat_set_axis_angle(godot_quat *p_self, const godot_vector3 *p_axis, const godot_real p_angle) { + Quat *self = (Quat *)p_self; + const Vector3 *axis = (const Vector3 *)p_axis; + self->set_axis_angle(*axis, p_angle); +} + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/gdnative/rect2.cpp b/modules/gdnative/gdnative/rect2.cpp index 54b98fc4e5..5cbc2712c3 100644 --- a/modules/gdnative/gdnative/rect2.cpp +++ b/modules/gdnative/gdnative/rect2.cpp @@ -109,6 +109,27 @@ godot_rect2 GDAPI godot_rect2_grow(const godot_rect2 *p_self, const godot_real p return dest; } +godot_rect2 GDAPI godot_rect2_grow_individual(const godot_rect2 *p_self, const godot_real p_left, const godot_real p_top, const godot_real p_right, const godot_real p_bottom) { + godot_rect2 dest; + const Rect2 *self = (const Rect2 *)p_self; + *((Rect2 *)&dest) = self->grow_individual(p_left, p_top, p_right, p_bottom); + return dest; +} + +godot_rect2 GDAPI godot_rect2_grow_margin(const godot_rect2 *p_self, const godot_int p_margin, const godot_real p_by) { + godot_rect2 dest; + const Rect2 *self = (const Rect2 *)p_self; + *((Rect2 *)&dest) = self->grow_margin((Margin)p_margin, p_by); + return dest; +} + +godot_rect2 GDAPI godot_rect2_abs(const godot_rect2 *p_self) { + godot_rect2 dest; + const Rect2 *self = (const Rect2 *)p_self; + *((Rect2 *)&dest) = self->abs(); + return dest; +} + godot_rect2 GDAPI godot_rect2_expand(const godot_rect2 *p_self, const godot_vector2 *p_to) { godot_rect2 dest; const Rect2 *self = (const Rect2 *)p_self; diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp index 8ca57392a3..0996633b70 100644 --- a/modules/gdnative/gdnative/string.cpp +++ b/modules/gdnative/gdnative/string.cpp @@ -1285,6 +1285,64 @@ godot_bool GDAPI godot_string_is_valid_ip_address(const godot_string *p_self) { return self->is_valid_ip_address(); } +godot_string GDAPI godot_string_dedent(const godot_string *p_self) { + const String *self = (const String *)p_self; + godot_string result; + String return_value = self->dedent(); + memnew_placement(&result, String(return_value)); + + return result; +} + +godot_string GDAPI godot_string_trim_prefix(const godot_string *p_self, const godot_string *p_prefix) { + const String *self = (const String *)p_self; + String *prefix = (String *)p_prefix; + godot_string result; + String return_value = self->trim_prefix(*prefix); + memnew_placement(&result, String(return_value)); + + return result; +} + +godot_string GDAPI godot_string_trim_suffix(const godot_string *p_self, const godot_string *p_suffix) { + const String *self = (const String *)p_self; + String *suffix = (String *)p_suffix; + godot_string result; + String return_value = self->trim_suffix(*suffix); + memnew_placement(&result, String(return_value)); + + return result; +} + +godot_string GDAPI godot_string_rstrip(const godot_string *p_self, const godot_string *p_chars) { + const String *self = (const String *)p_self; + String *chars = (String *)p_chars; + godot_string result; + String return_value = self->rstrip(*chars); + memnew_placement(&result, String(return_value)); + + return result; +} + +godot_pool_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_divisor, + const godot_bool p_allow_empty, const godot_int p_maxsplit) { + const String *self = (const String *)p_self; + String *divisor = (String *)p_divisor; + + godot_pool_string_array result; + memnew_placement(&result, PoolStringArray); + PoolStringArray *proxy = (PoolStringArray *)&result; + PoolStringArray::Write proxy_writer = proxy->write(); + Vector<String> tmp_result = self->rsplit(*divisor, p_allow_empty, p_maxsplit); + proxy->resize(tmp_result.size()); + + for (int i = 0; i < tmp_result.size(); i++) { + proxy_writer[i] = tmp_result[i]; + } + + return result; +} + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 16a34a9a33..c5a1fa139e 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -14,6 +14,183 @@ "next": null, "api": [ { + "name": "godot_color_to_abgr32", + "return_type": "godot_int", + "arguments": [ + ["const godot_color *", "p_self"] + ] + }, + { + "name": "godot_color_to_abgr64", + "return_type": "godot_int", + "arguments": [ + ["const godot_color *", "p_self"] + ] + }, + { + "name": "godot_color_to_argb64", + "return_type": "godot_int", + "arguments": [ + ["const godot_color *", "p_self"] + ] + }, + { + "name": "godot_color_to_rgba64", + "return_type": "godot_int", + "arguments": [ + ["const godot_color *", "p_self"] + ] + }, + { + "name": "godot_color_darkened", + "return_type": "godot_color", + "arguments": [ + ["const godot_color *", "p_self"], + ["const godot_real", "p_amount"] + ] + }, + { + "name": "godot_color_from_hsv", + "return_type": "godot_color", + "arguments": [ + ["const godot_color *", "p_self"], + ["const godot_real", "p_h"], + ["const godot_real", "p_s"], + ["const godot_real", "p_v"], + ["const godot_real", "p_a"] + ] + }, + { + "name": "godot_color_lightened", + "return_type": "godot_color", + "arguments": [ + ["const godot_color *", "p_self"], + ["const godot_real", "p_amount"] + ] + }, + { + "name": "godot_array_duplicate", + "return_type": "godot_array", + "arguments": [ + ["const godot_array *", "p_self"], + ["const godot_bool", "p_deep"] + ] + }, + { + "name": "godot_array_max", + "return_type": "godot_variant", + "arguments": [ + ["const godot_array *", "p_self"] + ] + }, + { + "name": "godot_array_min", + "return_type": "godot_variant", + "arguments": [ + ["const godot_array *", "p_self"] + ] + }, + { + "name": "godot_array_shuffle", + "return_type": "void", + "arguments": [ + ["godot_array *", "p_self"] + ] + }, + { + "name": "godot_basis_slerp", + "return_type": "godot_basis", + "arguments": [ + ["const godot_basis *", "p_self"], + ["const godot_basis *", "p_b"], + ["const godot_real", "p_t"] + ] + }, + { + "name": "godot_node_path_get_as_property_path", + "return_type": "godot_node_path", + "arguments": [ + ["const godot_node_path *", "p_self"] + ] + }, + { + "name": "godot_quat_set_axis_angle", + "return_type": "void", + "arguments": [ + ["godot_quat *", "p_self"], + ["const godot_vector3 *", "p_axis"], + ["const godot_real", "p_angle"] + ] + }, + { + "name": "godot_rect2_grow_individual", + "return_type": "godot_rect2", + "arguments": [ + ["const godot_rect2 *", "p_self"], + ["const godot_real", "p_left"], + ["const godot_real", "p_top"], + ["const godot_real", "p_right"], + ["const godot_real", "p_bottom"] + ] + }, + { + "name": "godot_rect2_grow_margin", + "return_type": "godot_rect2", + "arguments": [ + ["const godot_rect2 *", "p_self"], + ["const godot_int", "p_margin"], + ["const godot_real", "p_by"] + ] + }, + { + "name": "godot_rect2_abs", + "return_type": "godot_rect2", + "arguments": [ + ["const godot_rect2 *", "p_self"] + ] + }, + { + "name": "godot_string_dedent", + "return_type": "godot_string", + "arguments": [ + ["const godot_string *", "p_self"] + ] + }, + { + "name": "godot_string_trim_prefix", + "return_type": "godot_string", + "arguments": [ + ["const godot_string *", "p_self"], + ["const godot_string *", "p_prefix"] + ] + }, + { + "name": "godot_string_trim_suffix", + "return_type": "godot_string", + "arguments": [ + ["const godot_string *", "p_self"], + ["const godot_string *", "p_suffix"] + ] + }, + { + "name": "godot_string_rstrip", + "return_type": "godot_string", + "arguments": [ + ["const godot_string *", "p_self"], + ["const godot_string *", "p_chars"] + ] + }, + { + "name": "godot_string_rsplit", + "return_type": "godot_pool_string_array", + "arguments": [ + ["const godot_string *", "p_self"], + ["const godot_string *", "p_divisor"], + ["const godot_bool", "p_allow_empty"], + ["const godot_int", "p_maxsplit"] + ] + }, + { "name": "godot_basis_get_quat", "return_type": "godot_quat", "arguments": [ diff --git a/modules/gdnative/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h index 1e66d133b9..876b8f8e8f 100644 --- a/modules/gdnative/include/gdnative/array.h +++ b/modules/gdnative/include/gdnative/array.h @@ -130,6 +130,14 @@ godot_int GDAPI godot_array_bsearch_custom(godot_array *p_self, const godot_vari void GDAPI godot_array_destroy(godot_array *p_self); +godot_array GDAPI godot_array_duplicate(const godot_array *p_self, const godot_bool p_deep); + +godot_variant GDAPI godot_array_max(const godot_array *p_self); + +godot_variant GDAPI godot_array_min(const godot_array *p_self); + +void GDAPI godot_array_shuffle(godot_array *p_self); + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/include/gdnative/basis.h b/modules/gdnative/include/gdnative/basis.h index ebe2b1125b..6128bf3ac3 100644 --- a/modules/gdnative/include/gdnative/basis.h +++ b/modules/gdnative/include/gdnative/basis.h @@ -127,6 +127,8 @@ godot_basis GDAPI godot_basis_operator_multiply_vector(const godot_basis *p_self godot_basis GDAPI godot_basis_operator_multiply_scalar(const godot_basis *p_self, const godot_real p_b); +godot_basis GDAPI godot_basis_slerp(const godot_basis *p_self, const godot_basis *p_b, const godot_real p_t); + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/include/gdnative/color.h b/modules/gdnative/include/gdnative/color.h index 1f0ac8354d..3007dbc6e3 100644 --- a/modules/gdnative/include/gdnative/color.h +++ b/modules/gdnative/include/gdnative/color.h @@ -81,6 +81,14 @@ godot_string GDAPI godot_color_as_string(const godot_color *p_self); godot_int GDAPI godot_color_to_rgba32(const godot_color *p_self); +godot_int GDAPI godot_color_to_abgr32(const godot_color *p_self); + +godot_int GDAPI godot_color_to_abgr64(const godot_color *p_self); + +godot_int GDAPI godot_color_to_argb64(const godot_color *p_self); + +godot_int GDAPI godot_color_to_rgba64(const godot_color *p_self); + godot_int GDAPI godot_color_to_argb32(const godot_color *p_self); godot_real GDAPI godot_color_gray(const godot_color *p_self); @@ -93,6 +101,12 @@ godot_color GDAPI godot_color_linear_interpolate(const godot_color *p_self, cons godot_color GDAPI godot_color_blend(const godot_color *p_self, const godot_color *p_over); +godot_color GDAPI godot_color_darkened(const godot_color *p_self, const godot_real p_amount); + +godot_color GDAPI godot_color_from_hsv(const godot_color *p_self, const godot_real p_h, const godot_real p_s, const godot_real p_v, const godot_real p_a); + +godot_color GDAPI godot_color_lightened(const godot_color *p_self, const godot_real p_amount); + godot_string GDAPI godot_color_to_html(const godot_color *p_self, const godot_bool p_with_alpha); godot_bool GDAPI godot_color_operator_equal(const godot_color *p_self, const godot_color *p_b); diff --git a/modules/gdnative/include/gdnative/node_path.h b/modules/gdnative/include/gdnative/node_path.h index 2b55e01d13..48fe5b4d3d 100644 --- a/modules/gdnative/include/gdnative/node_path.h +++ b/modules/gdnative/include/gdnative/node_path.h @@ -80,6 +80,8 @@ godot_bool GDAPI godot_node_path_is_empty(const godot_node_path *p_self); godot_bool GDAPI godot_node_path_operator_equal(const godot_node_path *p_self, const godot_node_path *p_b); +godot_node_path godot_node_path_get_as_property_path(const godot_node_path *p_self); + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/include/gdnative/quat.h b/modules/gdnative/include/gdnative/quat.h index b1290f745c..634f486e66 100644 --- a/modules/gdnative/include/gdnative/quat.h +++ b/modules/gdnative/include/gdnative/quat.h @@ -109,6 +109,8 @@ godot_bool GDAPI godot_quat_operator_equal(const godot_quat *p_self, const godot godot_quat GDAPI godot_quat_operator_neg(const godot_quat *p_self); +void GDAPI godot_quat_set_axis_angle(godot_quat *p_self, const godot_vector3 *p_axis, const godot_real p_angle); + #ifdef __cplusplus } #endif diff --git a/modules/gdnative/include/gdnative/rect2.h b/modules/gdnative/include/gdnative/rect2.h index 4adcb73e3d..47c15c80bd 100644 --- a/modules/gdnative/include/gdnative/rect2.h +++ b/modules/gdnative/include/gdnative/rect2.h @@ -77,6 +77,12 @@ godot_bool GDAPI godot_rect2_has_point(const godot_rect2 *p_self, const godot_ve godot_rect2 GDAPI godot_rect2_grow(const godot_rect2 *p_self, const godot_real p_by); +godot_rect2 GDAPI godot_rect2_grow_individual(const godot_rect2 *p_self, const godot_real p_left, const godot_real p_top, const godot_real p_right, const godot_real p_bottom); + +godot_rect2 GDAPI godot_rect2_grow_margin(const godot_rect2 *p_self, const godot_int p_margin, const godot_real p_by); + +godot_rect2 GDAPI godot_rect2_abs(const godot_rect2 *p_self); + godot_rect2 GDAPI godot_rect2_expand(const godot_rect2 *p_self, const godot_vector2 *p_to); godot_bool GDAPI godot_rect2_operator_equal(const godot_rect2 *p_self, const godot_rect2 *p_b); diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h index 73245160c1..95ae42a9ec 100644 --- a/modules/gdnative/include/gdnative/string.h +++ b/modules/gdnative/include/gdnative/string.h @@ -246,6 +246,12 @@ godot_bool GDAPI godot_string_is_valid_identifier(const godot_string *p_self); godot_bool GDAPI godot_string_is_valid_integer(const godot_string *p_self); godot_bool GDAPI godot_string_is_valid_ip_address(const godot_string *p_self); +godot_string GDAPI godot_string_dedent(const godot_string *p_self); +godot_string GDAPI godot_string_trim_prefix(const godot_string *p_self, const godot_string *p_prefix); +godot_string GDAPI godot_string_trim_suffix(const godot_string *p_self, const godot_string *p_suffix); +godot_string GDAPI godot_string_rstrip(const godot_string *p_self, const godot_string *p_chars); +godot_pool_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_divisor, const godot_bool p_allow_empty, const godot_int p_maxsplit); + void GDAPI godot_string_destroy(godot_string *p_self); #ifdef __cplusplus diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp index 37e72bf9f8..3e56275396 100644 --- a/modules/gdnative/nativescript/nativescript.cpp +++ b/modules/gdnative/nativescript/nativescript.cpp @@ -1711,8 +1711,7 @@ void NativeReloadNode::_notification(int p_what) { } RES ResourceFormatLoaderNativeScript::load(const String &p_path, const String &p_original_path, Error *r_error) { - ResourceFormatLoaderText rsflt; - return rsflt.load(p_path, p_original_path, r_error); + return ResourceFormatLoaderText::singleton->load(p_path, p_original_path, r_error); } void ResourceFormatLoaderNativeScript::get_recognized_extensions(List<String> *p_extensions) const { diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 48c1760662..ef86ccae14 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -2065,12 +2065,12 @@ GDScriptLanguage::GDScriptLanguage() { _debug_call_stack_pos = 0; int dmcs = GLOBAL_DEF("debug/settings/gdscript/max_call_stack", 1024); + ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/gdscript/max_call_stack", PropertyInfo(Variant::INT, "debug/settings/gdscript/max_call_stack", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); //minimum is 1024 + if (ScriptDebugger::get_singleton()) { //debugging enabled! _debug_max_call_stack = dmcs; - if (_debug_max_call_stack < 1024) - _debug_max_call_stack = 1024; _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1); } else { @@ -2081,6 +2081,7 @@ GDScriptLanguage::GDScriptLanguage() { #ifdef DEBUG_ENABLED GLOBAL_DEF("debug/gdscript/warnings/enable", true); GLOBAL_DEF("debug/gdscript/warnings/treat_warnings_as_errors", false); + GLOBAL_DEF("debug/gdscript/completion/autocomplete_setters_and_getters", false); for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) { String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower(); GLOBAL_DEF("debug/gdscript/warnings/" + warning, !warning.begins_with("unsafe_")); diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 310c4e21f2..45319c59e7 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -1603,13 +1603,13 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Blo return OK; } -Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready) { +Error GDScriptCompiler::_parse_function(Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready) { Vector<int> bytecode; CodeGen codegen; codegen.class_node = p_class; - codegen.script = p_script; + codegen.script = p_script.ptr(); codegen.function_node = p_func; codegen.stack_max = 0; codegen.current_line = 0; @@ -1853,7 +1853,7 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser return OK; } -Error GDScriptCompiler::_parse_class_level(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { +Error GDScriptCompiler::_parse_class_level(Ref<GDScript> p_script, Ref<GDScript> p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { if (p_class->owner && p_class->owner->owner) { // Owner is not root @@ -1887,7 +1887,7 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, GDScript *p_owner p_script->initializer = NULL; p_script->subclasses.clear(); - p_script->_owner = p_owner; + p_script->_owner = p_owner.ptr(); p_script->tool = p_class->tool; p_script->name = p_class->name; @@ -1994,7 +1994,7 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, GDScript *p_owner StringName name = p_class->_signals[i].name; - GDScript *c = p_script; + GDScript *c = p_script.ptr(); while (c) { @@ -2054,7 +2054,7 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, GDScript *p_owner return OK; } -Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { +Error GDScriptCompiler::_parse_class_blocks(Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { //parse methods bool has_initializer = false; @@ -2159,7 +2159,7 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa return OK; } -void GDScriptCompiler::_make_scripts(const GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { +void GDScriptCompiler::_make_scripts(const Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { Map<StringName, Ref<GDScript> > old_subclasses; @@ -2178,20 +2178,20 @@ void GDScriptCompiler::_make_scripts(const GDScript *p_script, const GDScriptPar subclass.instance(); } - subclass->_owner = const_cast<GDScript *>(p_script); + subclass->_owner = const_cast<GDScript *>(p_script.ptr()); class_map.insert(name, subclass); _make_scripts(subclass.ptr(), p_class->subclasses[i], p_keep_state); } } -Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) { +Error GDScriptCompiler::compile(const GDScriptParser *p_parser, Ref<GDScript> p_script, bool p_keep_state) { err_line = -1; err_column = -1; error = ""; parser = p_parser; - main_script = p_script; + main_script = p_script.ptr(); const GDScriptParser::Node *root = parser->get_parse_tree(); ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, ERR_INVALID_DATA); diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h index 55f5e2b48e..23c6450aa7 100644 --- a/modules/gdscript/gdscript_compiler.h +++ b/modules/gdscript/gdscript_compiler.h @@ -148,17 +148,17 @@ class GDScriptCompiler { int _parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::OperatorNode *p_expression, int p_stack_level); int _parse_expression(CodeGen &codegen, const GDScriptParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false); Error _parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1); - Error _parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false); - Error _parse_class_level(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state); - Error _parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); - void _make_scripts(const GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _parse_function(Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false); + Error _parse_class_level(Ref<GDScript> p_script, Ref<GDScript> p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _parse_class_blocks(Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + void _make_scripts(const Ref<GDScript> p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); int err_line; int err_column; StringName source; String error; public: - Error compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state = false); + Error compile(const GDScriptParser *p_parser, Ref<GDScript> p_script, bool p_keep_state = false); String get_error() const; int get_error_line() const; diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index ddd9e6b01c..068e8d2d92 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -1308,37 +1308,38 @@ static bool _guess_identifier_type(const GDScriptCompletionContext &p_context, c return false; } - // Check ClassDB - if (ClassDB::class_exists(p_identifier)) { - r_type.type.has_type = true; - r_type.type.kind = GDScriptParser::DataType::NATIVE; - r_type.type.native_type = p_identifier; - if (Engine::get_singleton()->has_singleton(p_identifier)) { - r_type.type.is_meta_type = false; - r_type.value = Engine::get_singleton()->get_singleton_object(p_identifier); - } else { - r_type.type.is_meta_type = true; - int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; - r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx]; + for (int i = 0; i < 2; i++) { + StringName target_id; + switch (i) { + case 0: + // Check ClassDB + target_id = p_identifier; + break; + case 1: + // ClassDB again for underscore-prefixed classes + target_id = String("_") + p_identifier; + break; } - return true; - } - // ClassDB again for underscore-prefixed classes - StringName under_id = String("_") + p_identifier; - if (ClassDB::class_exists(under_id)) { - r_type.type.has_type = true; - r_type.type.kind = GDScriptParser::DataType::NATIVE; - r_type.type.native_type = p_identifier; - if (Engine::get_singleton()->has_singleton(p_identifier)) { - r_type.type.is_meta_type = false; - r_type.value = Engine::get_singleton()->get_singleton_object(p_identifier); - } else { - r_type.type.is_meta_type = true; - int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; - r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx]; + if (ClassDB::class_exists(target_id)) { + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::NATIVE; + r_type.type.native_type = target_id; + if (Engine::get_singleton()->has_singleton(target_id)) { + r_type.type.is_meta_type = false; + r_type.value = Engine::get_singleton()->get_singleton_object(target_id); + } else { + r_type.type.is_meta_type = true; + const Map<StringName, int>::Element *target_elem = GDScriptLanguage::get_singleton()->get_global_map().find(target_id); + // Check because classes like EditorNode are in ClassDB by now, but unknown to GDScript + if (!target_elem) { + return false; + } + int idx = target_elem->get(); + r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx]; + } + return true; } - return true; } // Check autoload singletons @@ -1999,7 +2000,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context if (!_static) { List<MethodInfo> methods; - ClassDB::get_method_list(type, &methods, false, true); + bool is_autocompleting_getters = GLOBAL_GET("debug/gdscript/completion/autocomplete_setters_and_getters").booleanize(); + ClassDB::get_method_list(type, &methods, false, !is_autocompleting_getters); for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { if (E->get().name.begins_with("_")) { continue; diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index f09ff224e8..31115a4bd9 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -275,7 +275,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #endif uint32_t alloca_size = 0; - GDScript *_class; + GDScript *script; int ip = 0; int line = _initial_line; @@ -286,7 +286,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a line = p_state->line; ip = p_state->ip; alloca_size = p_state->stack.size(); - _class = p_state->_class; + script = p_state->script.ptr(); p_instance = p_state->instance; defarg = p_state->defarg; self = p_state->self; @@ -368,9 +368,9 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } else { self = p_instance->owner; } - _class = p_instance->script.ptr(); + script = p_instance->script.ptr(); } else { - _class = _script; + script = this->_script.ptr(); } } @@ -395,7 +395,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #define GET_VARIANT_PTR(m_v, m_code_ofs) \ Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, stack, err_text); \ if (unlikely(!m_v)) \ OPCODE_BREAK; @@ -404,7 +404,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #define CHECK_SPACE(m_space) #define GET_VARIANT_PTR(m_v, m_code_ofs) \ Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, stack, err_text); #endif @@ -1185,7 +1185,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a GET_VARIANT_PTR(dst, argc + 3); - const GDScript *gds = _script; + const GDScript *gds = _script.ptr(); const Map<StringName, GDScriptFunction *>::Element *E = NULL; while (gds->base.ptr()) { @@ -1256,11 +1256,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a gdfs->state.stack_size = _stack_size; gdfs->state.self = self; gdfs->state.alloca_size = alloca_size; - gdfs->state._class = _class; + gdfs->state.script = _script; gdfs->state.ip = ip + ipofs; gdfs->state.line = line; gdfs->state.instance_id = (p_instance && p_instance->get_owner()) ? p_instance->get_owner()->get_instance_id() : 0; - gdfs->state.script_id = _class->get_instance_id(); //gdfs->state.result_pos=ip+ipofs-1; gdfs->state.defarg = defarg; gdfs->state.instance = p_instance; @@ -1549,8 +1548,8 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a String err_file; if (p_instance) err_file = p_instance->script->path; - else if (_class) - err_file = _class->path; + else if (script) + err_file = script->path; if (err_file == "") err_file = "<built-in>"; String err_func = name; @@ -1765,15 +1764,20 @@ GDScriptFunction::~GDScriptFunction() { Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { #ifdef DEBUG_ENABLED - if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); + // Checking this first since it's faster + if (!state.script.is_valid()) { + ERR_EXPLAIN("Resumed after yield, but script is gone"); ERR_FAIL_V(Variant()); } - if (state.script_id && !ObjectDB::get_instance(state.script_id)) { - ERR_EXPLAIN("Resumed after yield, but script is gone"); + if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { + ERR_EXPLAIN("Resumed after yield, but class instance is gone"); ERR_FAIL_V(Variant()); } +#else + if (!is_valid()) { + return Variant(); + } #endif Variant arg; @@ -1841,12 +1845,12 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const { return false; if (p_extended_check) { + //script gone? (checking this first since it's faster) + if (!state.script.is_valid()) + return false; //class instance gone? if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) return false; - //script gone? - if (state.script_id && !ObjectDB::get_instance(state.script_id)) - return false; } return true; @@ -1856,13 +1860,14 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) { ERR_FAIL_COND_V(!function, Variant()); #ifdef DEBUG_ENABLED - if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); + // Checking this first since it's faster + if (!state.script.is_valid()) { + ERR_EXPLAIN("Resumed after yield, but script is gone"); ERR_FAIL_V(Variant()); } - if (state.script_id && !ObjectDB::get_instance(state.script_id)) { - ERR_EXPLAIN("Resumed after yield, but script is gone"); + if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { + ERR_EXPLAIN("Resumed after yield, but class instance is gone"); ERR_FAIL_V(Variant()); } #endif diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index bfb6d673f1..a47070de4f 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -225,7 +225,7 @@ private: bool _static; MultiplayerAPI::RPCMode rpc_mode; - GDScript *_script; + Ref<GDScript> _script; StringName name; Vector<Variant> constants; @@ -272,15 +272,13 @@ private: public: struct CallState { - ObjectID instance_id; //by debug only - ObjectID script_id; - + ObjectID instance_id; GDScriptInstance *instance; Vector<uint8_t> stack; int stack_size; Variant self; uint32_t alloca_size; - GDScript *_class; + Ref<GDScript> script; int ip; int line; int defarg; @@ -299,7 +297,7 @@ public: int get_default_argument_addr(int p_idx) const; GDScriptDataType get_return_type() const; GDScriptDataType get_argument_type(int p_idx) const; - GDScript *get_script() const { return _script; } + GDScript *get_script() const { return const_cast<GDScript *>(_script.ptr()); } StringName get_source() const { return source; } void debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const; diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 5f2655eb92..97ac6f7de6 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -6709,9 +6709,15 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat } } + bool rets = false; return_type.has_type = true; return_type.kind = DataType::BUILTIN; - return_type.builtin_type = Variant::get_method_return_type(base_type.builtin_type, callee_name); + return_type.builtin_type = Variant::get_method_return_type(base_type.builtin_type, callee_name, &rets); + // If the method returns, but it might return any type, (Variant::NIL), pretend we don't know the type. + // At least make sure we know that it returns + if (rets && return_type.builtin_type == Variant::NIL) { + return_type.has_type = false; + } break; } diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index a49137ae73..24d40111cf 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -48,9 +48,9 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p const int image_width = decoder.get_width(); const int image_height = decoder.get_height(); - int comps = decoder.get_num_components(); - if (comps == 3) - comps = 4; //weird + const int comps = decoder.get_num_components(); + if (comps != 1 && comps != 3) + return ERR_FILE_CORRUPT; if (decoder.begin_decoding() != jpgd::JPGD_SUCCESS) return ERR_FILE_CORRUPT; @@ -73,7 +73,19 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p } jpgd::uint8 *pDst = pImage_data + y * dst_bpl; - memcpy(pDst, pScan_line, dst_bpl); + + if (comps == 1) { + memcpy(pDst, pScan_line, dst_bpl); + } else { + // For images with more than 1 channel pScan_line will always point to a buffer + // containing 32-bit RGBA pixels. Alpha is always 255 and we ignore it. + for (int x = 0; x < image_width; x++) { + pDst[0] = pScan_line[x * 4 + 0]; + pDst[1] = pScan_line[x * 4 + 1]; + pDst[2] = pScan_line[x * 4 + 2]; + pDst += 3; + } + } } //all good @@ -82,7 +94,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p if (comps == 1) fmt = Image::FORMAT_L8; else - fmt = Image::FORMAT_RGBA8; + fmt = Image::FORMAT_RGB8; dw = PoolVector<uint8_t>::Write(); p_image->create(image_width, image_height, 0, fmt, data); diff --git a/modules/mono/SCsub b/modules/mono/SCsub index 9a62b0fdc9..0e5dd9b4cf 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -44,7 +44,7 @@ def make_cs_files_header(src, dst, version_dst): if i > 0: header.write(', ') header.write(byte_to_str(buf[buf_idx])) - inserted_files += '\tr_files.insert("' + filepath_src_rel + '", ' \ + inserted_files += '\tr_files.insert("' + filepath_src_rel.replace('\\', '\\\\') + '", ' \ 'CompressedFile(_cs_' + name + '_compressed_size, ' \ '_cs_' + name + '_uncompressed_size, ' \ '_cs_' + name + '_compressed));\n' @@ -102,6 +102,75 @@ env_mono = conf.Finish() import os +def find_nuget_unix(): + import os.path + import sys + + hint_dirs = ['/opt/novell/mono/bin'] + if sys.platform == 'darwin': + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs + + for hint_dir in hint_dirs: + hint_path = os.path.join(hint_dir, 'nuget') + if os.path.isfile(hint_path): + return hint_path + elif os.path.isfile(hint_path + '.exe'): + return hint_path + '.exe' + + for hint_dir in os.environ['PATH'].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, 'nuget') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + if os.path.isfile(hint_path + '.exe') and os.access(hint_path + '.exe', os.X_OK): + return hint_path + '.exe' + + return None + + +def find_nuget_windows(): + import mono_reg_utils as monoreg + + mono_root = '' + bits = env['bits'] + + if bits == '32': + if os.getenv('MONO32_PREFIX'): + mono_root = os.getenv('MONO32_PREFIX') + else: + mono_root = monoreg.find_mono_root_dir(bits) + else: + if os.getenv('MONO64_PREFIX'): + mono_root = os.getenv('MONO64_PREFIX') + else: + mono_root = monoreg.find_mono_root_dir(bits) + + if mono_root: + mono_bin_dir = os.path.join(mono_root, 'bin') + nuget_mono = os.path.join(mono_bin_dir, 'nuget.bat') + + if os.path.isfile(nuget_mono): + return nuget_mono + + # Standalone NuGet + + for hint_dir in os.environ['PATH'].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, 'nuget.exe') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + if 'NUGET_PATH' in os.environ: + hint_path = os.environ['NUGET_PATH'] + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + hint_path = os.path.join(hint_path, 'nuget.exe') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + return None + + def find_msbuild_unix(filename): import os.path import sys @@ -176,14 +245,17 @@ def mono_build_solution(source, target, env): import mono_reg_utils as monoreg from shutil import copyfile - framework_path = '' + sln_path = os.path.abspath(str(source[0])) + target_path = os.path.abspath(str(target[0])) + framework_path = '' msbuild_env = os.environ.copy() # Needed when running from Developer Command Prompt for VS if 'PLATFORM' in msbuild_env: del msbuild_env['PLATFORM'] + # Find MSBuild if os.name == 'nt': msbuild_info = find_msbuild_windows() if msbuild_info is None: @@ -213,11 +285,27 @@ def mono_build_solution(source, target, env): print('MSBuild path: ' + msbuild_path) + # Find NuGet + nuget_path = find_nuget_windows() if os.name == 'nt' else find_nuget_unix() + if nuget_path is None: + raise RuntimeError('Cannot find NuGet executable') + + print('NuGet path: ' + nuget_path) + + # Do NuGet restore + + try: + subprocess.check_call([nuget_path, 'restore', sln_path]) + except subprocess.CalledProcessError: + raise RuntimeError('GodotSharpTools: NuGet restore failed') + + # Build solution + build_config = 'Release' msbuild_args = [ msbuild_path, - os.path.abspath(str(source[0])), + sln_path, '/p:Configuration=' + build_config, ] @@ -227,20 +315,24 @@ def mono_build_solution(source, target, env): try: subprocess.check_call(msbuild_args, env=msbuild_env) except subprocess.CalledProcessError: - raise RuntimeError('GodotSharpTools build failed') + raise RuntimeError('GodotSharpTools: Build failed') + + # Copy files - src_dir = os.path.abspath(os.path.join(str(source[0]), os.pardir, 'bin', build_config)) - dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + src_dir = os.path.abspath(os.path.join(sln_path, os.pardir, 'bin', build_config)) + dst_dir = os.path.abspath(os.path.join(target_path, os.pardir)) + asm_file = 'GodotSharpTools.dll' if not os.path.isdir(dst_dir): if os.path.exists(dst_dir): raise RuntimeError('Target directory is a file') os.makedirs(dst_dir) - asm_file = 'GodotSharpTools.dll' - copyfile(os.path.join(src_dir, asm_file), os.path.join(dst_dir, asm_file)) + # Dependencies + copyfile(os.path.join(src_dir, "DotNet.Glob.dll"), os.path.join(dst_dir, "DotNet.Glob.dll")) + if env['tools']: output_dir = Dir('#bin').abspath editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools') diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 5160d42367..a048baf5d7 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -32,6 +32,7 @@ #include <mono/metadata/threads.h> +#include "core/io/json.h" #include "core/os/file_access.h" #include "core/os/os.h" #include "core/os/thread.h" @@ -42,7 +43,6 @@ #include "editor/csharp_project.h" #include "editor/editor_node.h" #include "editor/godotsharp_editor.h" -#include "utils/string_utils.h" #endif #include "godotsharp_dirs.h" @@ -50,6 +50,7 @@ #include "mono_gd/gd_mono_marshal.h" #include "signal_awaiter_utils.h" #include "utils/macros.h" +#include "utils/string_utils.h" #include "utils/thread_local.h" #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var) @@ -370,6 +371,7 @@ bool CSharpLanguage::supports_builtin_mode() const { return false; } +#ifdef TOOLS_ENABLED static String variant_type_to_managed_name(const String &p_var_type_name) { if (p_var_type_name.empty()) @@ -432,8 +434,7 @@ static String variant_type_to_managed_name(const String &p_var_type_name) { return p_var_type_name; } -String CSharpLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { -#ifdef TOOLS_ENABLED +String CSharpLanguage::make_function(const String &, const String &p_name, const PoolStringArray &p_args) const { // FIXME // - Due to Godot's API limitation this just appends the function to the end of the file // - Use fully qualified name if there is ambiguity @@ -449,10 +450,12 @@ String CSharpLanguage::make_function(const String &p_class, const String &p_name s += ")\n{\n // Replace with function body.\n}\n"; return s; +} #else +String CSharpLanguage::make_function(const String &, const String &, const PoolStringArray &) const { return String(); -#endif } +#endif String CSharpLanguage::_get_indentation() const { #ifdef TOOLS_ENABLED @@ -822,6 +825,49 @@ void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) { } #endif +void CSharpLanguage::project_assembly_loaded() { + + scripts_metadata.clear(); + + String scripts_metadata_filename = "scripts_metadata."; + +#ifdef TOOLS_ENABLED + scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player"; +#else +#ifdef DEBUG_ENABLED + scripts_metadata_filename += "debug"; +#else + scripts_metadata_filename += "release"; +#endif +#endif + + String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename); + + if (FileAccess::exists(scripts_metadata_path)) { + String old_json; + + Error ferr = read_all_file_utf8(scripts_metadata_path, old_json); + ERR_FAIL_COND(ferr != OK); + + Variant old_dict_var; + String err_str; + int err_line; + Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line); + if (json_err != OK) { + ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ")"); + return; + } + + scripts_metadata = old_dict_var.operator Dictionary(); + + print_verbose("Successfully loaded scripts metadata"); + } else { + if (!Engine::get_singleton()->is_editor_hint()) { + ERR_PRINT("Missing scripts metadata file"); + } + } +} + void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("cs"); @@ -1407,6 +1453,8 @@ bool CSharpInstance::_unreference_owner_unsafe() { if (!unsafe_referenced) return false; // Already unreferenced + unsafe_referenced = false; + // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance() // Unsafe refcount decrement. The managed instance also counts as a reference. @@ -2208,10 +2256,27 @@ bool CSharpScript::can_instance() const { #endif #ifdef TOOLS_ENABLED - return valid && (tool || ScriptServer::is_scripting_enabled()); + bool extra_cond = tool || ScriptServer::is_scripting_enabled(); #else - return valid; + bool extra_cond = true; #endif + + // FIXME Need to think this through better. + // For tool scripts, this will never fire if the class is not found. That's because we + // don't know if it's a tool script if we can't find the class to access the attributes. + if (extra_cond && !script_class) { + if (GDMono::get_singleton()->get_project_assembly() == NULL) { + // The project assembly is not loaded + ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path()); + ERR_FAIL_V(NULL); + } else { + // The project assembly is loaded, but the class could not found + ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path()); + ERR_FAIL_V(NULL); + } + } + + return valid && extra_cond; } StringName CSharpScript::get_instance_base_type() const { @@ -2317,20 +2382,6 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) { CRASH_COND(!valid); #endif - if (!script_class) { - if (GDMono::get_singleton()->get_project_assembly() == NULL) { - // The project assembly is not loaded - ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path()); - ERR_FAIL_V(NULL); - } else { - // The project assembly is loaded, but the class could not found - ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path()); - ERR_FAIL_V(NULL); - } - } - - ERR_FAIL_COND_V(!valid, NULL); - if (native) { String native_name = native->get_name(); if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) { @@ -2418,7 +2469,23 @@ Error CSharpScript::reload(bool p_keep_state) { GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly(); if (project_assembly) { - script_class = project_assembly->get_object_derived_class(name); + const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path()); + if (script_metadata_var) { + Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"]; + const Variant *namespace_ = script_metadata.getptr("namespace"); + const Variant *class_name = script_metadata.getptr("class_name"); + ERR_FAIL_NULL_V(namespace_, ERR_BUG); + ERR_FAIL_NULL_V(class_name, ERR_BUG); + GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String()); + if (klass) { + bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass); + ERR_FAIL_COND_V(!obj_type, ERR_BUG); + script_class = klass; + } + } else { + // Missing script metadata. Fallback to legacy method + script_class = project_assembly->get_object_derived_class(name); + } valid = script_class != NULL; @@ -2546,29 +2613,14 @@ int CSharpScript::get_member_line(const StringName &p_member) const { Error CSharpScript::load_source_code(const String &p_path) { - PoolVector<uint8_t> sourcef; - Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - ERR_FAIL_COND_V(err != OK, err); - - int len = f->get_len(); - sourcef.resize(len + 1); - PoolVector<uint8_t>::Write w = sourcef.write(); - int r = f->get_buffer(w.ptr(), len); - f->close(); - memdelete(f); - ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); - w[len] = 0; - - String s; - if (s.parse_utf8((const char *)w.ptr())) { - - ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); - ERR_FAIL_V(ERR_INVALID_DATA); + Error ferr = read_all_file_utf8(p_path, source); + if (ferr != OK) { + if (ferr == ERR_INVALID_DATA) { + ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); + } + ERR_FAIL_V(ferr); } - source = s; - #ifdef TOOLS_ENABLED source_changed_cache = true; #endif diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 8b0a095890..fc604df2a0 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -67,7 +67,7 @@ class CSharpScript : public Script { friend class CSharpInstance; friend class CSharpLanguage; - friend class CSharpScriptDepSort; + friend struct CSharpScriptDepSort; bool tool; bool valid; @@ -275,6 +275,8 @@ class CSharpLanguage : public ScriptLanguage { int lang_idx; + Dictionary scripts_metadata; + public: StringNameCache string_names; @@ -295,6 +297,10 @@ public: void reload_assemblies_if_needed(bool p_soft_reload); #endif + void project_assembly_loaded(); + + _FORCE_INLINE_ const Dictionary &get_scripts_metadata() { return scripts_metadata; } + virtual String get_name() const; /* LANGUAGE FUNCTIONS */ diff --git a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj b/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj index fceb732426..f9e9f41977 100644 --- a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj +++ b/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj @@ -31,6 +31,9 @@ <Reference Include="System" /> <Reference Include="Microsoft.Build" /> <Reference Include="Microsoft.Build.Framework" /> + <Reference Include="DotNet.Glob, Version=2.1.1.0, Culture=neutral, PublicKeyToken=b68cc888b4f632d1, processorArchitecture=MSIL"> + <HintPath>packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath> + </Reference> </ItemGroup> <ItemGroup> <Compile Include="StringExtensions.cs" /> @@ -43,5 +46,8 @@ <Compile Include="Utils\OS.cs" /> <Compile Include="Editor\GodotSharpExport.cs" /> </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> </Project>
\ No newline at end of file diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs b/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs index f00ec5a2ad..647d9ac81d 100644 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs +++ b/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs @@ -1,4 +1,5 @@ using System; +using DotNet.Globbing; using Microsoft.Build.Construction; namespace GodotSharpTools.Project @@ -7,7 +8,10 @@ namespace GodotSharpTools.Project { public static bool HasItem(this ProjectRootElement root, string itemType, string include) { - string includeNormalized = include.NormalizePath(); + GlobOptions globOptions = new GlobOptions(); + globOptions.Evaluation.CaseInsensitive = false; + + string normalizedInclude = include.NormalizePath(); foreach (var itemGroup in root.ItemGroups) { @@ -16,10 +20,14 @@ namespace GodotSharpTools.Project foreach (var item in itemGroup.Items) { - if (item.ItemType == itemType) + if (item.ItemType != itemType) + continue; + + var glob = Glob.Parse(item.Include.NormalizePath(), globOptions); + + if (glob.IsMatch(normalizedInclude)) { - if (item.Include.NormalizePath() == includeNormalized) - return true; + return true; } } } diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs b/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs index 1d863e6f61..574b711b29 100644 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs +++ b/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs @@ -6,6 +6,9 @@ namespace GodotSharpTools.Project { public static class ProjectGenerator { + const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}"; + const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}"; + public static string GenCoreApiProject(string dir, string[] compileItems) { string path = Path.Combine(dir, CoreApiProject + ".csproj"); @@ -15,6 +18,7 @@ namespace GodotSharpTools.Project mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml")); mainGroup.SetProperty("RootNamespace", "Godot"); + mainGroup.SetProperty("ProjectGuid", CoreApiProjectGuid); GenAssemblyInfoFile(root, dir, CoreApiProject, new string[] { "[assembly: InternalsVisibleTo(\"" + EditorApiProject + "\")]" }, @@ -39,6 +43,7 @@ namespace GodotSharpTools.Project mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml")); mainGroup.SetProperty("RootNamespace", "Godot"); + mainGroup.SetProperty("ProjectGuid", EditorApiProjectGuid); GenAssemblyInfoFile(root, dir, EditorApiProject); diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs b/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs index 6889ea715f..a13f4fd6ef 100644 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs +++ b/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs @@ -1,5 +1,6 @@ -using System; +using System.Collections.Generic; using System.IO; +using DotNet.Globbing; using Microsoft.Build.Construction; namespace GodotSharpTools.Project @@ -10,8 +11,61 @@ namespace GodotSharpTools.Project { var dir = Directory.GetParent(projectPath).FullName; var root = ProjectRootElement.Open(projectPath); - if (root.AddItemChecked(itemType, include.RelativeToPath(dir).Replace("/", "\\"))) + var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\"); + + if (root.AddItemChecked(itemType, normalizedInclude)) root.Save(); } + + private static string[] GetAllFilesRecursive(string rootDirectory, string mask) + { + string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories); + + // We want relative paths + for (int i = 0; i < files.Length; i++) { + files[i] = files[i].RelativeToPath(rootDirectory); + } + + return files; + } + + public static string[] GetIncludeFiles(string projectPath, string itemType) + { + var result = new List<string>(); + var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs"); + + GlobOptions globOptions = new GlobOptions(); + globOptions.Evaluation.CaseInsensitive = false; + + var root = ProjectRootElement.Open(projectPath); + + foreach (var itemGroup in root.ItemGroups) + { + if (itemGroup.Condition.Length != 0) + continue; + + foreach (var item in itemGroup.Items) + { + if (item.ItemType != itemType) + continue; + + string normalizedInclude = item.Include.NormalizePath(); + + var glob = Glob.Parse(normalizedInclude, globOptions); + + // TODO Check somehow if path has no blog to avoid the following loop... + + foreach (var existingFile in existingFiles) + { + if (glob.IsMatch(existingFile)) + { + result.Add(existingFile); + } + } + } + } + + return result.ToArray(); + } } } diff --git a/modules/mono/editor/GodotSharpTools/StringExtensions.cs b/modules/mono/editor/GodotSharpTools/StringExtensions.cs index b66c86f8ce..b0436d2f18 100644 --- a/modules/mono/editor/GodotSharpTools/StringExtensions.cs +++ b/modules/mono/editor/GodotSharpTools/StringExtensions.cs @@ -36,7 +36,9 @@ namespace GodotSharpTools public static bool IsAbsolutePath(this string path) { - return path.StartsWith("/") || path.StartsWith("\\") || path.StartsWith(driveRoot); + return path.StartsWith("/", StringComparison.Ordinal) || + path.StartsWith("\\", StringComparison.Ordinal) || + path.StartsWith(driveRoot, StringComparison.Ordinal); } public static string CsvEscape(this string value, char delimiter = ',') diff --git a/modules/mono/editor/GodotSharpTools/packages.config b/modules/mono/editor/GodotSharpTools/packages.config new file mode 100644 index 0000000000..2c7cb0bd4b --- /dev/null +++ b/modules/mono/editor/GodotSharpTools/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="DotNet.Glob" version="2.1.1" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/modules/mono/editor/csharp_project.cpp b/modules/mono/editor/csharp_project.cpp index 6f223b75a3..ab96356d6d 100644 --- a/modules/mono/editor/csharp_project.cpp +++ b/modules/mono/editor/csharp_project.cpp @@ -30,11 +30,15 @@ #include "csharp_project.h" +#include "core/io/json.h" #include "core/os/os.h" #include "core/project_settings.h" +#include "../csharp_script.h" #include "../mono_gd/gd_mono_class.h" #include "../mono_gd/gd_mono_marshal.h" +#include "../utils/string_utils.h" +#include "script_class_parser.h" namespace CSharpProject { @@ -118,4 +122,110 @@ void add_item(const String &p_project_path, const String &p_item_type, const Str ERR_FAIL(); } } + +Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path) { + + _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) + + GDMonoClass *project_utils = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectUtils"); + + void *args[2] = { + GDMonoMarshal::mono_string_from_godot(p_project_path), + GDMonoMarshal::mono_string_from_godot("Compile") + }; + + MonoException *exc = NULL; + MonoArray *ret = (MonoArray *)project_utils->get_method("GetIncludeFiles", 2)->invoke_raw(NULL, args, &exc); + + if (exc) { + GDMonoUtils::debug_print_unhandled_exception(exc); + ERR_FAIL_V(FAILED); + } + + PoolStringArray project_files = GDMonoMarshal::mono_array_to_PoolStringArray(ret); + PoolStringArray::Read r = project_files.read(); + + Dictionary old_dict = CSharpLanguage::get_singleton()->get_scripts_metadata(); + Dictionary new_dict; + + for (int i = 0; i < project_files.size(); i++) { + const String &project_file = ("res://" + r[i]).simplify_path(); + + uint64_t modified_time = FileAccess::get_modified_time(project_file); + + const Variant *old_file_var = old_dict.getptr(project_file); + if (old_file_var) { + Dictionary old_file_dict = old_file_var->operator Dictionary(); + + if (old_file_dict["modified_time"].operator uint64_t() == modified_time) { + // No changes so no need to parse again + new_dict[project_file] = old_file_dict; + continue; + } + } + + ScriptClassParser scp; + Error err = scp.parse_file(project_file); + if (err != OK) { + ERR_PRINTS("Parse error: " + scp.get_error()); + ERR_EXPLAIN("Failed to determine namespace and class for script: " + project_file); + ERR_FAIL_V(err); + } + + Vector<ScriptClassParser::ClassDecl> classes = scp.get_classes(); + + bool found = false; + Dictionary class_dict; + + String search_name = project_file.get_file().get_basename(); + + for (int j = 0; j < classes.size(); j++) { + const ScriptClassParser::ClassDecl &class_decl = classes[j]; + + if (class_decl.base.size() == 0) + continue; // Does not inherit nor implement anything, so it can't be a script class + + String class_cmp; + + if (class_decl.nested) { + class_cmp = class_decl.name.get_slice(".", class_decl.name.get_slice_count(".") - 1); + } else { + class_cmp = class_decl.name; + } + + if (class_cmp != search_name) + continue; + + class_dict["namespace"] = class_decl.namespace_; + class_dict["class_name"] = class_decl.name; + class_dict["nested"] = class_decl.nested; + + found = true; + break; + } + + if (found) { + Dictionary file_dict; + file_dict["modified_time"] = modified_time; + file_dict["class"] = class_dict; + new_dict[project_file] = file_dict; + } + } + + if (new_dict.size()) { + String json = JSON::print(new_dict, "", false); + + Error ferr; + FileAccess *f = FileAccess::open(p_output_path, FileAccess::WRITE, &ferr); + ERR_EXPLAIN("Cannot open file for writing: " + p_output_path); + ERR_FAIL_COND_V(ferr != OK, ferr); + f->store_string(json); + f->flush(); + f->close(); + memdelete(f); + } + + return OK; +} + } // namespace CSharpProject diff --git a/modules/mono/editor/csharp_project.h b/modules/mono/editor/csharp_project.h index d852139de0..aeeeff50f0 100644 --- a/modules/mono/editor/csharp_project.h +++ b/modules/mono/editor/csharp_project.h @@ -40,6 +40,9 @@ String generate_editor_api_project(const String &p_dir, const String &p_core_dll String generate_game_project(const String &p_dir, const String &p_name, const Vector<String> &p_files = Vector<String>()); void add_item(const String &p_project_path, const String &p_item_type, const String &p_include); + +Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path); + } // namespace CSharpProject #endif // CSHARP_PROJECT_H diff --git a/modules/mono/editor/godotsharp_builds.cpp b/modules/mono/editor/godotsharp_builds.cpp index b504cfe712..6216213716 100644 --- a/modules/mono/editor/godotsharp_builds.cpp +++ b/modules/mono/editor/godotsharp_builds.cpp @@ -39,6 +39,7 @@ #include "../mono_gd/gd_mono_marshal.h" #include "../utils/path_utils.h" #include "bindings_generator.h" +#include "csharp_project.h" #include "godotsharp_editor.h" #define PROP_NAME_MSBUILD_MONO "MSBuild (Mono)" @@ -268,7 +269,7 @@ bool GodotSharpBuilds::copy_api_assembly(const String &p_src_dir, const String & if (!FileAccess::exists(assembly_dst) || FileAccess::get_modified_time(assembly_src) > FileAccess::get_modified_time(assembly_dst) || GDMono::get_singleton()->metadata_is_api_assembly_invalidated(p_api_type)) { - DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String xml_file = p_assembly_name + ".xml"; if (da->copy(p_src_dir.plus_file(xml_file), p_dst_dir.plus_file(xml_file)) != OK) @@ -280,8 +281,6 @@ bool GodotSharpBuilds::copy_api_assembly(const String &p_src_dir, const String & Error err = da->copy(assembly_src, assembly_dst); - memdelete(da); - if (err != OK) { show_build_error_dialog("Failed to copy " + assembly_file); return false; @@ -398,6 +397,18 @@ bool GodotSharpBuilds::build_project_blocking(const String &p_config) { bool GodotSharpBuilds::editor_build_callback() { + String scripts_metadata_path_editor = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor"); + String scripts_metadata_path_player = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor_player"); + + Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path_editor); + ERR_FAIL_COND_V(metadata_err != OK, false); + + DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Error copy_err = da->copy(scripts_metadata_path_editor, scripts_metadata_path_player); + + ERR_EXPLAIN("Failed to copy scripts metadata file"); + ERR_FAIL_COND_V(copy_err != OK, false); + return build_project_blocking("Tools"); } diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp index 933ede93dc..509ec961fb 100644 --- a/modules/mono/editor/godotsharp_export.cpp +++ b/modules/mono/editor/godotsharp_export.cpp @@ -37,6 +37,7 @@ #include "../godotsharp_dirs.h" #include "../mono_gd/gd_mono_class.h" #include "../mono_gd/gd_mono_marshal.h" +#include "csharp_project.h" #include "godotsharp_builds.h" static MonoString *godot_icall_GodotSharpExport_GetTemplatesDir() { @@ -86,6 +87,12 @@ void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug String build_config = p_debug ? "Debug" : "Release"; + String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata." + String(p_debug ? "debug" : "release")); + Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path); + ERR_FAIL_COND(metadata_err != OK); + + ERR_FAIL_COND(!_add_file(scripts_metadata_path, scripts_metadata_path)); + ERR_FAIL_COND(!GodotSharpBuilds::build_project_blocking(build_config)); // Add dependency assemblies @@ -124,7 +131,7 @@ void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug for (Map<String, String>::Element *E = dependencies.front(); E; E = E->next()) { String depend_src_path = E->value(); String depend_dst_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(depend_src_path.get_file()); - ERR_FAIL_COND(!_add_assembly(depend_src_path, depend_dst_path)); + ERR_FAIL_COND(!_add_file(depend_src_path, depend_dst_path)); } // Mono specific export template extras (data dir) @@ -155,7 +162,7 @@ void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug } } -bool GodotSharpExport::_add_assembly(const String &p_src_path, const String &p_dst_path) { +bool GodotSharpExport::_add_file(const String &p_src_path, const String &p_dst_path, bool p_remap) { FileAccessRef f = FileAccess::open(p_src_path, FileAccess::READ); ERR_FAIL_COND_V(!f, false); @@ -164,7 +171,7 @@ bool GodotSharpExport::_add_assembly(const String &p_src_path, const String &p_d data.resize(f->get_len()); f->get_buffer(data.ptrw(), data.size()); - add_file(p_dst_path, data, false); + add_file(p_dst_path, data, p_remap); return true; } @@ -191,21 +198,21 @@ Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, c if (has_extension) { path = search_dir.plus_file(ref_name); if (FileAccess::exists(path)) { - GDMono::get_singleton()->load_assembly_from(ref_name.get_basename(), search_dir, ref_aname, &ref_assembly, true); + GDMono::get_singleton()->load_assembly_from(ref_name.get_basename(), path, &ref_assembly, true); if (ref_assembly != NULL) break; } } else { path = search_dir.plus_file(ref_name + ".dll"); if (FileAccess::exists(path)) { - GDMono::get_singleton()->load_assembly_from(ref_name, search_dir, ref_aname, &ref_assembly, true); + GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true); if (ref_assembly != NULL) break; } path = search_dir.plus_file(ref_name + ".exe"); if (FileAccess::exists(path)) { - GDMono::get_singleton()->load_assembly_from(ref_name, search_dir, ref_aname, &ref_assembly, true); + GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true); if (ref_assembly != NULL) break; } diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h index f007016578..10d4375567 100644 --- a/modules/mono/editor/godotsharp_export.h +++ b/modules/mono/editor/godotsharp_export.h @@ -41,7 +41,7 @@ class GodotSharpExport : public EditorExportPlugin { MonoAssemblyName *aname_prealloc; - bool _add_assembly(const String &p_src_path, const String &p_dst_path); + bool _add_file(const String &p_src_path, const String &p_dst_path, bool p_remap = false); Error _get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies); diff --git a/modules/mono/editor/mono_bottom_panel.cpp b/modules/mono/editor/mono_bottom_panel.cpp index 0ac59a1be8..d7bfa54aba 100644 --- a/modules/mono/editor/mono_bottom_panel.cpp +++ b/modules/mono/editor/mono_bottom_panel.cpp @@ -31,6 +31,8 @@ #include "mono_bottom_panel.h" #include "../csharp_script.h" +#include "../godotsharp_dirs.h" +#include "csharp_project.h" #include "godotsharp_editor.h" MonoBottomPanel *MonoBottomPanel::singleton = NULL; @@ -148,6 +150,10 @@ void MonoBottomPanel::_errors_toggled(bool p_pressed) { void MonoBottomPanel::_build_project_pressed() { + String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor"); + Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path); + ERR_FAIL_COND(metadata_err != OK); + GodotSharpBuilds::get_singleton()->build_project_blocking("Tools"); MonoReloadNode::get_singleton()->restart_reload_timer(); diff --git a/modules/mono/editor/net_solution.cpp b/modules/mono/editor/net_solution.cpp index 8bbd376c9a..a000debe52 100644 --- a/modules/mono/editor/net_solution.cpp +++ b/modules/mono/editor/net_solution.cpp @@ -52,7 +52,7 @@ #define PROJECT_DECLARATION "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"%0\", \"%1\", \"{%2}\"\nEndProject" -#define SOLUTION_PLATFORMS_CONFIG "\t\%0|Any CPU = %0|Any CPU" +#define SOLUTION_PLATFORMS_CONFIG "\t%0|Any CPU = %0|Any CPU" #define PROJECT_PLATFORMS_CONFIG \ "\t\t{%0}.%1|Any CPU.ActiveCfg = %1|Any CPU\n" \ diff --git a/modules/mono/editor/script_class_parser.cpp b/modules/mono/editor/script_class_parser.cpp new file mode 100644 index 0000000000..bc8eed81cf --- /dev/null +++ b/modules/mono/editor/script_class_parser.cpp @@ -0,0 +1,542 @@ +#include "script_class_parser.h" + +#include "core/map.h" +#include "core/os/os.h" + +#include "../utils/string_utils.h" + +const char *ScriptClassParser::token_names[ScriptClassParser::TK_MAX] = { + "[", + "]", + "{", + "}", + ".", + ":", + ",", + "Symbol", + "Identifier", + "String", + "Number", + "<", + ">", + "EOF", + "Error" +}; + +String ScriptClassParser::get_token_name(ScriptClassParser::Token p_token) { + + ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>"); + return token_names[p_token]; +} + +ScriptClassParser::Token ScriptClassParser::get_token() { + + while (true) { + switch (code[idx]) { + case '\n': { + line++; + idx++; + break; + }; + case 0: { + return TK_EOF; + } break; + case '{': { + idx++; + return TK_CURLY_BRACKET_OPEN; + }; + case '}': { + idx++; + return TK_CURLY_BRACKET_CLOSE; + }; + case '[': { + idx++; + return TK_BRACKET_OPEN; + }; + case ']': { + idx++; + return TK_BRACKET_CLOSE; + }; + case '<': { + idx++; + return TK_OP_LESS; + }; + case '>': { + idx++; + return TK_OP_GREATER; + }; + case ':': { + idx++; + return TK_COLON; + }; + case ',': { + idx++; + return TK_COMMA; + }; + case '.': { + idx++; + return TK_PERIOD; + }; + case '#': { + //compiler directive + while (code[idx] != '\n' && code[idx] != 0) { + idx++; + } + continue; + } break; + case '/': { + switch (code[idx + 1]) { + case '*': { // block comment + idx += 2; + while (true) { + if (code[idx] == 0) { + error_str = "Unterminated comment"; + error = true; + return TK_ERROR; + } else if (code[idx] == '*' && code[idx + 1] == '/') { + idx += 2; + break; + } else if (code[idx] == '\n') { + line++; + } + + idx++; + } + + } break; + case '/': { // line comment skip + while (code[idx] != '\n' && code[idx] != 0) { + idx++; + } + + } break; + default: { + value = "/"; + idx++; + return TK_SYMBOL; + } + } + + continue; // a comment + } break; + case '\'': + case '"': { + bool verbatim = idx != 0 && code[idx - 1] == '@'; + + CharType begin_str = code[idx]; + idx++; + String tk_string = String(); + while (true) { + if (code[idx] == 0) { + error_str = "Unterminated String"; + error = true; + return TK_ERROR; + } else if (code[idx] == begin_str) { + if (verbatim && code[idx + 1] == '"') { // `""` is verbatim string's `\"` + idx += 2; // skip next `"` as well + continue; + } + + idx += 1; + break; + } else if (code[idx] == '\\' && !verbatim) { + //escaped characters... + idx++; + CharType next = code[idx]; + if (next == 0) { + error_str = "Unterminated String"; + error = true; + return TK_ERROR; + } + CharType res = 0; + + switch (next) { + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'f': res = 12; break; + case 'r': + res = 13; + break; + case '\"': res = '\"'; break; + case '\\': + res = '\\'; + break; + default: { + res = next; + } break; + } + + tk_string += res; + + } else { + if (code[idx] == '\n') + line++; + tk_string += code[idx]; + } + idx++; + } + + value = tk_string; + + return TK_STRING; + } break; + default: { + if (code[idx] <= 32) { + idx++; + break; + } + + if ((code[idx] >= 33 && code[idx] <= 47) || (code[idx] >= 58 && code[idx] <= 63) || (code[idx] >= 91 && code[idx] <= 94) || code[idx] == 96 || (code[idx] >= 123 && code[idx] <= 127)) { + value = String::chr(code[idx]); + idx++; + return TK_SYMBOL; + } + + if (code[idx] == '-' || (code[idx] >= '0' && code[idx] <= '9')) { + //a number + const CharType *rptr; + double number = String::to_double(&code[idx], &rptr); + idx += (rptr - &code[idx]); + value = number; + return TK_NUMBER; + + } else if ((code[idx] == '@' && code[idx + 1] != '"') || code[idx] == '_' || (code[idx] >= 'A' && code[idx] <= 'Z') || (code[idx] >= 'a' && code[idx] <= 'z') || code[idx] > 127) { + String id; + + id += code[idx]; + idx++; + + while (code[idx] == '_' || (code[idx] >= 'A' && code[idx] <= 'Z') || (code[idx] >= 'a' && code[idx] <= 'z') || (code[idx] >= '0' && code[idx] <= '9') || code[idx] > 127) { + id += code[idx]; + idx++; + } + + value = id; + return TK_IDENTIFIER; + } else if (code[idx] == '@' && code[idx + 1] == '"') { + // begin of verbatim string + idx++; + } else { + error_str = "Unexpected character."; + error = true; + return TK_ERROR; + } + } + } + } +} + +Error ScriptClassParser::_skip_generic_type_params() { + + Token tk; + + while (true) { + tk = get_token(); + + if (tk == TK_IDENTIFIER) { + tk = get_token(); + + if (tk == TK_PERIOD) { + while (true) { + tk = get_token(); + + if (tk != TK_IDENTIFIER) { + error_str = "Expected " + get_token_name(TK_IDENTIFIER) + ", found: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + + tk = get_token(); + + if (tk != TK_PERIOD) + break; + } + } + + if (tk == TK_OP_LESS) { + Error err = _skip_generic_type_params(); + if (err) + return err; + continue; + } else if (tk != TK_COMMA) { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + } else if (tk == TK_OP_LESS) { + error_str = "Expected " + get_token_name(TK_IDENTIFIER) + ", found " + get_token_name(TK_OP_LESS); + error = true; + return ERR_PARSE_ERROR; + } else if (tk == TK_OP_GREATER) { + return OK; + } else { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + } +} + +Error ScriptClassParser::_parse_type_full_name(String &r_full_name) { + + Token tk = get_token(); + + if (tk != TK_IDENTIFIER) { + error_str = "Expected " + get_token_name(TK_IDENTIFIER) + ", found: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + + r_full_name += String(value); + + if (code[idx] != '.') // We only want to take the next token if it's a period + return OK; + + tk = get_token(); + + CRASH_COND(tk != TK_PERIOD); // Assertion + + r_full_name += "."; + + return _parse_type_full_name(r_full_name); +} + +Error ScriptClassParser::_parse_class_base(Vector<String> &r_base) { + + String name; + + Error err = _parse_type_full_name(name); + if (err) + return err; + + Token tk = get_token(); + + if (tk == TK_OP_LESS) { + // We don't add it to the base list if it's generic + Error err = _skip_generic_type_params(); + if (err) + return err; + } else if (tk == TK_COMMA) { + Error err = _parse_class_base(r_base); + if (err) + return err; + r_base.push_back(name); + } else if (tk == TK_CURLY_BRACKET_OPEN) { + r_base.push_back(name); + } else { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + + return OK; +} + +Error ScriptClassParser::_parse_namespace_name(String &r_name, int &r_curly_stack) { + + Token tk = get_token(); + + if (tk == TK_IDENTIFIER) { + r_name += String(value); + } else { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + + tk = get_token(); + + if (tk == TK_PERIOD) { + r_name += "."; + return _parse_namespace_name(r_name, r_curly_stack); + } else if (tk == TK_CURLY_BRACKET_OPEN) { + r_curly_stack++; + return OK; + } else { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } +} + +Error ScriptClassParser::parse(const String &p_code) { + + code = p_code; + idx = 0; + line = 0; + error_str = String(); + error = false; + value = Variant(); + classes.clear(); + + Token tk = get_token(); + + Map<int, NameDecl> name_stack; + int curly_stack = 0; + int type_curly_stack = 0; + + while (!error && tk != TK_EOF) { + if (tk == TK_IDENTIFIER && String(value) == "class") { + tk = get_token(); + + if (tk == TK_IDENTIFIER) { + String name = value; + int at_level = type_curly_stack; + + ClassDecl class_decl; + + for (Map<int, NameDecl>::Element *E = name_stack.front(); E; E = E->next()) { + const NameDecl &name_decl = E->value(); + + if (name_decl.type == NameDecl::NAMESPACE_DECL) { + if (E != name_stack.front()) + class_decl.namespace_ += "."; + class_decl.namespace_ += name_decl.name; + } else { + class_decl.name += name_decl.name + "."; + } + } + + class_decl.name += name; + class_decl.nested = type_curly_stack > 0; + + bool generic = false; + + while (true) { + tk = get_token(); + + if (tk == TK_COLON) { + Error err = _parse_class_base(class_decl.base); + if (err) + return err; + + curly_stack++; + type_curly_stack++; + + break; + } else if (tk == TK_CURLY_BRACKET_OPEN) { + curly_stack++; + type_curly_stack++; + break; + } else if (tk == TK_OP_LESS && !generic) { + generic = true; + + Error err = _skip_generic_type_params(); + if (err) + return err; + } else { + error_str = "Unexpected token: " + get_token_name(tk); + error = true; + return ERR_PARSE_ERROR; + } + } + + NameDecl name_decl; + name_decl.name = name; + name_decl.type = NameDecl::CLASS_DECL; + name_stack[at_level] = name_decl; + + if (!generic) { // no generics, thanks + classes.push_back(class_decl); + } else if (OS::get_singleton()->is_stdout_verbose()) { + String full_name = class_decl.namespace_; + if (full_name.length()) + full_name += "."; + full_name += class_decl.name; + OS::get_singleton()->print(String("Ignoring generic class declaration: " + class_decl.name).utf8()); + } + } + } else if (tk == TK_IDENTIFIER && String(value) == "struct") { + String name; + int at_level = type_curly_stack; + while (true) { + tk = get_token(); + if (tk == TK_IDENTIFIER && name.empty()) { + name = String(value); + } else if (tk == TK_CURLY_BRACKET_OPEN) { + if (name.empty()) { + error_str = "Expected " + get_token_name(TK_IDENTIFIER) + " after keyword `struct`, found " + get_token_name(TK_CURLY_BRACKET_OPEN); + error = true; + return ERR_PARSE_ERROR; + } + + curly_stack++; + type_curly_stack++; + break; + } else if (tk == TK_EOF) { + error_str = "Expected " + get_token_name(TK_CURLY_BRACKET_OPEN) + " after struct decl, found " + get_token_name(TK_EOF); + error = true; + return ERR_PARSE_ERROR; + } + } + + NameDecl name_decl; + name_decl.name = name; + name_decl.type = NameDecl::STRUCT_DECL; + name_stack[at_level] = name_decl; + } else if (tk == TK_IDENTIFIER && String(value) == "namespace") { + if (type_curly_stack > 0) { + error_str = "Found namespace nested inside type."; + error = true; + return ERR_PARSE_ERROR; + } + + String name; + int at_level = curly_stack; + + Error err = _parse_namespace_name(name, curly_stack); + if (err) + return err; + + NameDecl name_decl; + name_decl.name = name; + name_decl.type = NameDecl::NAMESPACE_DECL; + name_stack[at_level] = name_decl; + } else if (tk == TK_CURLY_BRACKET_OPEN) { + curly_stack++; + } else if (tk == TK_CURLY_BRACKET_CLOSE) { + curly_stack--; + if (name_stack.has(curly_stack)) { + if (name_stack[curly_stack].type != NameDecl::NAMESPACE_DECL) + type_curly_stack--; + name_stack.erase(curly_stack); + } + } + + tk = get_token(); + } + + if (!error && tk == TK_EOF && curly_stack > 0) { + error_str = "Reached EOF with missing close curly brackets."; + error = true; + } + + if (error) + return ERR_PARSE_ERROR; + + return OK; +} + +Error ScriptClassParser::parse_file(const String &p_filepath) { + + String source; + + Error ferr = read_all_file_utf8(p_filepath, source); + if (ferr != OK) { + if (ferr == ERR_INVALID_DATA) { + ERR_EXPLAIN("File '" + p_filepath + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); + } + ERR_FAIL_V(ferr); + } + + return parse(source); +} + +String ScriptClassParser::get_error() { + return error_str; +} + +Vector<ScriptClassParser::ClassDecl> ScriptClassParser::get_classes() { + return classes; +} diff --git a/modules/mono/editor/script_class_parser.h b/modules/mono/editor/script_class_parser.h new file mode 100644 index 0000000000..1e174c28a9 --- /dev/null +++ b/modules/mono/editor/script_class_parser.h @@ -0,0 +1,79 @@ +#ifndef SCRIPT_CLASS_PARSER_H +#define SCRIPT_CLASS_PARSER_H + +#include "core/ustring.h" +#include "core/variant.h" +#include "core/vector.h" + +class ScriptClassParser { + +public: + struct NameDecl { + enum Type { + NAMESPACE_DECL, + CLASS_DECL, + STRUCT_DECL + }; + + String name; + Type type; + }; + + struct ClassDecl { + String name; + String namespace_; + Vector<String> base; + bool nested; + bool has_script_attr; + }; + +private: + String code; + int idx; + int line; + String error_str; + bool error; + Variant value; + + Vector<ClassDecl> classes; + + enum Token { + TK_BRACKET_OPEN, + TK_BRACKET_CLOSE, + TK_CURLY_BRACKET_OPEN, + TK_CURLY_BRACKET_CLOSE, + TK_PERIOD, + TK_COLON, + TK_COMMA, + TK_SYMBOL, + TK_IDENTIFIER, + TK_STRING, + TK_NUMBER, + TK_OP_LESS, + TK_OP_GREATER, + TK_EOF, + TK_ERROR, + TK_MAX + }; + + static const char *token_names[TK_MAX]; + static String get_token_name(Token p_token); + + Token get_token(); + + Error _skip_generic_type_params(); + + Error _parse_type_full_name(String &r_full_name); + Error _parse_class_base(Vector<String> &r_base); + Error _parse_namespace_name(String &r_name, int &r_curly_stack); + +public: + Error parse(const String &p_code); + Error parse_file(const String &p_filepath); + + String get_error(); + + Vector<ClassDecl> get_classes(); +}; + +#endif // SCRIPT_CLASS_PARSER_H diff --git a/modules/mono/glue/Managed/Files/GD.cs b/modules/mono/glue/Managed/Files/GD.cs index e4818e186c..8c1a5a6ee8 100644 --- a/modules/mono/glue/Managed/Files/GD.cs +++ b/modules/mono/glue/Managed/Files/GD.cs @@ -70,6 +70,16 @@ namespace Godot return ResourceLoader.Load<T>(path); } + public static void LogError(string message) + { + godot_icall_GD_logerror(message); + } + + public static void LogWarning(string message) + { + godot_icall_GD_logwarning(message); + } + public static void Print(params object[] what) { godot_icall_GD_print(what); @@ -238,5 +248,11 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_var2str(object var); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static void godot_icall_GD_logerror(string type); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static void godot_icall_GD_logwarning(string type); } } diff --git a/modules/mono/glue/gd_glue.cpp b/modules/mono/glue/gd_glue.cpp index 051f42b966..6a5430489e 100644 --- a/modules/mono/glue/gd_glue.cpp +++ b/modules/mono/glue/gd_glue.cpp @@ -157,6 +157,14 @@ bool godot_icall_GD_type_exists(MonoString *p_type) { return ClassDB::class_exists(GDMonoMarshal::mono_string_to_godot(p_type)); } +void godot_icall_GD_logerror(MonoString *p_str) { + ERR_PRINTS(GDMonoMarshal::mono_string_to_godot(p_str)); +} + +void godot_icall_GD_logwarning(MonoString *p_str) { + WARN_PRINTS(GDMonoMarshal::mono_string_to_godot(p_str)); +} + MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var) { Variant var = GDMonoMarshal::mono_object_to_variant(p_var); @@ -186,6 +194,8 @@ void godot_register_gd_icalls() { mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert); mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash); mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id); + mono_add_internal_call("Godot.GD::godot_icall_GD_logerror", (void *)godot_icall_GD_logerror); + mono_add_internal_call("Godot.GD::godot_icall_GD_logwarning", (void *)godot_icall_GD_logwarning); mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print); mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr); mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw); diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 0c4433112d..c3feafee28 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -191,7 +191,6 @@ void GDMono::initialize() { String hint_config_dir = path_join(locations[i], "etc"); if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) { - need_set_mono_dirs = false; assembly_rootdir = hint_assembly_rootdir; config_dir = hint_config_dir; break; @@ -378,34 +377,24 @@ GDMonoAssembly **GDMono::get_loaded_assembly(const String &p_name) { bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) { - return load_assembly_from(p_name, String(), r_assembly, p_refonly); -} - -bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) { - - return load_assembly_from(p_name, String(), p_aname, r_assembly, p_refonly); -} - -bool GDMono::load_assembly_from(const String &p_name, const String &p_basedir, GDMonoAssembly **r_assembly, bool p_refonly) { - CRASH_COND(!r_assembly); MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8()); - bool result = load_assembly_from(p_name, p_basedir, aname, r_assembly, p_refonly); + bool result = load_assembly(p_name, aname, r_assembly, p_refonly); mono_assembly_name_free(aname); mono_free(aname); return result; } -bool GDMono::load_assembly_from(const String &p_name, const String &p_basedir, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) { +bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) { CRASH_COND(!r_assembly); print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "..."); MonoImageOpenStatus status = MONO_IMAGE_OK; - MonoAssembly *assembly = mono_assembly_load_full(p_aname, p_basedir.length() ? p_basedir.utf8().get_data() : NULL, &status, p_refonly); + MonoAssembly *assembly = mono_assembly_load_full(p_aname, NULL, &status, p_refonly); if (!assembly) return false; @@ -426,6 +415,32 @@ bool GDMono::load_assembly_from(const String &p_name, const String &p_basedir, M return true; } +bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) { + + CRASH_COND(!r_assembly); + + print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "..."); + + GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly); + + if (!assembly) + return false; + +#ifdef DEBUG_ENABLED + uint32_t domain_id = mono_domain_get_id(mono_domain_get()); + GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name); + + ERR_FAIL_COND_V(stored_assembly == NULL, false); + ERR_FAIL_COND_V(*stored_assembly != assembly, false); +#endif + + *r_assembly = assembly; + + print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path()); + + return true; +} + APIAssembly::Version APIAssembly::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, APIAssembly::Type p_api_type) { APIAssembly::Version api_assembly_version; @@ -481,7 +496,14 @@ bool GDMono::_load_core_api_assembly() { } #endif - bool success = load_assembly(API_ASSEMBLY_NAME, &core_api_assembly); + String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(API_ASSEMBLY_NAME ".dll"); + + if (!FileAccess::exists(assembly_path)) + return false; + + bool success = load_assembly_from(API_ASSEMBLY_NAME, + assembly_path, + &core_api_assembly); if (success) { #ifdef MONO_GLUE_ENABLED @@ -511,7 +533,14 @@ bool GDMono::_load_editor_api_assembly() { return false; } - bool success = load_assembly(EDITOR_API_ASSEMBLY_NAME, &editor_api_assembly); + String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); + + if (!FileAccess::exists(assembly_path)) + return false; + + bool success = load_assembly_from(EDITOR_API_ASSEMBLY_NAME, + assembly_path, + &editor_api_assembly); if (success) { #ifdef MONO_GLUE_ENABLED @@ -552,6 +581,8 @@ bool GDMono::_load_project_assembly() { if (success) { mono_assembly_set_main(project_assembly->get_assembly()); + + CSharpLanguage::get_singleton()->project_assembly_loaded(); } else { if (OS::get_singleton()->is_stdout_verbose()) print_error("Mono: Failed to load project assembly"); diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index 745dcc34eb..fd9551b6de 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -199,8 +199,7 @@ public: bool load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly = false); bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly = false); - bool load_assembly_from(const String &p_name, const String &p_basedir, GDMonoAssembly **r_assembly, bool p_refonly = false); - bool load_assembly_from(const String &p_name, const String &p_basedir, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly = false); + bool load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly = false); Error finalize_and_unload_domain(MonoDomain *p_domain); diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 1067c11e0e..72b0204672 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -457,6 +457,20 @@ GDMonoClass *GDMonoAssembly::get_object_derived_class(const StringName &p_class) return match; } +GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_path, bool p_refonly) { + + GDMonoAssembly **loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name); + if (loaded_asm) + return *loaded_asm; +#ifdef DEBUG_ENABLED + CRASH_COND(!FileAccess::exists(p_path)); +#endif + no_search = true; + GDMonoAssembly *res = _load_assembly_from(p_name, p_path, p_refonly); + no_search = false; + return res; +} + GDMonoAssembly::GDMonoAssembly(const String &p_name, const String &p_path) { loaded = false; diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h index 4c9b1cb10d..2af40ec901 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.h +++ b/modules/mono/mono_gd/gd_mono_assembly.h @@ -128,6 +128,8 @@ public: static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String()); + static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly); + GDMonoAssembly(const String &p_name, const String &p_path = String()); ~GDMonoAssembly(); }; diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp index b4c78df538..fa1fbebb16 100644 --- a/modules/mono/signal_awaiter_utils.cpp +++ b/modules/mono/signal_awaiter_utils.cpp @@ -141,7 +141,7 @@ SignalAwaiterHandle::~SignalAwaiterHandle() { if (exc) { GDMonoUtils::set_pending_exception(exc); - ERR_FAIL_V(); + ERR_FAIL(); } } } diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index 8691932f9a..6900866725 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -30,6 +30,8 @@ #include "string_utils.h" +#include "core/os/file_access.h" + namespace { int sfind(const String &p_text, int p_from) { @@ -128,6 +130,7 @@ String sformat(const String &p_text, const Variant &p1, const Variant &p2, const return new_string; } +#ifdef TOOLS_ENABLED bool is_csharp_keyword(const String &p_name) { // Reserved keywords @@ -156,3 +159,28 @@ bool is_csharp_keyword(const String &p_name) { String escape_csharp_keyword(const String &p_name) { return is_csharp_keyword(p_name) ? "@" + p_name : p_name; } +#endif + +Error read_all_file_utf8(const String &p_path, String &r_content) { + PoolVector<uint8_t> sourcef; + Error err; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + ERR_FAIL_COND_V(err != OK, err); + + int len = f->get_len(); + sourcef.resize(len + 1); + PoolVector<uint8_t>::Write w = sourcef.write(); + int r = f->get_buffer(w.ptr(), len); + f->close(); + memdelete(f); + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); + w[len] = 0; + + String source; + if (source.parse_utf8((const char *)w.ptr())) { + ERR_FAIL_V(ERR_INVALID_DATA); + } + + r_content = source; + return OK; +} diff --git a/modules/mono/utils/string_utils.h b/modules/mono/utils/string_utils.h index f2df2340ae..ee803bd720 100644 --- a/modules/mono/utils/string_utils.h +++ b/modules/mono/utils/string_utils.h @@ -42,4 +42,6 @@ bool is_csharp_keyword(const String &p_name); String escape_csharp_keyword(const String &p_name); #endif +Error read_all_file_utf8(const String &p_path, String &r_content); + #endif // STRING_FORMAT_H diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml index d88abb3180..ba54160a90 100644 --- a/modules/opensimplex/doc_classes/NoiseTexture.xml +++ b/modules/opensimplex/doc_classes/NoiseTexture.xml @@ -17,6 +17,9 @@ <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap"> If true, the resulting texture contains a normal map created from the original noise interpreted as a bump map. </member> + <member name="height" type="int" setter="set_height" getter="get_height"> + Height of the generated texture. + </member> <member name="noise" type="OpenSimplexNoise" setter="set_noise" getter="get_noise"> The [OpenSimplexNoise] instance used to generate the noise. </member> @@ -26,9 +29,6 @@ <member name="width" type="int" setter="set_width" getter="get_width"> Width of the generated texture. </member> - <member name="height" type="int" setter="set_height" getter="get_height"> - Height of the generated texture. - </member> </members> <constants> </constants> diff --git a/modules/recast/navigation_mesh_editor_plugin.cpp b/modules/recast/navigation_mesh_editor_plugin.cpp index 98351fbaee..d121a82d9e 100644 --- a/modules/recast/navigation_mesh_editor_plugin.cpp +++ b/modules/recast/navigation_mesh_editor_plugin.cpp @@ -103,24 +103,25 @@ void NavigationMeshEditor::_bind_methods() { NavigationMeshEditor::NavigationMeshEditor() { bake_hbox = memnew(HBoxContainer); + button_bake = memnew(ToolButton); - button_bake->set_text(TTR("Bake!")); + bake_hbox->add_child(button_bake); button_bake->set_toggle_mode(true); - button_reset = memnew(Button); - button_bake->set_tooltip(TTR("Bake the navigation mesh.") + "\n"); + button_bake->set_text(TTR("Bake NavMesh")); + button_bake->connect("pressed", this, "_bake_pressed"); - bake_info = memnew(Label); - bake_hbox->add_child(button_bake); + button_reset = memnew(ToolButton); bake_hbox->add_child(button_reset); + // No button text, we only use a revert icon which is set when entering the tree. + button_reset->set_tooltip(TTR("Clear the navigation mesh.")); + button_reset->connect("pressed", this, "_clear_pressed"); + + bake_info = memnew(Label); bake_hbox->add_child(bake_info); err_dialog = memnew(AcceptDialog); add_child(err_dialog); node = NULL; - - button_bake->connect("pressed", this, "_bake_pressed"); - button_reset->connect("pressed", this, "_clear_pressed"); - button_reset->set_tooltip(TTR("Clear the navigation mesh.")); } NavigationMeshEditor::~NavigationMeshEditor() { diff --git a/modules/recast/navigation_mesh_editor_plugin.h b/modules/recast/navigation_mesh_editor_plugin.h index 4f3e222002..914d9ab8b9 100644 --- a/modules/recast/navigation_mesh_editor_plugin.h +++ b/modules/recast/navigation_mesh_editor_plugin.h @@ -43,8 +43,8 @@ class NavigationMeshEditor : public Control { AcceptDialog *err_dialog; HBoxContainer *bake_hbox; - Button *button_bake; - Button *button_reset; + ToolButton *button_bake; + ToolButton *button_reset; Label *bake_info; NavigationMeshInstance *node; diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 52a30baaec..186e9e63b1 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -2699,11 +2699,11 @@ VisualScriptLanguage::VisualScriptLanguage() { _debug_parse_err_file = ""; _debug_call_stack_pos = 0; int dmcs = GLOBAL_DEF("debug/settings/visual_script/max_call_stack", 1024); + ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/visual_script/max_call_stack", PropertyInfo(Variant::INT, "debug/settings/visual_script/max_call_stack", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); //minimum is 1024 + if (ScriptDebugger::get_singleton()) { //debugging enabled! _debug_max_call_stack = dmcs; - if (_debug_max_call_stack < 1024) - _debug_max_call_stack = 1024; _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1); } else { diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 7fdd7fe446..a80a015ed3 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -3018,11 +3018,15 @@ void VisualScriptEditor::_node_filter_changed(const String &p_text) { void VisualScriptEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_READY) { + if (p_what == NOTIFICATION_READY || (p_what == NOTIFICATION_THEME_CHANGED && is_visible_in_tree())) { + node_filter->set_right_icon(Control::get_icon("Search", "EditorIcons")); node_filter->set_clear_button_enabled(true); - variable_editor->connect("changed", this, "_update_members"); - signal_editor->connect("changed", this, "_update_members"); + + if (p_what == NOTIFICATION_READY) { + variable_editor->connect("changed", this, "_update_members"); + signal_editor->connect("changed", this, "_update_members"); + } Ref<Theme> tm = EditorNode::get_singleton()->get_theme_base()->get_theme(); @@ -3056,8 +3060,12 @@ void VisualScriptEditor::_notification(int p_what) { node_styles[E->get().first] = frame_style; } } - } - if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { + + if (is_visible_in_tree()) { + _update_members(); + _update_graph(); + } + } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { left_vsplit->set_visible(is_visible_in_tree()); } } diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp index ad4a758c0f..db02162699 100644 --- a/modules/websocket/emws_server.cpp +++ b/modules/websocket/emws_server.cpp @@ -71,6 +71,9 @@ int EMWSServer::get_peer_port(int p_peer_id) const { void EMWSServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) { } +void EMWSServer::poll() { +} + EMWSServer::EMWSServer() { } diff --git a/modules/websocket/lws_client.cpp b/modules/websocket/lws_client.cpp index add3931b50..d71d091720 100644 --- a/modules/websocket/lws_client.cpp +++ b/modules/websocket/lws_client.cpp @@ -34,10 +34,6 @@ #include "core/io/stream_peer_ssl.h" #include "tls/mbedtls/wrapper/include/openssl/ssl.h" -#if defined(MINGW_ENABLED) || defined(_MSC_VER) -#define strncpy strncpy_s -#endif - Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) { ERR_FAIL_COND_V(context != NULL, FAILED); @@ -80,26 +76,11 @@ Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, ERR_FAIL_V(FAILED); } - char abuf[1024]; - char hbuf[1024]; - char pbuf[2048]; - String addr_str = (String)addr; - strncpy(abuf, addr_str.ascii().get_data(), 1023); - abuf[1023] = '\0'; - strncpy(hbuf, p_host.utf8().get_data(), 1023); - hbuf[1023] = '\0'; - strncpy(pbuf, p_path.utf8().get_data(), 2047); - pbuf[2047] = '\0'; - i.context = context; if (p_protocols.size() > 0) i.protocol = _lws_ref->lws_names; else i.protocol = NULL; - i.address = abuf; - i.host = hbuf; - i.path = pbuf; - i.port = p_port; if (p_ssl) { i.ssl_connection = LCCSCF_USE_SSL; @@ -109,7 +90,16 @@ Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, i.ssl_connection = 0; } + // This String needs to survive till we call lws_client_connect_via_info + String addr_str = (String)addr; + + i.address = addr_str.ascii().get_data(); + i.host = p_host.utf8().get_data(); + i.path = p_path.utf8().get_data(); + i.port = p_port; + lws_client_connect_via_info(&i); + return OK; }; diff --git a/platform/android/build.gradle.template b/platform/android/build.gradle.template index 1603ea70d9..18ffc74fc3 100644 --- a/platform/android/build.gradle.template +++ b/platform/android/build.gradle.template @@ -14,9 +14,9 @@ apply plugin: 'com.android.application' allprojects { repositories { - jcenter() mavenCentral() google() + jcenter() $$GRADLE_REPOSITORY_URLS$$ } } diff --git a/platform/android/detect.py b/platform/android/detect.py index 953a2fa6d2..e4cab2fb23 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -186,7 +186,7 @@ def configure(env): env.PrependENVPath('PATH', tools_path) ccache_path = os.environ.get("CCACHE") - if ccache_path == None: + if ccache_path is None: env['CC'] = compiler_path + '/clang' env['CXX'] = compiler_path + '/clang++' else: @@ -293,7 +293,7 @@ def configure(env): # Return NDK version string in source.properties (adapted from the Chromium project). def get_ndk_version(path): - if path == None: + if path is None: return None prop_file_path = os.path.join(path, "source.properties") try: diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index 3b503e2657..edb84cce07 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -395,7 +395,7 @@ class EditorExportAndroid : public EditorExportPlatform { return aname; } - String get_package_name(const String &p_package) { + String get_package_name(const String &p_package) const { String pname = p_package; String basename = ProjectSettings::get_singleton()->get("application/config/name"); @@ -420,6 +420,70 @@ class EditorExportAndroid : public EditorExportPlatform { return pname; } + bool is_package_name_valid(const String &p_package, String *r_error = NULL) const { + + String pname = p_package; + + if (pname.length() == 0) { + if (r_error) { + *r_error = "Package name is missing."; + } + return false; + } + + int segments = 0; + bool first = true; + for (int i = 0; i < pname.length(); i++) { + CharType c = pname[i]; + if (first && c == '.') { + if (r_error) { + *r_error = "Package segments must be of non-zero length."; + } + return false; + } + if (c == '.') { + segments++; + first = true; + continue; + } + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) { + if (r_error) { + *r_error = "The character '" + String::chr(c) + "' is not allowed in Android application package names."; + } + return false; + } + if (first && (c >= '0' && c <= '9')) { + if (r_error) { + *r_error = "A digit cannot be the first character in a package segment."; + } + return false; + } + if (first && c == '_') { + if (r_error) { + *r_error = "The character '" + String::chr(c) + "' cannot be the first character in a package segment."; + } + return false; + } + first = false; + } + + if (segments == 0) { + if (r_error) { + *r_error = "The package must have at least one '.' separator."; + } + return false; + } + + if (first) { + if (r_error) { + *r_error = "Package segments must be of non-zero length."; + } + return false; + } + + return true; + } + static bool _should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) { /* @@ -1382,6 +1446,15 @@ public: } } + String pn = p_preset->get("package/unique_name"); + String pn_err; + + if (!is_package_name_valid(get_package_name(pn), &pn_err)) { + + valid = false; + err += "Invalid package name - " + pn_err + "\n"; + } + r_error = err; return valid; } diff --git a/platform/android/java/src/org/godotengine/godot/Godot.java b/platform/android/java/src/org/godotengine/godot/Godot.java index ab37f7a02c..88194f00d1 100644 --- a/platform/android/java/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/src/org/godotengine/godot/Godot.java @@ -279,7 +279,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC // ...add to FrameLayout layout.addView(edittext); - mView = new GodotView(getApplication(), io, use_gl3, use_32_bits, use_debug_opengl,this); + mView = new GodotView(getApplication(), io, use_gl3, use_32_bits, use_debug_opengl, this); layout.addView(mView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); edittext.setView(mView); io.setEdit(edittext); diff --git a/platform/android/java/src/org/godotengine/godot/GodotView.java b/platform/android/java/src/org/godotengine/godot/GodotView.java index 181ffc3b4b..4cb4db33de 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotView.java +++ b/platform/android/java/src/org/godotengine/godot/GodotView.java @@ -86,7 +86,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { private Godot activity; private InputManagerCompat mInputManager; - public GodotView(Context context, GodotIO p_io, boolean p_use_gl3, boolean p_use_32_bits, boolean p_use_debug_opengl,Godot p_activity) { + public GodotView(Context context, GodotIO p_io, boolean p_use_gl3, boolean p_use_32_bits, boolean p_use_debug_opengl, Godot p_activity) { super(context); ctx = context; io = p_io; @@ -204,48 +204,65 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { return i; } } - onInputDeviceAdded(device_id); - return joy_devices.size() - 1; + + return -1; } @Override public void onInputDeviceAdded(int deviceId) { - joystick joy = new joystick(); - joy.device_id = deviceId; - final int id = joy_devices.size(); - InputDevice device = mInputManager.getInputDevice(deviceId); - final String name = device.getName(); - joy.name = device.getName(); - joy.axes = new ArrayList<InputDevice.MotionRange>(); - joy.hats = new ArrayList<InputDevice.MotionRange>(); - List<InputDevice.MotionRange> ranges = device.getMotionRanges(); - Collections.sort(ranges, new RangeComparator()); - for (InputDevice.MotionRange range : ranges) { - if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) { - joy.hats.add(range); - } else { - joy.axes.add(range); + int id = find_joy_device(deviceId); + + // Check if the device has not been already added + if (id < 0) { + InputDevice device = mInputManager.getInputDevice(deviceId); + + id = joy_devices.size(); + + joystick joy = new joystick(); + joy.device_id = deviceId; + joy.name = device.getName(); + joy.axes = new ArrayList<InputDevice.MotionRange>(); + joy.hats = new ArrayList<InputDevice.MotionRange>(); + + List<InputDevice.MotionRange> ranges = device.getMotionRanges(); + Collections.sort(ranges, new RangeComparator()); + + for (InputDevice.MotionRange range : ranges) { + if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) { + joy.hats.add(range); + } else { + joy.axes.add(range); + } } + + joy_devices.add(joy); + + final int device_id = id; + final String name = joy.name; + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joyconnectionchanged(device_id, true, name); + } + }); } - joy_devices.add(joy); - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joyconnectionchanged(id, true, name); - } - }); } @Override public void onInputDeviceRemoved(int deviceId) { - final int id = find_joy_device(deviceId); - joy_devices.remove(id); - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joyconnectionchanged(id, false, ""); - } - }); + final int device_id = find_joy_device(deviceId); + + // Check if the evice has not been already removed + if (device_id > -1) { + joy_devices.remove(device_id); + + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joyconnectionchanged(device_id, false, ""); + } + }); + } } @Override @@ -266,15 +283,18 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { if ((source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK || (source & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD || (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) { final int button = get_godot_button(keyCode); - final int device = find_joy_device(event.getDeviceId()); + final int device_id = find_joy_device(event.getDeviceId()); - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joybutton(device, button, false); - } - }); - return true; + // Check if the device exists + if (device_id > -1) { + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joybutton(device_id, button, false); + } + }); + return true; + } } else { final int chr = event.getUnicodeChar(0); queueEvent(new Runnable() { @@ -284,6 +304,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { } }); }; + return super.onKeyUp(keyCode, event); }; @@ -308,18 +329,20 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { if (event.getRepeatCount() > 0) // ignore key echo return true; - final int button = get_godot_button(keyCode); - final int device = find_joy_device(event.getDeviceId()); - //Log.e(TAG, String.format("joy button down! button %x, %d, device %d", keyCode, button, device)); - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joybutton(device, button, true); - } - }); - return true; + final int button = get_godot_button(keyCode); + final int device_id = find_joy_device(event.getDeviceId()); + // Check if the device exists + if (device_id > -1) { + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joybutton(device_id, button, true); + } + }); + return true; + } } else { final int chr = event.getUnicodeChar(0); queueEvent(new Runnable() { @@ -329,6 +352,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { } }); }; + return super.onKeyDown(keyCode, event); } @@ -338,33 +362,35 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && event.getAction() == MotionEvent.ACTION_MOVE) { final int device_id = find_joy_device(event.getDeviceId()); - joystick joy = joy_devices.get(device_id); - for (int i = 0; i < joy.axes.size(); i++) { - InputDevice.MotionRange range = joy.axes.get(i); - final float value = (event.getAxisValue(range.getAxis()) - range.getMin()) / range.getRange() * 2.0f - 1.0f; - //Log.e(TAG, String.format("axis event: %d, value %f", i, value)); - final int idx = i; - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joyaxis(device_id, idx, value); - } - }); - } + // Check if the device exists + if (device_id > -1) { + joystick joy = joy_devices.get(device_id); + + for (int i = 0; i < joy.axes.size(); i++) { + InputDevice.MotionRange range = joy.axes.get(i); + final float value = (event.getAxisValue(range.getAxis()) - range.getMin()) / range.getRange() * 2.0f - 1.0f; + final int idx = i; + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joyaxis(device_id, idx, value); + } + }); + } - for (int i = 0; i < joy.hats.size(); i += 2) { - final int hatX = Math.round(event.getAxisValue(joy.hats.get(i).getAxis())); - final int hatY = Math.round(event.getAxisValue(joy.hats.get(i + 1).getAxis())); - //Log.e(TAG, String.format("HAT EVENT %d, %d", hatX, hatY)); - queueEvent(new Runnable() { - @Override - public void run() { - GodotLib.joyhat(device_id, hatX, hatY); - } - }); + for (int i = 0; i < joy.hats.size(); i += 2) { + final int hatX = Math.round(event.getAxisValue(joy.hats.get(i).getAxis())); + final int hatY = Math.round(event.getAxisValue(joy.hats.get(i + 1).getAxis())); + queueEvent(new Runnable() { + @Override + public void run() { + GodotLib.joyhat(device_id, hatX, hatY); + } + }); + } + return true; } - return true; }; return super.onGenericMotionEvent(event); @@ -408,9 +434,9 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { setRenderer(new Renderer()); } - private static final int _EGL_CONTEXT_FLAGS_KHR = 0x30FC; - private static final int _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR= 0x00000001; - + private static final int _EGL_CONTEXT_FLAGS_KHR = 0x30FC; + private static final int _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR = 0x00000001; + private static class ContextFactory implements GLSurfaceView.EGLContextFactory { private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) { @@ -422,9 +448,9 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { checkEglError("Before eglCreateContext", egl); EGLContext context; if (use_debug_opengl) { - int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2,_EGL_CONTEXT_FLAGS_KHR,_EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE }; - int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3,_EGL_CONTEXT_FLAGS_KHR,_EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE }; - context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, use_gl3 ? attrib_list3 : attrib_list2); + int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE }; + int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE }; + context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, use_gl3 ? attrib_list3 : attrib_list2); } else { int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE }; int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE }; diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp index 30bc413459..abbd9c9aa7 100644 --- a/platform/android/os_android.cpp +++ b/platform/android/os_android.cpp @@ -39,7 +39,7 @@ #include "file_access_android.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" -//#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/visual/visual_server_wrap_mt.h" #ifdef ANDROID_NATIVE_ACTIVITY #include "dir_access_android.h" @@ -182,11 +182,12 @@ Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int video_driver_index = p_video_driver; - visual_server = memnew(VisualServerRaster); - /* if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { + if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, false)); - };*/ + } else { + visual_server = memnew(VisualServerRaster); + } visual_server->init(); // visual_server->cursor_set_visible(false, 0); @@ -586,7 +587,7 @@ Error OS_Android::shell_open(String p_uri) { String OS_Android::get_resource_dir() const { - return "/"; //android has it's own filesystem for resources inside the APK + return "/"; //android has its own filesystem for resources inside the APK } String OS_Android::get_locale() const { diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp index c80365f1f3..a4a32c939c 100644 --- a/platform/haiku/os_haiku.cpp +++ b/platform/haiku/os_haiku.cpp @@ -117,16 +117,15 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p #endif - visual_server = memnew(VisualServerRaster()); - - ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); - - // TODO: enable multithreaded VS - /* + // FIXME: Reimplement threaded rendering? Or remove? if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + + visual_server = memnew(VisualServerWrapMT(visual_server, false)); + } else { + visual_server = memnew(VisualServerRaster); } - */ + + ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); video_driver_index = p_video_driver; diff --git a/platform/iphone/detect.py b/platform/iphone/detect.py index b13a1e9643..417571f6f3 100644 --- a/platform/iphone/detect.py +++ b/platform/iphone/detect.py @@ -87,7 +87,7 @@ def configure(env): s_compiler_path = '$IPHONEPATH/Developer/usr/bin/' ccache_path = os.environ.get("CCACHE") - if ccache_path == None: + if ccache_path is None: env['CC'] = compiler_path + 'clang' env['CXX'] = compiler_path + 'clang++' env['S_compiler'] = s_compiler_path + 'gcc' diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp index addef61ec7..d0934d8e9d 100644 --- a/platform/iphone/os_iphone.cpp +++ b/platform/iphone/os_iphone.cpp @@ -34,7 +34,7 @@ #include "drivers/gles3/rasterizer_gles3.h" #include "servers/visual/visual_server_raster.h" -//#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/visual/visual_server_wrap_mt.h" #include "main/main.h" @@ -107,13 +107,12 @@ Error OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); - visual_server = memnew(VisualServerRaster()); - /* - FIXME: Reimplement threaded rendering? Or remove? + // FIXME: Reimplement threaded rendering? Or remove? if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, false)); - }; - */ + } else { + visual_server = memnew(VisualServerRaster); + } visual_server->init(); //visual_server->cursor_set_visible(false, 0); diff --git a/platform/javascript/detect.py b/platform/javascript/detect.py index 17b31f8d73..cf85c3df7f 100644 --- a/platform/javascript/detect.py +++ b/platform/javascript/detect.py @@ -128,6 +128,10 @@ def configure(env): # us since we don't know requirements at compile-time. env.Append(LINKFLAGS=['-s', 'ALLOW_MEMORY_GROWTH=1']) + # Since we use both memory growth and MEMFS preloading, + # this avoids unecessary copying on start-up. + env.Append(LINKFLAGS=['--no-heap-copy']) + # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1. env.Append(LINKFLAGS=['-s', 'USE_WEBGL2=1']) diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp index 7c7aeac980..9250ca4903 100644 --- a/platform/javascript/os_javascript.cpp +++ b/platform/javascript/os_javascript.cpp @@ -862,6 +862,24 @@ void OS_JavaScript::finalize() { // Miscellaneous +Error OS_JavaScript::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr) { + + ERR_EXPLAIN("OS::execute() is not available on the HTML5 platform"); + ERR_FAIL_V(ERR_UNAVAILABLE); +} + +Error OS_JavaScript::kill(const ProcessID &p_pid) { + + ERR_EXPLAIN("OS::kill() is not available on the HTML5 platform"); + ERR_FAIL_V(ERR_UNAVAILABLE); +} + +int OS_JavaScript::get_process_id() const { + + ERR_EXPLAIN("OS::get_process_id() is not available on the HTML5 platform"); + ERR_FAIL_V(0); +} + extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) { if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) { diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index 84075898ac..79dac5940f 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -133,6 +133,10 @@ public: void run_async(); bool main_loop_iterate(); + virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL, bool read_stderr = false); + virtual Error kill(const ProcessID &p_pid); + virtual int get_process_id() const; + virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); virtual void set_window_title(const String &p_title); virtual void set_icon(const Ref<Image> &p_icon); diff --git a/platform/osx/detect.py b/platform/osx/detect.py index 8a0883eca3..c5bd64b15c 100644 --- a/platform/osx/detect.py +++ b/platform/osx/detect.py @@ -89,7 +89,7 @@ def configure(env): basecmd = root + "/target/bin/x86_64-apple-" + env["osxcross_sdk"] + "-" ccache_path = os.environ.get("CCACHE") - if ccache_path == None: + if ccache_path is None: env['CC'] = basecmd + "cc" env['CXX'] = basecmd + "c++" else: diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h index 6fd52f09d1..546c88e74a 100644 --- a/platform/osx/os_osx.h +++ b/platform/osx/os_osx.h @@ -74,8 +74,12 @@ public: IP_Unix *ip_unix; +#ifdef COREAUDIO_ENABLED AudioDriverCoreAudio audio_driver; +#endif +#ifdef COREMIDI_ENABLED MIDIDriverCoreMidi midi_driver; +#endif InputDefault *input; JoypadOSX *joypad_osx; diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index 6ab433203f..cbdec92b90 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -100,12 +100,13 @@ static int prev_mouse_y = 0; static int button_mask = 0; static bool mouse_down_control = false; -static Vector2 get_mouse_pos(NSEvent *event) { +static Vector2 get_mouse_pos(NSPoint locationInWindow, CGFloat backingScaleFactor) { const NSRect contentRect = [OS_OSX::singleton->window_view frame]; - const NSPoint p = [event locationInWindow]; - mouse_x = p.x * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); - mouse_y = (contentRect.size.height - p.y) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); + const NSPoint p = locationInWindow; + const float s = OS_OSX::singleton->_mouse_scale(backingScaleFactor); + mouse_x = p.x * s; + mouse_y = (contentRect.size.height - p.y) * s; return Vector2(mouse_x, mouse_y); } @@ -325,6 +326,14 @@ static Vector2 get_mouse_pos(NSEvent *event) { - (void)windowDidBecomeKey:(NSNotification *)notification { //_GodotInputWindowFocus(window, GL_TRUE); //_GodotPlatformSetCursorMode(window, window->cursorMode); + [OS_OSX::singleton->context update]; + + get_mouse_pos( + [OS_OSX::singleton->window_object mouseLocationOutsideOfEventStream], + [OS_OSX::singleton->window_view backingScaleFactor]); + if (OS_OSX::singleton->input) + OS_OSX::singleton->input->set_mouse_position(Point2(mouse_x, mouse_y)); + if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); } @@ -593,12 +602,13 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { mm->set_button_mask(button_mask); prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; - const Vector2 pos = get_mouse_pos(event); + const CGFloat backingScaleFactor = [[event window] backingScaleFactor]; + const Vector2 pos = get_mouse_pos([event locationInWindow], backingScaleFactor); mm->set_position(pos); mm->set_global_position(pos); Vector2 relativeMotion = Vector2(); - relativeMotion.x = [event deltaX] * OS_OSX::singleton -> _mouse_scale([[event window] backingScaleFactor]); - relativeMotion.y = [event deltaY] * OS_OSX::singleton -> _mouse_scale([[event window] backingScaleFactor]); + relativeMotion.x = [event deltaX] * OS_OSX::singleton -> _mouse_scale(backingScaleFactor); + relativeMotion.y = [event deltaY] * OS_OSX::singleton -> _mouse_scale(backingScaleFactor); mm->set_relative(relativeMotion); get_key_modifier_state([event modifierFlags], mm); @@ -681,7 +691,7 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { Ref<InputEventMagnifyGesture> ev; ev.instance(); get_key_modifier_state([event modifierFlags], ev); - ev->set_position(get_mouse_pos(event)); + ev->set_position(get_mouse_pos([event locationInWindow], [[event window] backingScaleFactor])); ev->set_factor([event magnification] + 1.0); OS_OSX::singleton->push_input(ev); } @@ -1073,6 +1083,8 @@ inline void sendPanEvent(double dx, double dy, int modifierFlags) { - (void)scrollWheel:(NSEvent *)event { double deltaX, deltaY; + get_mouse_pos([event locationInWindow], [[event window] backingScaleFactor]); + deltaX = [event scrollingDeltaX]; deltaY = [event scrollingDeltaY]; @@ -1371,10 +1383,11 @@ Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_a video_driver_index = p_video_driver; - visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + } else { + visual_server = memnew(VisualServerRaster); } visual_server->init(); @@ -1397,7 +1410,9 @@ Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_a void OS_OSX::finalize() { +#ifdef COREMIDI_ENABLED midi_driver.close(); +#endif CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL); CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL); @@ -2714,7 +2729,9 @@ OS_OSX::OS_OSX() { [NSApp sendEvent:event]; } +#ifdef COREAUDIO_ENABLED AudioDriverManager::add_driver(&audio_driver); +#endif } bool OS_OSX::_check_internal_feature_support(const String &p_feature) { diff --git a/platform/server/SCsub b/platform/server/SCsub index c9082f9b3a..51fd05a87e 100644 --- a/platform/server/SCsub +++ b/platform/server/SCsub @@ -1,10 +1,21 @@ #!/usr/bin/env python +import os +import platform +import sys + Import('env') common_server = [\ "os_server.cpp",\ - "#platform/x11/crash_handler_x11.cpp", - "#platform/x11/power_x11.cpp", ] + +if sys.platform == "darwin": + common_server.append("#platform/osx/crash_handler_osx.mm") + common_server.append("#platform/osx/power_osx.cpp") + common_server.append("#platform/osx/sem_osx.cpp") +else: + common_server.append("#platform/x11/crash_handler_x11.cpp") + common_server.append("#platform/x11/power_x11.cpp") + prog = env.add_program('#bin/godot_server', ['godot_server.cpp'] + common_server) diff --git a/platform/server/detect.py b/platform/server/detect.py index 597a2ff6a0..0b23e9c649 100644 --- a/platform/server/detect.py +++ b/platform/server/detect.py @@ -11,9 +11,15 @@ def get_name(): return "Server" +def get_program_suffix(): + if (sys.platform == "darwin"): + return "osx" + return "x11" + + def can_build(): - if (os.name != "posix" or sys.platform == "darwin"): + if (os.name != "posix"): return False return True @@ -147,6 +153,10 @@ def configure(env): env.Append(CPPPATH=['#platform/server']) env.Append(CPPFLAGS=['-DSERVER_ENABLED', '-DUNIX_ENABLED']) + + if (platform.system() == "Darwin"): + env.Append(LINKFLAGS=['-framework', 'Cocoa', '-framework', 'Carbon', '-lz', '-framework', 'IOKit']) + env.Append(LIBS=['pthread']) if (platform.system() == "Linux"): diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp index 6a7038e946..60f20d6009 100644 --- a/platform/server/os_server.cpp +++ b/platform/server/os_server.cpp @@ -68,6 +68,10 @@ void OS_Server::initialize_core() { crash_handler.initialize(); OS_Unix::initialize_core(); + +#ifdef __APPLE__ + SemaphoreOSX::make_default(); +#endif } Error OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { @@ -87,7 +91,11 @@ Error OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int input = memnew(InputDefault); +#ifdef __APPLE__ + power_manager = memnew(power_osx); +#else power_manager = memnew(PowerX11); +#endif _ensure_user_data_dir(); diff --git a/platform/server/os_server.h b/platform/server/os_server.h index 07d70e5236..0367ec3db9 100644 --- a/platform/server/os_server.h +++ b/platform/server/os_server.h @@ -34,8 +34,14 @@ #include "drivers/rtaudio/audio_driver_rtaudio.h" #include "drivers/unix/os_unix.h" #include "main/input_default.h" +#ifdef __APPLE__ +#include "platform/osx/crash_handler_osx.h" +#include "platform/osx/power_osx.h" +#include "platform/osx/sem_osx.h" +#else #include "platform/x11/crash_handler_x11.h" #include "platform/x11/power_x11.h" +#endif #include "servers/audio_server.h" #include "servers/visual/rasterizer.h" #include "servers/visual_server.h" @@ -61,7 +67,11 @@ class OS_Server : public OS_Unix { InputDefault *input; +#ifdef __APPLE__ + power_osx *power_manager; +#else PowerX11 *power_manager; +#endif CrashHandler crash_handler; diff --git a/platform/server/platform_config.h b/platform/server/platform_config.h index 2fa8eda337..26ba8f26c6 100644 --- a/platform/server/platform_config.h +++ b/platform/server/platform_config.h @@ -28,10 +28,13 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifdef __linux__ +#if defined(__linux__) || defined(__APPLE__) #include <alloca.h> #endif #if defined(__FreeBSD__) || defined(__OpenBSD__) #include <stdlib.h> #define PTHREAD_BSD_SET_NAME #endif +#ifdef __APPLE__ +#define PTHREAD_RENAME_SELF +#endif diff --git a/platform/uwp/detect.py b/platform/uwp/detect.py index 559f23ca5b..f25b9ba9cd 100644 --- a/platform/uwp/detect.py +++ b/platform/uwp/detect.py @@ -17,7 +17,7 @@ def can_build(): # building natively on windows! if (os.getenv("VSINSTALLDIR")): - if (os.getenv("ANGLE_SRC_PATH") == None): + if (os.getenv("ANGLE_SRC_PATH") is None): return False return True diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 6410378593..5de8f6539f 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -294,14 +294,13 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au set_video_mode(vm); - visual_server = memnew(VisualServerRaster); // FIXME: Reimplement threaded rendering? Or remove? - /* if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + visual_server = memnew(VisualServerWrapMT(visual_server, false)); + } else { + visual_server = memnew(VisualServerRaster); } - */ visual_server->init(); input = memnew(InputDefault); diff --git a/platform/windows/context_gl_win.cpp b/platform/windows/context_gl_win.cpp index fd7cd69c37..2d70b00dda 100644 --- a/platform/windows/context_gl_win.cpp +++ b/platform/windows/context_gl_win.cpp @@ -92,9 +92,9 @@ Error ContextGL_Win::initialize() { PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, (BYTE)PFD_TYPE_RGBA, - OS::get_singleton()->is_layered_allowed() ? (BYTE)32 : (BYTE)24, + (BYTE)(OS::get_singleton()->is_layered_allowed() ? 32 : 24), (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Color Bits Ignored - OS::get_singleton()->is_layered_allowed() ? (BYTE)8 : (BYTE)0, // Alpha Buffer + (BYTE)(OS::get_singleton()->is_layered_allowed() ? 8 : 0), // Alpha Buffer (BYTE)0, // Shift Bit Ignored (BYTE)0, // No Accumulation Buffer (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Accumulation Bits Ignored diff --git a/platform/windows/joypad.cpp b/platform/windows/joypad.cpp index 99ac0214e0..7201714fb8 100644 --- a/platform/windows/joypad.cpp +++ b/platform/windows/joypad.cpp @@ -172,7 +172,7 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) { joy->di_joy->SetDataFormat(&c_dfDIJoystick2); joy->di_joy->SetCooperativeLevel(*hWnd, DISCL_FOREGROUND); - joy->di_joy->EnumObjects(objectsCallback, this, NULL); + joy->di_joy->EnumObjects(objectsCallback, this, 0); joy->joy_axis.sort(); joy->guid = instance->guidInstance; diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index ac130ac4f2..7a543445b6 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -763,7 +763,7 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) RECT r; GetWindowRect(hWnd, &r); - dib_size = Size2(r.right - r.left, r.bottom - r.top); + dib_size = Size2i(r.right - r.left, r.bottom - r.top); BITMAPINFO bmi; ZeroMemory(&bmi, sizeof(BITMAPINFO)); @@ -773,7 +773,7 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; - bmi.bmiHeader.biSizeImage = dib_size.x, dib_size.y * 4; + bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4; hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0); SelectObject(hDC_dib, hBitmap); @@ -1050,7 +1050,6 @@ static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Defau UINT x = 0, y = 0; HRESULT hr = E_FAIL; - bool bSet = false; if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) { hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y); if (SUCCEEDED(hr) && (x > 0) && (y > 0)) { @@ -1229,7 +1228,7 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int printf("Error setting WNDPROC: %li\n", le); }; - LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC); + GetWindowLongPtr(hWnd, GWLP_WNDPROC); RECT rect; if (!GetClientRect(hWnd, &rect)) { @@ -1333,10 +1332,11 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int gl_context->set_use_vsync(video_mode.use_vsync); #endif - visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + } else { + visual_server = memnew(VisualServerRaster); } /* @@ -1728,14 +1728,18 @@ void OS_Windows::set_window_position(const Point2 &p_position) { Size2 OS_Windows::get_window_size() const { RECT r; - GetClientRect(hWnd, &r); - return Vector2(r.right - r.left, r.bottom - r.top); + if (GetClientRect(hWnd, &r)) { // Only area inside of window border + return Size2(r.right - r.left, r.bottom - r.top); + } + return Size2(); } Size2 OS_Windows::get_real_window_size() const { RECT r; - GetWindowRect(hWnd, &r); - return Vector2(r.right - r.left, r.bottom - r.top); + if (GetWindowRect(hWnd, &r)) { // Includes area of the window border + return Size2(r.right - r.left, r.bottom - r.top); + } + return Size2(); } void OS_Windows::set_window_size(const Size2 p_size) { @@ -2274,7 +2278,6 @@ void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shap ERR_FAIL_COND(!image.is_valid()); UINT image_size = texture_size.width * texture_size.height; - UINT size = sizeof(UINT) * image_size; // Create the BITMAP with alpha channel COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size); @@ -2746,11 +2749,6 @@ void OS_Windows::run() { main_loop->init(); - uint64_t last_ticks = get_ticks_usec(); - - int frames = 0; - uint64_t frame = 0; - while (!force_quit) { process_events(); // get rid of pending events diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp index 7c4c8f0eff..4fa34b1f2b 100644 --- a/platform/x11/os_x11.cpp +++ b/platform/x11/os_x11.cpp @@ -342,11 +342,12 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a context_gl->set_use_vsync(current_videomode.use_vsync); #endif - visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + } else { + visual_server = memnew(VisualServerRaster); } if (current_videomode.maximized) { current_videomode.maximized = false; @@ -2095,7 +2096,7 @@ void OS_X11::process_xevents() { last_timestamp = event.xkey.time; // key event is a little complex, so - // it will be handled in it's own function. + // it will be handled in its own function. handle_key_event((XKeyEvent *)&event); } break; case SelectionRequest: { diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp index cdb208e6cd..4276918f53 100644 --- a/scene/2d/path_2d.cpp +++ b/scene/2d/path_2d.cpp @@ -63,6 +63,10 @@ bool Path2D::_edit_use_rect() const { bool Path2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const { + if (curve.is_null()) { + return false; + } + for (int i = 0; i < curve->get_point_count(); i++) { Vector2 s[2]; s[0] = curve->get_point_position(i); diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index d0bebd3354..60074abb29 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -32,8 +32,11 @@ #include "core/core_string_names.h" #include "core/engine.h" +#include "core/list.h" #include "core/math/math_funcs.h" #include "core/method_bind_ext.gen.inc" +#include "core/object.h" +#include "core/rid.h" #include "scene/scene_string_names.h" void PhysicsBody2D::_notification(int p_what) { @@ -65,6 +68,8 @@ void PhysicsBody2D::_bind_methods() { ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody2D::_set_layers); ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody2D::_get_layers); + + ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody2D::get_collision_exceptions); ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody2D::add_collision_exception_with); ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody2D::remove_collision_exception_with); ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_2D_PHYSICS, "", 0), "_set_layers", "_get_layers"); //for backwards compat @@ -134,6 +139,20 @@ PhysicsBody2D::PhysicsBody2D(Physics2DServer::BodyMode p_mode) : set_pickable(false); } +Array PhysicsBody2D::get_collision_exceptions() { + List<RID> exceptions; + Physics2DServer::get_singleton()->body_get_collision_exceptions(get_rid(), &exceptions); + Array ret; + for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) { + RID body = E->get(); + ObjectID instance_id = Physics2DServer::get_singleton()->body_get_object_instance_id(body); + Object *obj = ObjectDB::get_instance(instance_id); + PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(obj); + ret.append(physics_body); + } + return ret; +} + void PhysicsBody2D::add_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h index 29befb0375..ddd55f7b7f 100644 --- a/scene/2d/physics_body_2d.h +++ b/scene/2d/physics_body_2d.h @@ -67,6 +67,7 @@ public: void set_collision_layer_bit(int p_bit, bool p_value); bool get_collision_layer_bit(int p_bit) const; + Array get_collision_exceptions(); void add_collision_exception_with(Node *p_node); //must be physicsbody void remove_collision_exception_with(Node *p_node); diff --git a/scene/3d/arvr_nodes.cpp b/scene/3d/arvr_nodes.cpp index 4bff26a200..2dc500f7ab 100644 --- a/scene/3d/arvr_nodes.cpp +++ b/scene/3d/arvr_nodes.cpp @@ -38,14 +38,14 @@ void ARVRCamera::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { - // need to find our ARVROrigin parent and let it know we're it's camera! + // need to find our ARVROrigin parent and let it know we're its camera! ARVROrigin *origin = Object::cast_to<ARVROrigin>(get_parent()); if (origin != NULL) { origin->set_tracked_camera(this); } }; break; case NOTIFICATION_EXIT_TREE: { - // need to find our ARVROrigin parent and let it know we're no longer it's camera! + // need to find our ARVROrigin parent and let it know we're no longer its camera! ARVROrigin *origin = Object::cast_to<ARVROrigin>(get_parent()); if (origin != NULL) { origin->clear_tracked_camera_if(this); diff --git a/scene/3d/arvr_nodes.h b/scene/3d/arvr_nodes.h index 67fb658562..d6690676cc 100644 --- a/scene/3d/arvr_nodes.h +++ b/scene/3d/arvr_nodes.h @@ -62,7 +62,7 @@ public: }; /* - ARVRController is a helper node that automatically updates it's position based on tracker data. + ARVRController is a helper node that automatically updates its position based on tracker data. It must be a child node of our ARVROrigin node */ @@ -102,7 +102,7 @@ public: }; /* - ARVRAnchor is a helper node that automatically updates it's position based on anchor data, it represents a real world location. + ARVRAnchor is a helper node that automatically updates its position based on anchor data, it represents a real world location. It must be a child node of our ARVROrigin node */ diff --git a/scene/3d/light.cpp b/scene/3d/light.cpp index 7e1d60ab8e..11d61315ba 100644 --- a/scene/3d/light.cpp +++ b/scene/3d/light.cpp @@ -163,11 +163,6 @@ void Light::_update_visibility() { if (!is_inside_tree()) return; - // FIXME: Since the call to VS::instance_light_set_enabled was disabled below, - // the whole logic became pointless so editor_ok triggers unused variable warnings. - // Commenting out for now but this should be fixed/reimplemented so that editor_only - // works as expected (GH-17989). - /* bool editor_ok = true; #ifdef TOOLS_ENABLED @@ -184,8 +179,8 @@ void Light::_update_visibility() { } #endif - //VS::get_singleton()->instance_light_set_enabled(get_instance(),is_visible_in_tree() && editor_ok); - */ + VS::get_singleton()->instance_set_visible(get_instance(), is_visible_in_tree() && editor_ok); + _change_notify("geometry/visible"); } diff --git a/scene/3d/mesh_instance.cpp b/scene/3d/mesh_instance.cpp index 4cbf6f2de3..cf0317cd58 100644 --- a/scene/3d/mesh_instance.cpp +++ b/scene/3d/mesh_instance.cpp @@ -253,6 +253,11 @@ void MeshInstance::_notification(int p_what) { } } +int MeshInstance::get_surface_material_count() const { + + return materials.size(); +} + void MeshInstance::set_surface_material(int p_surface, const Ref<Material> &p_material) { ERR_FAIL_INDEX(p_surface, materials.size()); @@ -359,6 +364,7 @@ void MeshInstance::_bind_methods() { ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path"), &MeshInstance::set_skeleton_path); ClassDB::bind_method(D_METHOD("get_skeleton_path"), &MeshInstance::get_skeleton_path); + ClassDB::bind_method(D_METHOD("get_surface_material_count"), &MeshInstance::get_surface_material_count); ClassDB::bind_method(D_METHOD("set_surface_material", "surface", "material"), &MeshInstance::set_surface_material); ClassDB::bind_method(D_METHOD("get_surface_material", "surface"), &MeshInstance::get_surface_material); diff --git a/scene/3d/mesh_instance.h b/scene/3d/mesh_instance.h index 0dfec538f9..0b5b4b9e7b 100644 --- a/scene/3d/mesh_instance.h +++ b/scene/3d/mesh_instance.h @@ -76,6 +76,7 @@ public: void set_skeleton_path(const NodePath &p_skeleton); NodePath get_skeleton_path(); + int get_surface_material_count() const; void set_surface_material(int p_surface, const Ref<Material> &p_material); Ref<Material> get_surface_material(int p_surface) const; diff --git a/scene/3d/path.cpp b/scene/3d/path.cpp index e37efa0e8a..339a434a6e 100644 --- a/scene/3d/path.cpp +++ b/scene/3d/path.cpp @@ -43,6 +43,16 @@ void Path::_curve_changed() { if (is_inside_tree()) { emit_signal("curve_changed"); } + + // update the configuration warnings of all children of type OrientedPathFollows + if (is_inside_tree()) { + for (int i = 0; i < get_child_count(); i++) { + OrientedPathFollow *child = Object::cast_to<OrientedPathFollow>(get_child(i)); + if (child) { + child->update_configuration_warning(); + } + } + } } void Path::set_curve(const Ref<Curve3D> &p_curve) { @@ -207,6 +217,18 @@ void PathFollow::_validate_property(PropertyInfo &property) const { } } +String PathFollow::get_configuration_warning() const { + + if (!is_visible_in_tree() || !is_inside_tree()) + return String(); + + if (!Object::cast_to<Path>(get_parent())) { + return TTR("PathFollow only works when set as a child of a Path node."); + } + + return String(); +} + void PathFollow::_bind_methods() { ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow::set_offset); @@ -444,6 +466,23 @@ void OrientedPathFollow::_validate_property(PropertyInfo &property) const { } } +String OrientedPathFollow::get_configuration_warning() const { + + if (!is_visible_in_tree() || !is_inside_tree()) + return String(); + + if (!Object::cast_to<Path>(get_parent())) { + return TTR("OrientedPathFollow only works when set as a child of a Path node."); + } else { + Path *path = Object::cast_to<Path>(get_parent()); + if (path->get_curve().is_valid() && !path->get_curve()->is_up_vector_enabled()) { + return TTR("OrientedPathFollow requires up vectors enabled in its parent Path."); + } + } + + return String(); +} + void OrientedPathFollow::_bind_methods() { ClassDB::bind_method(D_METHOD("set_offset", "offset"), &OrientedPathFollow::set_offset); diff --git a/scene/3d/path.h b/scene/3d/path.h index f73bf17dfe..beb37d9714 100644 --- a/scene/3d/path.h +++ b/scene/3d/path.h @@ -106,6 +106,8 @@ public: void set_cubic_interpolation(bool p_enable); bool get_cubic_interpolation() const; + String get_configuration_warning() const; + PathFollow(); }; @@ -151,6 +153,8 @@ public: void set_cubic_interpolation(bool p_enable); bool get_cubic_interpolation() const; + String get_configuration_warning() const; + OrientedPathFollow(); }; diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp index 0fb0869979..970e8cf1ee 100644 --- a/scene/3d/physics_body.cpp +++ b/scene/3d/physics_body.cpp @@ -32,7 +32,10 @@ #include "core/core_string_names.h" #include "core/engine.h" +#include "core/list.h" #include "core/method_bind_ext.gen.inc" +#include "core/object.h" +#include "core/rid.h" #include "scene/scene_string_names.h" #ifdef TOOLS_ENABLED @@ -108,6 +111,20 @@ bool PhysicsBody::get_collision_layer_bit(int p_bit) const { return get_collision_layer() & (1 << p_bit); } +Array PhysicsBody::get_collision_exceptions() { + List<RID> exceptions; + PhysicsServer::get_singleton()->body_get_collision_exceptions(get_rid(), &exceptions); + Array ret; + for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) { + RID body = E->get(); + ObjectID instance_id = PhysicsServer::get_singleton()->body_get_object_instance_id(body); + Object *obj = ObjectDB::get_instance(instance_id); + PhysicsBody *physics_body = Object::cast_to<PhysicsBody>(obj); + ret.append(physics_body); + } + return ret; +} + void PhysicsBody::add_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); @@ -289,6 +306,7 @@ void StaticBody::_bind_methods() { ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &StaticBody::_reload_physics_characteristics); + ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody::get_collision_exceptions); ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody::add_collision_exception_with); ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody::remove_collision_exception_with); @@ -2326,7 +2344,8 @@ void PhysicalBone::set_joint_type(JointType p_joint_type) { if (p_joint_type == get_joint_type()) return; - memdelete(joint_data); + if (joint_data) + memdelete(joint_data); joint_data = NULL; switch (p_joint_type) { case JOINT_TYPE_PIN: @@ -2526,7 +2545,8 @@ PhysicalBone::PhysicalBone() : } PhysicalBone::~PhysicalBone() { - memdelete(joint_data); + if (joint_data) + memdelete(joint_data); } void PhysicalBone::update_bone_id() { diff --git a/scene/3d/physics_body.h b/scene/3d/physics_body.h index ed9f41197b..fa319e6fbb 100644 --- a/scene/3d/physics_body.h +++ b/scene/3d/physics_body.h @@ -69,6 +69,7 @@ public: void set_collision_mask_bit(int p_bit, bool p_value); bool get_collision_mask_bit(int p_bit) const; + Array get_collision_exceptions(); void add_collision_exception_with(Node *p_node); //must be physicsbody void remove_collision_exception_with(Node *p_node); diff --git a/scene/3d/soft_body.cpp b/scene/3d/soft_body.cpp index 4ebc941ebc..1e730d0b3d 100644 --- a/scene/3d/soft_body.cpp +++ b/scene/3d/soft_body.cpp @@ -29,8 +29,12 @@ /*************************************************************************/ #include "soft_body.h" +#include "core/list.h" +#include "core/object.h" #include "core/os/os.h" +#include "core/rid.h" #include "scene/3d/collision_object.h" +#include "scene/3d/physics_body.h" #include "scene/3d/skeleton.h" #include "servers/physics_server.h" @@ -335,6 +339,7 @@ void SoftBody::_bind_methods() { ClassDB::bind_method(D_METHOD("set_parent_collision_ignore", "parent_collision_ignore"), &SoftBody::set_parent_collision_ignore); ClassDB::bind_method(D_METHOD("get_parent_collision_ignore"), &SoftBody::get_parent_collision_ignore); + ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &SoftBody::get_collision_exceptions); ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &SoftBody::add_collision_exception_with); ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &SoftBody::remove_collision_exception_with); @@ -547,6 +552,20 @@ PoolVector<SoftBody::PinnedPoint> SoftBody::get_pinned_points_indices() { return pinned_points; } +Array SoftBody::get_collision_exceptions() { + List<RID> exceptions; + PhysicsServer::get_singleton()->soft_body_get_collision_exceptions(physics_rid, &exceptions); + Array ret; + for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) { + RID body = E->get(); + ObjectID instance_id = PhysicsServer::get_singleton()->body_get_object_instance_id(body); + Object *obj = ObjectDB::get_instance(instance_id); + PhysicsBody *physics_body = Object::cast_to<PhysicsBody>(obj); + ret.append(physics_body); + } + return ret; +} + void SoftBody::add_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); CollisionObject *collision_object = Object::cast_to<CollisionObject>(p_node); diff --git a/scene/3d/soft_body.h b/scene/3d/soft_body.h index ee3d8d87cf..b1e699e839 100644 --- a/scene/3d/soft_body.h +++ b/scene/3d/soft_body.h @@ -166,6 +166,7 @@ public: void set_drag_coefficient(real_t p_drag_coefficient); real_t get_drag_coefficient(); + Array get_collision_exceptions(); void add_collision_exception_with(Node *p_node); void remove_collision_exception_with(Node *p_node); diff --git a/scene/3d/voxel_light_baker.cpp b/scene/3d/voxel_light_baker.cpp index 541f6047d9..0eccbbc8f9 100644 --- a/scene/3d/voxel_light_baker.cpp +++ b/scene/3d/voxel_light_baker.cpp @@ -261,7 +261,7 @@ static _FORCE_INLINE_ void get_uv_and_normal(const Vector3 &p_pos, const Vector3 void VoxelLightBaker::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector3 *p_normal, const Vector2 *p_uv, const MaterialCache &p_material, const AABB &p_aabb) { if (p_level == cell_subdiv - 1) { - //plot the face by guessing it's albedo and emission value + //plot the face by guessing its albedo and emission value //find best axis to map to, for scanning values int closest_axis = 0; diff --git a/scene/gui/gradient_edit.cpp b/scene/gui/gradient_edit.cpp index 934b84ec0c..c13964d196 100644 --- a/scene/gui/gradient_edit.cpp +++ b/scene/gui/gradient_edit.cpp @@ -236,8 +236,8 @@ void GradientEdit::_gui_input(const Ref<InputEvent> &p_event) { //Snap to nearest point if holding shift if (mm->get_shift()) { - float snap_treshhold = 0.03; - float smallest_ofs = snap_treshhold; + float snap_threshold = 0.03; + float smallest_ofs = snap_threshold; bool found = false; int nearest_point = 0; for (int i = 0; i < points.size(); ++i) { diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp index 0d5fbee9ee..494995fb85 100644 --- a/scene/gui/item_list.cpp +++ b/scene/gui/item_list.cpp @@ -1524,6 +1524,7 @@ void ItemList::_bind_methods() { ADD_SIGNAL(MethodInfo("nothing_selected")); GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000); + ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/incremental_search_max_interval_msec", PropertyInfo(Variant::INT, "gui/timers/incremental_search_max_interval_msec", PROPERTY_HINT_RANGE, "0,10000,1,or_greater")); // No negative numbers } ItemList::ItemList() { diff --git a/scene/gui/link_button.cpp b/scene/gui/link_button.cpp index d38a067fef..c1561e97ba 100644 --- a/scene/gui/link_button.cpp +++ b/scene/gui/link_button.cpp @@ -75,6 +75,7 @@ void LinkButton::_notification(int p_what) { color = get_color("font_color"); do_underline = underline_mode == UNDERLINE_MODE_ALWAYS; } break; + case DRAW_HOVER_PRESSED: case DRAW_PRESSED: { if (has_color("font_color_pressed")) @@ -91,7 +92,6 @@ void LinkButton::_notification(int p_what) { do_underline = underline_mode != UNDERLINE_MODE_NEVER; } break; - case DRAW_HOVER_PRESSED: break; // Not used in this class case DRAW_DISABLED: { color = get_color("font_color_disabled"); diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index bb36852cf9..9f1687262f 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -220,13 +220,14 @@ int RichTextLabel::_process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int & case ALIGN_LEFT: l.offset_caches.push_back(0); break; \ case ALIGN_CENTER: l.offset_caches.push_back(((p_width - margin) - used) / 2); break; \ case ALIGN_RIGHT: l.offset_caches.push_back(((p_width - margin) - used)); break; \ - case ALIGN_FILL: l.offset_caches.push_back((p_width - margin) - used /*+spaces_size*/); break; \ + case ALIGN_FILL: l.offset_caches.push_back(line_wrapped ? ((p_width - margin) - used) : 0); break; \ } \ l.height_caches.push_back(line_height); \ l.ascent_caches.push_back(line_ascent); \ l.descent_caches.push_back(line_descent); \ l.space_caches.push_back(spaces); \ } \ + line_wrapped = false; \ y += line_height + get_constant(SceneStringNames::get_singleton()->line_separation); \ line_height = 0; \ line_ascent = 0; \ @@ -254,6 +255,7 @@ int RichTextLabel::_process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int & l.minimum_width = MAX(l.minimum_width, m_width); \ } \ if (wofs + m_width > p_width) { \ + line_wrapped = true; \ if (p_mode == PROCESS_CACHE) { \ if (spaces > 0) \ spaces -= 1; \ @@ -298,6 +300,7 @@ int RichTextLabel::_process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int & int rchar = 0; int lh = 0; bool line_is_blank = true; + bool line_wrapped = false; int fh = 0; while (it) { diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index f8a5c4cea3..d996132960 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -1429,9 +1429,6 @@ void TextEdit::_notification(int p_what) { if (OS::get_singleton()->has_virtual_keyboard()) OS::get_singleton()->show_virtual_keyboard(get_text(), get_global_rect()); - if (raised_from_completion) { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); - } } break; case NOTIFICATION_FOCUS_EXIT: { @@ -1443,9 +1440,6 @@ void TextEdit::_notification(int p_what) { if (OS::get_singleton()->has_virtual_keyboard()) OS::get_singleton()->hide_virtual_keyboard(); - if (raised_from_completion) { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); - } } break; } } @@ -5666,16 +5660,12 @@ void TextEdit::_confirm_completion() { void TextEdit::_cancel_code_hint() { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); - raised_from_completion = false; completion_hint = ""; update(); } void TextEdit::_cancel_completion() { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); - raised_from_completion = false; if (!completion_active) return; @@ -5833,8 +5823,6 @@ void TextEdit::query_code_comple() { void TextEdit::set_code_hint(const String &p_hint) { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); - raised_from_completion = true; completion_hint = p_hint; completion_hint_offset = -0xFFFF; update(); @@ -5842,8 +5830,6 @@ void TextEdit::set_code_hint(const String &p_hint) { void TextEdit::code_complete(const Vector<String> &p_strings, bool p_forced) { - VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); - raised_from_completion = true; completion_strings = p_strings; completion_active = true; completion_forced = p_forced; @@ -6232,6 +6218,7 @@ void TextEdit::_bind_methods() { BIND_ENUM_CONSTANT(MENU_MAX); GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec", 3); + ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/text_edit_idle_detect_sec", PropertyInfo(Variant::REAL, "gui/timers/text_edit_idle_detect_sec", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater")); // No negative numbers } TextEdit::TextEdit() { @@ -6345,8 +6332,6 @@ TextEdit::TextEdit() { target_v_scroll = 0; v_scroll_speed = 80; - raised_from_completion = false; - context_menu_enabled = true; menu = memnew(PopupMenu); add_child(menu); diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index f0c18ad047..8a508a8738 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -306,8 +306,6 @@ private: float target_v_scroll; float v_scroll_speed; - bool raised_from_completion; - String highlighted_word; uint64_t last_dblclk; diff --git a/scene/gui/texture_button.cpp b/scene/gui/texture_button.cpp index 413f9dbbe6..1940bbfa98 100644 --- a/scene/gui/texture_button.cpp +++ b/scene/gui/texture_button.cpp @@ -128,6 +128,7 @@ void TextureButton::_notification(int p_what) { if (normal.is_valid()) texdraw = normal; } break; + case DRAW_HOVER_PRESSED: case DRAW_PRESSED: { if (pressed.is_null()) { @@ -150,7 +151,6 @@ void TextureButton::_notification(int p_what) { } else texdraw = hover; } break; - case DRAW_HOVER_PRESSED: break; // Not used in this class case DRAW_DISABLED: { if (disabled.is_null()) { diff --git a/scene/main/node.cpp b/scene/main/node.cpp index 8fd7dc1d7b..9f234f832d 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -1835,7 +1835,7 @@ void Node::set_editable_instance(Node *p_node, bool p_editable) { } } -bool Node::is_editable_instance(Node *p_node) const { +bool Node::is_editable_instance(const Node *p_node) const { if (!p_node) return false; //easier, null is never editable :) @@ -2192,7 +2192,7 @@ void Node::_duplicate_signals(const Node *p_original, Node *p_copy) const { if (p_copy->has_node(ptarget)) copytarget = p_copy->get_node(ptarget); - if (copy && copytarget) { + if (copy && copytarget && !copy->is_connected(E->get().signal, copytarget, E->get().method)) { copy->connect(E->get().signal, copytarget, E->get().method, E->get().binds, E->get().flags); } } diff --git a/scene/main/node.h b/scene/main/node.h index a7baebc9c2..78db12dda9 100644 --- a/scene/main/node.h +++ b/scene/main/node.h @@ -303,7 +303,7 @@ public: String get_filename() const; void set_editable_instance(Node *p_node, bool p_editable); - bool is_editable_instance(Node *p_node) const; + bool is_editable_instance(const Node *p_node) const; void set_editable_instances(const HashMap<NodePath, int> &p_editable_instances); HashMap<NodePath, int> get_editable_instances() const; diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp index fdbe3b57f0..f7dec77ce4 100644 --- a/scene/main/scene_tree.cpp +++ b/scene/main/scene_tree.cpp @@ -1944,6 +1944,7 @@ SceneTree::SceneTree() { debug_navigation_color = GLOBAL_DEF("debug/shapes/navigation/geometry_color", Color(0.1, 1.0, 0.7, 0.4)); debug_navigation_disabled_color = GLOBAL_DEF("debug/shapes/navigation/disabled_geometry_color", Color(1.0, 0.7, 0.1, 0.4)); collision_debug_contacts = GLOBAL_DEF("debug/shapes/collision/max_contacts_displayed", 10000); + ProjectSettings::get_singleton()->set_custom_property_info("debug/shapes/collision/max_contacts_displayed", PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1")); // No negative tree_version = 1; physics_process_time = 1; @@ -1977,7 +1978,9 @@ SceneTree::SceneTree() { current_scene = NULL; int ref_atlas_size = GLOBAL_DEF("rendering/quality/reflections/atlas_size", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/reflections/atlas_size", PropertyInfo(Variant::INT, "rendering/quality/reflections/atlas_size", PROPERTY_HINT_RANGE, "0,8192,or_greater")); //next_power_of_2 will return a 0 as min value int ref_atlas_subdiv = GLOBAL_DEF("rendering/quality/reflections/atlas_subdiv", 8); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/reflections/atlas_subdiv", PropertyInfo(Variant::INT, "rendering/quality/reflections/atlas_subdiv", PROPERTY_HINT_RANGE, "0,32,or_greater")); //next_power_of_2 will return a 0 as min value int msaa_mode = GLOBAL_DEF("rendering/quality/filters/msaa", 0); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/filters/msaa", PropertyInfo(Variant::INT, "rendering/quality/filters/msaa", PROPERTY_HINT_ENUM, "Disabled,2x,4x,8x,16x")); root->set_msaa(Viewport::MSAA(msaa_mode)); diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index bb379ff4af..6bf1d12086 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -629,10 +629,8 @@ Rect2 Viewport::get_visible_rect() const { Rect2 r; if (size == Size2()) { - - r = Rect2(Point2(), Size2(OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height)); + r = Rect2(Point2(), OS::get_singleton()->get_window_size()); } else { - r = Rect2(Point2(), size); } @@ -2945,6 +2943,7 @@ Viewport::Viewport() { //gui.tooltip_timer->force_parent_owned(); gui.tooltip_delay = GLOBAL_DEF("gui/timers/tooltip_delay_sec", 0.7); + ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/tooltip_delay_sec", PropertyInfo(Variant::REAL, "gui/timers/tooltip_delay_sec", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); // No negative numbers gui.tooltip = NULL; gui.tooltip_label = NULL; diff --git a/scene/resources/dynamic_font.cpp b/scene/resources/dynamic_font.cpp index 458cbf6718..7422c56eee 100644 --- a/scene/resources/dynamic_font.cpp +++ b/scene/resources/dynamic_font.cpp @@ -1029,7 +1029,7 @@ void DynamicFont::_bind_methods() { Mutex *DynamicFont::dynamic_font_mutex = NULL; -SelfList<DynamicFont>::List DynamicFont::dynamic_fonts; +SelfList<DynamicFont>::List *DynamicFont::dynamic_fonts = NULL; DynamicFont::DynamicFont() : font_list(this) { @@ -1041,29 +1041,31 @@ DynamicFont::DynamicFont() : spacing_char = 0; spacing_space = 0; outline_color = Color(1, 1, 1); - if (dynamic_font_mutex) + if (dynamic_font_mutex) { dynamic_font_mutex->lock(); - dynamic_fonts.add(&font_list); - if (dynamic_font_mutex) + dynamic_fonts->add(&font_list); dynamic_font_mutex->unlock(); + } } DynamicFont::~DynamicFont() { - - if (dynamic_font_mutex) + if (dynamic_font_mutex) { dynamic_font_mutex->lock(); - dynamic_fonts.remove(&font_list); - if (dynamic_font_mutex) + dynamic_fonts->remove(&font_list); dynamic_font_mutex->unlock(); + } } void DynamicFont::initialize_dynamic_fonts() { + dynamic_fonts = memnew(SelfList<DynamicFont>::List()); dynamic_font_mutex = Mutex::create(); } void DynamicFont::finish_dynamic_fonts() { memdelete(dynamic_font_mutex); dynamic_font_mutex = NULL; + memdelete(dynamic_fonts); + dynamic_fonts = NULL; } void DynamicFont::update_oversampling() { @@ -1073,7 +1075,7 @@ void DynamicFont::update_oversampling() { if (dynamic_font_mutex) dynamic_font_mutex->lock(); - SelfList<DynamicFont> *E = dynamic_fonts.first(); + SelfList<DynamicFont> *E = dynamic_fonts->first(); while (E) { if (E->self()->data_at_size.is_valid()) { diff --git a/scene/resources/dynamic_font.h b/scene/resources/dynamic_font.h index afda48a566..bd3f84d62c 100644 --- a/scene/resources/dynamic_font.h +++ b/scene/resources/dynamic_font.h @@ -285,7 +285,7 @@ public: SelfList<DynamicFont> font_list; static Mutex *dynamic_font_mutex; - static SelfList<DynamicFont>::List dynamic_fonts; + static SelfList<DynamicFont>::List *dynamic_fonts; static void initialize_dynamic_fonts(); static void finish_dynamic_fonts(); diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index 274c74a9a2..c3030ee741 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -614,7 +614,7 @@ void SpatialMaterial::_update_shader() { code += "\tfloat particle_frame = floor(INSTANCE_CUSTOM.z * float(particle_total_frames));\n"; code += "\tif (particles_anim_loop) particle_frame=clamp(particle_frame,0.0,particle_total_frames-1.0); else particle_frame=mod(particle_frame,float(particle_total_frames));\n"; code += "\tUV /= vec2(float(particles_anim_h_frames),float(particles_anim_v_frames));\n"; - code += "\tUV += vec2(mod(particle_frame,float(particles_anim_h_frames)) / float(particles_anim_h_frames),particle_frame / float(particles_anim_h_frames) / float(particles_anim_v_frames));\n"; + code += "\tUV += vec2(mod(particle_frame,float(particles_anim_h_frames)) / float(particles_anim_h_frames), floor(particle_frame / float(particles_anim_h_frames)) / float(particles_anim_v_frames));\n"; } break; } diff --git a/scene/resources/mesh_data_tool.cpp b/scene/resources/mesh_data_tool.cpp index a5449e1fe8..7af9086ab7 100644 --- a/scene/resources/mesh_data_tool.cpp +++ b/scene/resources/mesh_data_tool.cpp @@ -42,8 +42,6 @@ void MeshDataTool::clear() { Error MeshDataTool::create_from_surface(const Ref<ArrayMesh> &p_mesh, int p_surface) { ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER); - - ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface) != Mesh::PRIMITIVE_TRIANGLES, ERR_INVALID_PARAMETER); Array arrays = p_mesh->surface_get_arrays(p_surface); diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp index 086fb83af9..42ce9d10cd 100644 --- a/scene/resources/packed_scene.cpp +++ b/scene/resources/packed_scene.cpp @@ -264,7 +264,7 @@ Node *SceneState::instance(GenEditState p_edit_state) const { } if (n.instance >= 0 || n.type != TYPE_INSTANCED || i == 0) { - //if node was not part of instance, must set it's name, parenthood and ownership + //if node was not part of instance, must set its name, parenthood and ownership if (i > 0) { if (parent) { parent->_add_child_nocheck(node, snames[n.name]); diff --git a/servers/audio/audio_stream.cpp b/servers/audio/audio_stream.cpp index 7de0695e8c..02a0bed964 100644 --- a/servers/audio/audio_stream.cpp +++ b/servers/audio/audio_stream.cpp @@ -136,16 +136,20 @@ void AudioStreamPlaybackMicrophone::_mix_internal(AudioFrame *p_buffer, int p_fr Vector<int32_t> buf = AudioDriver::get_singleton()->get_input_buffer(); unsigned int input_size = AudioDriver::get_singleton()->get_input_size(); + int mix_rate = AudioDriver::get_singleton()->get_mix_rate(); + int playback_delay = MIN(((50 * mix_rate) / 1000) * 2, buf.size() >> 1); +#ifdef DEBUG_ENABLED + unsigned int input_position = AudioDriver::get_singleton()->get_input_position(); +#endif - // p_frames is multiplied by two since an AudioFrame is stereo - if ((p_frames + MICROPHONE_PLAYBACK_DELAY * 2) > input_size) { + if (playback_delay > input_size) { for (int i = 0; i < p_frames; i++) { p_buffer[i] = AudioFrame(0.0f, 0.0f); } input_ofs = 0; } else { for (int i = 0; i < p_frames; i++) { - if (input_size >= input_ofs) { + if (input_size > input_ofs) { float l = (buf[input_ofs++] >> 16) / 32768.f; if (input_ofs >= buf.size()) { input_ofs = 0; @@ -162,6 +166,12 @@ void AudioStreamPlaybackMicrophone::_mix_internal(AudioFrame *p_buffer, int p_fr } } +#ifdef DEBUG_ENABLED + if (input_ofs > input_position && (input_ofs - input_position) < (p_frames * 2)) { + print_verbose(String(get_class_name()) + " buffer underrun: input_position=" + itos(input_position) + " input_ofs=" + itos(input_ofs) + " input_size=" + itos(input_size)); + } +#endif + AudioDriver::get_singleton()->unlock(); } diff --git a/servers/audio/audio_stream.h b/servers/audio/audio_stream.h index 2740f86d55..f6ed45cc9c 100644 --- a/servers/audio/audio_stream.h +++ b/servers/audio/audio_stream.h @@ -122,8 +122,6 @@ class AudioStreamPlaybackMicrophone : public AudioStreamPlaybackResampled { GDCLASS(AudioStreamPlaybackMicrophone, AudioStreamPlayback) friend class AudioStreamMicrophone; - static const int MICROPHONE_PLAYBACK_DELAY = 256; - bool active; unsigned int input_ofs; diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp index d36057b465..b41fcac8fa 100644 --- a/servers/audio_server.cpp +++ b/servers/audio_server.cpp @@ -80,6 +80,14 @@ double AudioDriver::get_mix_time() const { return total; } +void AudioDriver::input_buffer_init(int driver_buffer_frames) { + + const int input_buffer_channels = 2; + input_buffer.resize(driver_buffer_frames * input_buffer_channels * 4); + input_position = 0; + input_size = 0; +} + void AudioDriver::input_buffer_write(int32_t sample) { input_buffer.write[input_position++] = sample; @@ -926,6 +934,7 @@ void AudioServer::init() { channel_disable_threshold_db = GLOBAL_DEF_RST("audio/channel_disable_threshold_db", -60.0); channel_disable_frames = float(GLOBAL_DEF_RST("audio/channel_disable_time", 2.0)) * get_mix_rate(); + ProjectSettings::get_singleton()->set_custom_property_info("audio/channel_disable_time", PropertyInfo(Variant::REAL, "audio/channel_disable_time", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); buffer_size = 1024; //hardcoded for now init_channels_and_buffers(); diff --git a/servers/audio_server.h b/servers/audio_server.h index ba6569eb38..b12ca6e589 100644 --- a/servers/audio_server.h +++ b/servers/audio_server.h @@ -59,6 +59,7 @@ protected: void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true); void update_mix_time(int p_frames); + void input_buffer_init(int driver_buffer_frames); void input_buffer_write(int32_t sample); #ifdef DEBUG_ENABLED diff --git a/servers/physics/area_pair_sw.cpp b/servers/physics/area_pair_sw.cpp index d2fef0ab77..5e295edcd1 100644 --- a/servers/physics/area_pair_sw.cpp +++ b/servers/physics/area_pair_sw.cpp @@ -147,10 +147,10 @@ Area2PairSW::~Area2PairSW() { if (colliding) { - if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) + if (area_b->has_area_monitor_callback()) area_b->remove_area_from_query(area_a, shape_a, shape_b); - if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) + if (area_a->has_area_monitor_callback()) area_a->remove_area_from_query(area_b, shape_b, shape_a); } diff --git a/servers/physics/collision_solver_sat.cpp b/servers/physics/collision_solver_sat.cpp index 087ae570fb..f17f6f7014 100644 --- a/servers/physics/collision_solver_sat.cpp +++ b/servers/physics/collision_solver_sat.cpp @@ -98,7 +98,6 @@ static void _generate_contacts_edge_edge(const Vector3 *p_points_A, int p_point_ Vector3 c = rel_A.cross(rel_B).cross(rel_B); - //if ( Math::abs(rel_A.dot(c) )<_EDGE_IS_VALID_SUPPORT_TRESHOLD ) { if (Math::abs(rel_A.dot(c)) < CMP_EPSILON) { // should handle somehow.. diff --git a/servers/physics/space_sw.cpp b/servers/physics/space_sw.cpp index 731749b8ce..feb96d8054 100644 --- a/servers/physics/space_sw.cpp +++ b/servers/physics/space_sw.cpp @@ -1183,6 +1183,7 @@ SpaceSW::SpaceSW() { body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_linear", 0.1); body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI)); body_time_to_sleep = GLOBAL_DEF("physics/3d/time_before_sleep", 0.5); + ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/time_before_sleep", PropertyInfo(Variant::REAL, "physics/3d/time_before_sleep", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); body_angular_velocity_damp_ratio = 10; broadphase = BroadPhaseSW::create_func(); diff --git a/servers/physics_2d/area_pair_2d_sw.cpp b/servers/physics_2d/area_pair_2d_sw.cpp index 9d515d2183..cdd35cf657 100644 --- a/servers/physics_2d/area_pair_2d_sw.cpp +++ b/servers/physics_2d/area_pair_2d_sw.cpp @@ -147,10 +147,10 @@ Area2Pair2DSW::~Area2Pair2DSW() { if (colliding) { - if (area_b->has_area_monitor_callback() && area_a->is_monitorable()) + if (area_b->has_area_monitor_callback()) area_b->remove_area_from_query(area_a, shape_a, shape_b); - if (area_a->has_area_monitor_callback() && area_b->is_monitorable()) + if (area_a->has_area_monitor_callback()) area_a->remove_area_from_query(area_b, shape_b, shape_a); } diff --git a/servers/physics_2d/broad_phase_2d_hash_grid.cpp b/servers/physics_2d/broad_phase_2d_hash_grid.cpp index 950f0f9d24..95195c8fff 100644 --- a/servers/physics_2d/broad_phase_2d_hash_grid.cpp +++ b/servers/physics_2d/broad_phase_2d_hash_grid.cpp @@ -635,11 +635,15 @@ BroadPhase2DSW *BroadPhase2DHashGrid::_create() { BroadPhase2DHashGrid::BroadPhase2DHashGrid() { hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size", 4096); + ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/bp_hash_table_size", PropertyInfo(Variant::INT, "physics/2d/bp_hash_table_size", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); hash_table_size = Math::larger_prime(hash_table_size); hash_table = memnew_arr(PosBin *, hash_table_size); cell_size = GLOBAL_DEF("physics/2d/cell_size", 128); + ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/cell_size", PropertyInfo(Variant::INT, "physics/2d/cell_size", PROPERTY_HINT_RANGE, "0,512,1,or_greater")); + large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_threshold_in_cells", 512); + ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/large_object_surface_threshold_in_cells", PropertyInfo(Variant::INT, "physics/2d/large_object_surface_threshold_in_cells", PROPERTY_HINT_RANGE, "0,1024,1,or_greater")); for (uint32_t i = 0; i < hash_table_size; i++) hash_table[i] = NULL; diff --git a/servers/physics_2d/space_2d_sw.cpp b/servers/physics_2d/space_2d_sw.cpp index f36328c985..adcc99aae8 100644 --- a/servers/physics_2d/space_2d_sw.cpp +++ b/servers/physics_2d/space_2d_sw.cpp @@ -1233,6 +1233,7 @@ Space2DSW::Space2DSW() { body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_linear", 2.0); body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI)); body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5); + ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/time_before_sleep", PropertyInfo(Variant::REAL, "physics/2d/time_before_sleep", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); broadphase = BroadPhase2DSW::create_func(); broadphase->set_pair_callback(_broadphase_pair, this); diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp index d52e121a13..e2db89e699 100644 --- a/servers/visual/shader_language.cpp +++ b/servers/visual/shader_language.cpp @@ -2498,7 +2498,7 @@ bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block, CompletionT identifier = StringName(); - TkPos pos; + TkPos pos = { 0, 0 }; Token tk = _get_token(); diff --git a/servers/visual_server.cpp b/servers/visual_server.cpp index 9d684d33d6..164be132b8 100644 --- a/servers/visual_server.cpp +++ b/servers/visual_server.cpp @@ -2370,6 +2370,7 @@ VisualServer::VisualServer() { GLOBAL_DEF("rendering/quality/directional_shadow/size", 4096); GLOBAL_DEF("rendering/quality/directional_shadow/size.mobile", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/directional_shadow/size", PropertyInfo(Variant::INT, "rendering/quality/directional_shadow/size", PROPERTY_HINT_RANGE, "256,16384")); GLOBAL_DEF("rendering/quality/shadow_atlas/size", 4096); GLOBAL_DEF("rendering/quality/shadow_atlas/size.mobile", 2048); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/shadow_atlas/size", PropertyInfo(Variant::INT, "rendering/quality/shadow_atlas/size", PROPERTY_HINT_RANGE, "256,16384")); diff --git a/thirdparty/libwebsockets/lws_config.h b/thirdparty/libwebsockets/lws_config.h index e5e15cc2fd..86ce9ac38a 100644 --- a/thirdparty/libwebsockets/lws_config.h +++ b/thirdparty/libwebsockets/lws_config.h @@ -174,7 +174,7 @@ #define LWS_HAVE_MALLOC_H #endif -#if !defined(IPHONE_ENABLED) && !defined(OSX_ENABLED) && !defined(__HAIKU__) +#if !defined(__APPLE__) && !defined(__HAIKU__) #define LWS_HAVE_PIPE2 #endif diff --git a/thirdparty/libwebsockets/lws_config_private.h b/thirdparty/libwebsockets/lws_config_private.h index b26d225afa..e531777624 100644 --- a/thirdparty/libwebsockets/lws_config_private.h +++ b/thirdparty/libwebsockets/lws_config_private.h @@ -81,7 +81,7 @@ /* Define to 1 if you have the <sys/prctl.h> header file. */ #define LWS_HAVE_SYS_PRCTL_H -#if defined(OSX_ENABLED) || defined(IPHONE_ENABLED) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__) +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__) #undef LWS_HAVE_SYS_PRCTL_H #endif |