summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/linux_builds.yml2
-rw-r--r--core/core_bind.cpp5
-rw-r--r--core/core_bind.h1
-rw-r--r--core/debugger/remote_debugger.cpp2
-rw-r--r--core/debugger/remote_debugger.h2
-rw-r--r--core/debugger/remote_debugger_peer.cpp6
-rw-r--r--core/extension/native_extension.cpp16
-rw-r--r--core/io/file_access_pack.cpp68
-rw-r--r--core/io/file_access_pack.h2
-rw-r--r--core/io/http_client_tcp.cpp3
-rw-r--r--core/io/logger.h12
-rw-r--r--core/io/packet_peer_udp.cpp4
-rw-r--r--core/io/packet_peer_udp.h2
-rw-r--r--core/io/resource.cpp2
-rw-r--r--core/io/stream_peer_tcp.cpp85
-rw-r--r--core/io/stream_peer_tcp.h11
-rw-r--r--core/math/convex_hull.cpp6
-rw-r--r--core/math/geometry_3d.cpp4
-rw-r--r--core/math/math_funcs.h3
-rw-r--r--core/object/class_db.cpp9
-rw-r--r--core/object/class_db.h14
-rw-r--r--core/object/method_bind.cpp2
-rw-r--r--core/object/method_bind.h90
-rw-r--r--core/os/keyboard.h2
-rw-r--r--core/os/os.cpp5
-rw-r--r--core/os/os.h2
-rw-r--r--core/string/ustring.cpp5
-rw-r--r--core/templates/oa_hash_map.h18
-rw-r--r--core/variant/variant.cpp4
-rw-r--r--core/variant/variant_call.cpp6
-rw-r--r--core/variant/variant_parser.cpp1
-rw-r--r--doc/classes/@GlobalScope.xml4
-rw-r--r--doc/classes/AspectRatioContainer.xml1
-rw-r--r--doc/classes/BoxContainer.xml1
-rw-r--r--doc/classes/CenterContainer.xml1
-rw-r--r--doc/classes/Container.xml1
-rw-r--r--doc/classes/Directory.xml3
-rw-r--r--doc/classes/DisplayServer.xml102
-rw-r--r--doc/classes/EditorPlugin.xml6
-rw-r--r--doc/classes/GPUParticles2D.xml3
-rw-r--r--doc/classes/GPUParticles3D.xml1
-rw-r--r--doc/classes/GridContainer.xml1
-rw-r--r--doc/classes/HBoxContainer.xml1
-rw-r--r--doc/classes/HSplitContainer.xml1
-rw-r--r--doc/classes/Input.xml3
-rw-r--r--doc/classes/Label3D.xml3
-rw-r--r--doc/classes/MarginContainer.xml1
-rw-r--r--doc/classes/MultiplayerAPI.xml4
-rw-r--r--doc/classes/Node.xml63
-rw-r--r--doc/classes/OS.xml8
-rw-r--r--doc/classes/PacketPeerUDP.xml2
-rw-r--r--doc/classes/PanelContainer.xml1
-rw-r--r--doc/classes/ProjectSettings.xml10
-rw-r--r--doc/classes/SceneTree.xml18
-rw-r--r--doc/classes/ScrollContainer.xml1
-rw-r--r--doc/classes/Skeleton3D.xml8
-rw-r--r--doc/classes/SplitContainer.xml1
-rw-r--r--doc/classes/StreamPeerTCP.xml8
-rw-r--r--doc/classes/StyleBoxFlat.xml10
-rw-r--r--doc/classes/TabContainer.xml1
-rw-r--r--doc/classes/TextServer.xml8
-rw-r--r--doc/classes/TextServerExtension.xml8
-rw-r--r--doc/classes/TileMap.xml4
-rw-r--r--doc/classes/Tween.xml20
-rw-r--r--doc/classes/Tweener.xml2
-rw-r--r--doc/classes/VBoxContainer.xml1
-rw-r--r--doc/classes/VSplitContainer.xml1
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.cpp239
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.h27
-rw-r--r--drivers/gles3/rasterizer_gles3.cpp46
-rw-r--r--drivers/gles3/rasterizer_gles3.h2
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp632
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.h329
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.cpp204
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.h42
-rw-r--r--drivers/gles3/shader_gles3.cpp11
-rw-r--r--drivers/gles3/shader_gles3.h2
-rw-r--r--drivers/gles3/shaders/SCsub1
-rw-r--r--drivers/gles3/shaders/canvas.glsl2
-rw-r--r--drivers/gles3/shaders/sky.glsl179
-rw-r--r--drivers/gles3/storage/config.cpp59
-rw-r--r--drivers/gles3/storage/config.h10
-rw-r--r--drivers/gles3/storage/material_storage.cpp3251
-rw-r--r--drivers/gles3/storage/material_storage.h400
-rw-r--r--drivers/gles3/storage/mesh_storage.cpp1190
-rw-r--r--drivers/gles3/storage/mesh_storage.h363
-rw-r--r--drivers/gles3/storage/texture_storage.cpp1170
-rw-r--r--drivers/gles3/storage/texture_storage.h398
-rw-r--r--drivers/pulseaudio/audio_driver_pulseaudio.cpp2
-rw-r--r--drivers/vulkan/rendering_device_vulkan.cpp2
-rw-r--r--editor/animation_track_editor.cpp109
-rw-r--r--editor/animation_track_editor.h2
-rw-r--r--editor/audio_stream_preview.cpp2
-rw-r--r--editor/code_editor.cpp98
-rw-r--r--editor/code_editor.h6
-rw-r--r--editor/connections_dialog.cpp19
-rw-r--r--editor/editor_export.cpp89
-rw-r--r--editor/editor_export.h4
-rw-r--r--editor/editor_inspector.cpp25
-rw-r--r--editor/editor_node.cpp113
-rw-r--r--editor/editor_node.h4
-rw-r--r--editor/editor_plugin.cpp5
-rw-r--r--editor/editor_plugin.h2
-rw-r--r--editor/editor_properties.cpp23
-rw-r--r--editor/editor_properties_array_dict.cpp43
-rw-r--r--editor/editor_property_name_processor.cpp3
-rw-r--r--editor/editor_resource_picker.cpp3
-rw-r--r--editor/editor_run.cpp122
-rw-r--r--editor/editor_settings.cpp6
-rw-r--r--editor/export_template_manager.cpp2
-rw-r--r--editor/icons/ExternalLink.svg2
-rw-r--r--editor/import/collada.cpp4
-rw-r--r--editor/import/collada.h4
-rw-r--r--editor/import/resource_importer_texture.cpp38
-rw-r--r--editor/import/scene_import_settings.cpp2
-rw-r--r--editor/plugins/animation_library_editor.cpp8
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp2
-rw-r--r--editor/plugins/animation_state_machine_editor.cpp12
-rw-r--r--editor/plugins/animation_state_machine_editor.h4
-rw-r--r--editor/plugins/bit_map_editor_plugin.cpp86
-rw-r--r--editor/plugins/bit_map_editor_plugin.h64
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp4
-rw-r--r--editor/plugins/editor_preview_plugins.cpp31
-rw-r--r--editor/plugins/editor_preview_plugins.h11
-rw-r--r--editor/plugins/gpu_particles_2d_editor_plugin.cpp4
-rw-r--r--editor/plugins/gpu_particles_3d_editor_plugin.cpp4
-rw-r--r--editor/plugins/gpu_particles_3d_editor_plugin.h2
-rw-r--r--editor/plugins/node_3d_editor_gizmos.cpp2
-rw-r--r--editor/plugins/node_3d_editor_gizmos.h2
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp16
-rw-r--r--editor/plugins/path_3d_editor_plugin.cpp4
-rw-r--r--editor/plugins/ray_cast_2d_editor_plugin.cpp151
-rw-r--r--editor/plugins/ray_cast_2d_editor_plugin.h79
-rw-r--r--editor/plugins/skeleton_3d_editor_plugin.cpp25
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.cpp3
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.h1
-rw-r--r--editor/plugins/texture_region_editor_plugin.cpp2
-rw-r--r--editor/plugins/tiles/tile_atlas_view.cpp2
-rw-r--r--editor/plugins/tiles/tile_data_editors.cpp4
-rw-r--r--editor/plugins/tiles/tile_set_atlas_source_editor.cpp4
-rw-r--r--editor/plugins/tiles/tile_set_scenes_collection_source_editor.cpp3
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp6
-rw-r--r--editor/plugins/visual_shader_editor_plugin.h2
-rw-r--r--editor/project_manager.cpp24
-rw-r--r--editor/scene_tree_dock.cpp2
-rw-r--r--editor/scene_tree_dock.h2
-rw-r--r--main/main.cpp50
-rw-r--r--modules/csg/editor/csg_gizmos.cpp14
-rw-r--r--modules/gdscript/gdscript.cpp8
-rw-r--r--modules/gdscript/gdscript.h1
-rw-r--r--modules/gdscript/gdscript_analyzer.cpp88
-rw-r--r--modules/gdscript/gdscript_analyzer.h3
-rw-r--r--modules/gdscript/gdscript_byte_codegen.cpp4
-rw-r--r--modules/gdscript/gdscript_byte_codegen.h2
-rw-r--r--modules/gdscript/gdscript_codegen.h2
-rw-r--r--modules/gdscript/gdscript_compiler.cpp2
-rw-r--r--modules/gdscript/gdscript_disassembler.cpp19
-rw-r--r--modules/gdscript/gdscript_editor.cpp2
-rw-r--r--modules/gdscript/gdscript_function.h1
-rw-r--r--modules/gdscript/gdscript_lambda_callable.cpp78
-rw-r--r--modules/gdscript/gdscript_lambda_callable.h25
-rw-r--r--modules/gdscript/gdscript_parser.cpp3
-rw-r--r--modules/gdscript/gdscript_parser.h2
-rw-r--r--modules/gdscript/gdscript_vm.cpp36
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.gd58
-rw-r--r--modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.out5
-rw-r--r--modules/gdscript/tests/scripts/runtime/features/lambda_use_self.gd23
-rw-r--r--modules/gdscript/tests/scripts/runtime/features/lambda_use_self.out5
-rw-r--r--modules/gltf/editor/editor_scene_exporter_gltf_plugin.cpp9
-rw-r--r--modules/gltf/gltf_document.cpp68
-rw-r--r--modules/gltf/gltf_state.cpp8
-rw-r--r--modules/gltf/gltf_state.h4
-rw-r--r--modules/mbedtls/packet_peer_mbed_dtls.cpp2
-rw-r--r--modules/navigation/godot_navigation_server.cpp72
-rw-r--r--modules/navigation/nav_map.cpp13
-rw-r--r--modules/navigation/nav_map.h7
-rw-r--r--modules/noise/SCsub1
-rw-r--r--modules/noise/doc_classes/FastNoiseLite.xml8
-rw-r--r--modules/noise/doc_classes/Noise.xml18
-rw-r--r--modules/noise/doc_classes/NoiseTexture.xml11
-rw-r--r--modules/noise/editor/noise_editor_plugin.cpp149
-rw-r--r--modules/noise/editor/noise_editor_plugin.h49
-rw-r--r--modules/noise/fastnoise_lite.cpp237
-rw-r--r--modules/noise/fastnoise_lite.h63
-rw-r--r--modules/noise/noise.cpp52
-rw-r--r--modules/noise/noise.h16
-rw-r--r--modules/noise/noise_texture.cpp97
-rw-r--r--modules/noise/noise_texture.h20
-rw-r--r--modules/noise/register_types.cpp9
-rw-r--r--modules/openxr/action_map/openxr_action_map.cpp18
-rw-r--r--modules/openxr/openxr_api.cpp4
-rw-r--r--modules/openxr/openxr_api.h4
-rw-r--r--modules/text_server_adv/text_server_adv.cpp60
-rw-r--r--modules/text_server_adv/text_server_adv.h4
-rw-r--r--modules/text_server_fb/text_server_fb.cpp25
-rw-r--r--modules/text_server_fb/text_server_fb.h2
-rw-r--r--modules/websocket/wsl_client.cpp3
-rw-r--r--modules/webxr/webxr_interface_js.cpp4
-rw-r--r--platform/android/SCsub1
-rw-r--r--platform/android/display_server_android.cpp30
-rw-r--r--platform/android/display_server_android.h9
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/Godot.java18
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotLib.java5
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/tts/GodotTTS.java298
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/tts/GodotUtterance.java55
-rw-r--r--platform/android/java_godot_lib_jni.cpp6
-rw-r--r--platform/android/java_godot_lib_jni.h1
-rw-r--r--platform/android/os_android.cpp2
-rw-r--r--platform/android/tts_android.cpp189
-rw-r--r--platform/android/tts_android.h67
-rw-r--r--platform/iphone/SCsub1
-rw-r--r--platform/iphone/display_server_iphone.h11
-rw-r--r--platform/iphone/display_server_iphone.mm40
-rw-r--r--platform/iphone/ios.h11
-rw-r--r--platform/iphone/ios.mm99
-rw-r--r--platform/iphone/os_iphone.mm8
-rw-r--r--platform/iphone/tts_ios.h59
-rw-r--r--platform/iphone/tts_ios.mm164
-rw-r--r--platform/javascript/display_server_javascript.cpp86
-rw-r--r--platform/javascript/display_server_javascript.h16
-rw-r--r--platform/javascript/godot_js.h10
-rw-r--r--platform/javascript/javascript_singleton.cpp2
-rw-r--r--platform/javascript/js/libs/library_godot_display.js90
-rw-r--r--platform/linuxbsd/SCsub3
-rw-r--r--platform/linuxbsd/detect.py21
-rw-r--r--platform/linuxbsd/display_server_x11.cpp85
-rw-r--r--platform/linuxbsd/display_server_x11.h19
-rw-r--r--platform/linuxbsd/os_linuxbsd.cpp85
-rw-r--r--platform/linuxbsd/os_linuxbsd.h2
-rw-r--r--platform/linuxbsd/speechd-so_wrap.c881
-rw-r--r--platform/linuxbsd/speechd-so_wrap.h330
-rw-r--r--platform/linuxbsd/tts_linux.cpp261
-rw-r--r--platform/linuxbsd/tts_linux.h78
-rw-r--r--platform/osx/SCsub1
-rw-r--r--platform/osx/display_server_osx.h11
-rw-r--r--platform/osx/display_server_osx.mm41
-rw-r--r--platform/osx/tts_osx.h66
-rw-r--r--platform/osx/tts_osx.mm266
-rw-r--r--platform/windows/SCsub1
-rw-r--r--platform/windows/detect.py2
-rw-r--r--platform/windows/display_server_windows.cpp43
-rw-r--r--platform/windows/display_server_windows.h12
-rw-r--r--platform/windows/export/export_plugin.cpp66
-rw-r--r--platform/windows/export/export_plugin.h2
-rw-r--r--platform/windows/godot_windows.cpp18
-rw-r--r--platform/windows/os_windows.cpp52
-rw-r--r--platform/windows/os_windows.h2
-rw-r--r--platform/windows/tts_windows.cpp269
-rw-r--r--platform/windows/tts_windows.h80
-rw-r--r--scene/2d/gpu_particles_2d.cpp13
-rw-r--r--scene/2d/gpu_particles_2d.h4
-rw-r--r--scene/2d/path_2d.cpp2
-rw-r--r--scene/2d/physics_body_2d.cpp6
-rw-r--r--scene/2d/tile_map.cpp10
-rw-r--r--scene/3d/label_3d.cpp20
-rw-r--r--scene/3d/label_3d.h4
-rw-r--r--scene/3d/path_3d.cpp2
-rw-r--r--scene/3d/physics_body_3d.cpp6
-rw-r--r--scene/3d/skeleton_3d.cpp20
-rw-r--r--scene/3d/skeleton_3d.h3
-rw-r--r--scene/3d/skeleton_ik_3d.cpp2
-rw-r--r--scene/3d/skeleton_ik_3d.h2
-rw-r--r--scene/3d/sprite_3d.cpp4
-rw-r--r--scene/3d/voxelizer.cpp4
-rw-r--r--scene/animation/animation_node_state_machine.cpp16
-rw-r--r--scene/animation/animation_node_state_machine.h2
-rw-r--r--scene/animation/animation_tree.cpp4
-rw-r--r--scene/animation/root_motion_view.cpp9
-rw-r--r--scene/animation/tween.cpp18
-rw-r--r--scene/animation/tween.h8
-rw-r--r--scene/gui/code_edit.cpp3
-rw-r--r--scene/gui/popup_menu.cpp4
-rw-r--r--scene/main/node.cpp72
-rw-r--r--scene/main/node.h7
-rw-r--r--scene/main/scene_tree.cpp67
-rw-r--r--scene/main/scene_tree.h5
-rw-r--r--scene/main/window.cpp15
-rw-r--r--scene/register_scene_types.cpp5
-rw-r--r--scene/resources/animation_library.cpp21
-rw-r--r--scene/resources/animation_library.h3
-rw-r--r--scene/resources/default_theme/default_theme.cpp11
-rw-r--r--scene/resources/default_theme/default_theme.h2
-rw-r--r--scene/resources/gradient.cpp2
-rw-r--r--scene/resources/gradient.h2
-rw-r--r--scene/resources/immediate_mesh.cpp2
-rw-r--r--scene/resources/style_box.cpp62
-rw-r--r--scene/resources/style_box.h4
-rw-r--r--scene/resources/texture.cpp5
-rw-r--r--servers/display_server.cpp94
-rw-r--r--servers/display_server.h36
-rw-r--r--servers/navigation_server_2d.cpp4
-rw-r--r--servers/physics_2d/godot_space_2d.cpp4
-rw-r--r--servers/physics_server_2d_wrap_mt.cpp22
-rw-r--r--servers/physics_server_2d_wrap_mt.h22
-rw-r--r--servers/physics_server_3d_wrap_mt.cpp22
-rw-r--r--servers/physics_server_3d_wrap_mt.h20
-rw-r--r--servers/register_server_types.cpp8
-rw-r--r--servers/rendering/dummy/rasterizer_scene_dummy.h2
-rw-r--r--servers/rendering/renderer_rd/SCsub1
-rw-r--r--servers/rendering/renderer_rd/effects/SCsub5
-rw-r--r--servers/rendering/renderer_rd/effects/tone_mapper.cpp280
-rw-r--r--servers/rendering/renderer_rd/effects/tone_mapper.h155
-rw-r--r--servers/rendering/renderer_rd/effects_rd.cpp201
-rw-r--r--servers/rendering/renderer_rd/effects_rd.h104
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp6
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h4
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp6
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h2
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp8
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp2
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_render_rd.cpp26
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_render_rd.h8
-rw-r--r--servers/rendering/renderer_rd/shaders/SCsub2
-rw-r--r--servers/rendering/renderer_rd/shaders/effects/SCsub17
-rw-r--r--servers/rendering/renderer_rd/shaders/effects/tonemap.glsl (renamed from servers/rendering/renderer_rd/shaders/tonemap.glsl)0
-rw-r--r--servers/rendering/renderer_rd/storage_rd/material_storage.cpp32
-rw-r--r--servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp30
-rw-r--r--servers/rendering/renderer_rd/storage_rd/particles_storage.cpp2
-rw-r--r--servers/rendering/renderer_scene_cull.cpp20
-rw-r--r--servers/rendering/renderer_scene_render.cpp8
-rw-r--r--servers/rendering/renderer_scene_render.h8
-rw-r--r--servers/rendering/shader_language.cpp141
-rw-r--r--servers/rendering/shader_language.h1
-rw-r--r--servers/rendering_server.cpp18
-rw-r--r--servers/text/text_server_extension.cpp10
-rw-r--r--servers/text/text_server_extension.h3
-rw-r--r--servers/text_server.cpp2
-rw-r--r--servers/text_server.h3
-rw-r--r--tests/scene/test_code_edit.h32
-rw-r--r--tests/servers/test_text_server.h43
-rw-r--r--tests/test_macros.h28
-rw-r--r--tests/test_main.cpp50
-rw-r--r--thirdparty/noise/FastNoiseLite.h92
-rw-r--r--thirdparty/noise/patches/FastNoiseLite.patch414
335 files changed, 14451 insertions, 4006 deletions
diff --git a/.github/workflows/linux_builds.yml b/.github/workflows/linux_builds.yml
index 7ac364c45f..338278f461 100644
--- a/.github/workflows/linux_builds.yml
+++ b/.github/workflows/linux_builds.yml
@@ -87,7 +87,7 @@ jobs:
sudo apt-get install build-essential pkg-config libx11-dev libxcursor-dev \
libxinerama-dev libgl1-mesa-dev libglu-dev libasound2-dev libpulse-dev \
libdbus-1-dev libudev-dev libxi-dev libxrandr-dev yasm xvfb wget unzip \
- llvm
+ llvm libspeechd-dev speech-dispatcher
- name: Setup Godot build cache
uses: ./.github/actions/godot-cache
diff --git a/core/core_bind.cpp b/core/core_bind.cpp
index 892b74c26a..8308c4fe53 100644
--- a/core/core_bind.cpp
+++ b/core/core_bind.cpp
@@ -483,6 +483,10 @@ void OS::dump_resources_to_file(const String &p_file) {
::OS::get_singleton()->dump_resources_to_file(p_file.utf8().get_data());
}
+Error OS::move_to_trash(const String &p_path) const {
+ return ::OS::get_singleton()->move_to_trash(p_path);
+}
+
String OS::get_user_data_dir() const {
return ::OS::get_singleton()->get_user_data_dir();
}
@@ -597,6 +601,7 @@ void OS::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_static_memory_usage"), &OS::get_static_memory_usage);
ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"), &OS::get_static_memory_peak_usage);
+ ClassDB::bind_method(D_METHOD("move_to_trash", "path"), &OS::move_to_trash);
ClassDB::bind_method(D_METHOD("get_user_data_dir"), &OS::get_user_data_dir);
ClassDB::bind_method(D_METHOD("get_system_dir", "dir", "shared_storage"), &OS::get_system_dir, DEFVAL(true));
ClassDB::bind_method(D_METHOD("get_config_dir"), &OS::get_config_dir);
diff --git a/core/core_bind.h b/core/core_bind.h
index 591cacdabb..bc68be3f62 100644
--- a/core/core_bind.h
+++ b/core/core_bind.h
@@ -235,6 +235,7 @@ public:
String get_system_dir(SystemDir p_dir, bool p_shared_storage = true) const;
+ Error move_to_trash(const String &p_path) const;
String get_user_data_dir() const;
String get_config_dir() const;
String get_data_dir() const;
diff --git a/core/debugger/remote_debugger.cpp b/core/debugger/remote_debugger.cpp
index 425261aa6c..c3506a7eea 100644
--- a/core/debugger/remote_debugger.cpp
+++ b/core/debugger/remote_debugger.cpp
@@ -169,7 +169,7 @@ public:
EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr);
}
- PerformanceProfiler(Object *p_performance) {
+ explicit PerformanceProfiler(Object *p_performance) {
performance = p_performance;
}
};
diff --git a/core/debugger/remote_debugger.h b/core/debugger/remote_debugger.h
index aada92da60..fdb312ae68 100644
--- a/core/debugger/remote_debugger.h
+++ b/core/debugger/remote_debugger.h
@@ -108,7 +108,7 @@ public:
void send_error(const String &p_func, const String &p_file, int p_line, const String &p_err, const String &p_descr, bool p_editor_notify, ErrorHandlerType p_type);
void debug(bool p_can_continue = true, bool p_is_error_breakpoint = false);
- RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer);
+ explicit RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer);
~RemoteDebugger();
};
diff --git a/core/debugger/remote_debugger_peer.cpp b/core/debugger/remote_debugger_peer.cpp
index 950500884e..e9362b4ea4 100644
--- a/core/debugger/remote_debugger_peer.cpp
+++ b/core/debugger/remote_debugger_peer.cpp
@@ -93,7 +93,7 @@ RemoteDebuggerPeerTCP::~RemoteDebuggerPeerTCP() {
}
void RemoteDebuggerPeerTCP::_write_out() {
- while (tcp_client->poll(NetSocket::POLL_TYPE_OUT) == OK) {
+ while (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED && tcp_client->wait(NetSocket::POLL_TYPE_OUT) == OK) {
uint8_t *buf = out_buf.ptrw();
if (out_left <= 0) {
if (out_queue.size() == 0) {
@@ -119,7 +119,7 @@ void RemoteDebuggerPeerTCP::_write_out() {
}
void RemoteDebuggerPeerTCP::_read_in() {
- while (tcp_client->poll(NetSocket::POLL_TYPE_IN) == OK) {
+ while (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED && tcp_client->wait(NetSocket::POLL_TYPE_IN) == OK) {
uint8_t *buf = in_buf.ptrw();
if (in_left <= 0) {
if (in_queue.size() > max_queued_messages) {
@@ -167,6 +167,7 @@ Error RemoteDebuggerPeerTCP::connect_to_host(const String &p_host, uint16_t p_po
tcp_client->connect_to_host(ip, port);
for (int i = 0; i < tries; i++) {
+ tcp_client->poll();
if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
print_verbose("Remote Debugger: Connected!");
break;
@@ -213,6 +214,7 @@ void RemoteDebuggerPeerTCP::poll() {
}
void RemoteDebuggerPeerTCP::_poll() {
+ tcp_client->poll();
if (connected) {
_write_out();
_read_in();
diff --git a/core/extension/native_extension.cpp b/core/extension/native_extension.cpp
index 34a11758f8..076d04a5eb 100644
--- a/core/extension/native_extension.cpp
+++ b/core/extension/native_extension.cpp
@@ -49,10 +49,10 @@ class NativeExtensionMethodBind : public MethodBind {
bool vararg;
protected:
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
return Variant::Type(get_argument_type_func(method_userdata, p_arg));
}
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
GDNativePropertyInfo pinfo;
get_argument_info_func(method_userdata, p_arg, &pinfo);
PropertyInfo ret;
@@ -66,11 +66,13 @@ protected:
}
public:
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+#ifdef DEBUG_METHODS_ENABLED
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
return GodotTypeInfo::Metadata(get_argument_metadata_func(method_userdata, p_arg));
}
+#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
Variant ret;
GDExtensionClassInstancePtr extension_instance = p_object->_get_extension_instance();
GDNativeCallError ce{ GDNATIVE_CALL_OK, 0, 0 };
@@ -80,16 +82,16 @@ public:
r_error.expected = ce.expected;
return ret;
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
ERR_FAIL_COND_MSG(vararg, "Vararg methods don't have ptrcall support. This is most likely an engine bug.");
GDExtensionClassInstancePtr extension_instance = p_object->_get_extension_instance();
ptrcall_func(method_userdata, extension_instance, (const GDNativeTypePtr *)p_args, (GDNativeTypePtr)r_ret);
}
- virtual bool is_vararg() const {
+ virtual bool is_vararg() const override {
return false;
}
- NativeExtensionMethodBind(const GDNativeExtensionClassMethodInfo *p_method_info) {
+ explicit NativeExtensionMethodBind(const GDNativeExtensionClassMethodInfo *p_method_info) {
method_userdata = p_method_info->method_userdata;
call_func = p_method_info->call_func;
ptrcall_func = p_method_info->ptrcall_func;
diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp
index c6e14ffee7..ba120de68b 100644
--- a/core/io/file_access_pack.cpp
+++ b/core/io/file_access_pack.cpp
@@ -32,6 +32,7 @@
#include "core/io/file_access_encrypted.h"
#include "core/object/script_language.h"
+#include "core/os/os.h"
#include "core/version.h"
#include <stdio.h>
@@ -131,32 +132,69 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files,
return false;
}
- f->seek(p_offset);
+ bool pck_header_found = false;
+ // Search for the header at the start offset - standalone PCK file.
+ f->seek(p_offset);
uint32_t magic = f->get_32();
+ if (magic == PACK_HEADER_MAGIC) {
+ pck_header_found = true;
+ }
- if (magic != PACK_HEADER_MAGIC) {
- // loading with offset feature not supported for self contained exe files
- ERR_FAIL_COND_V_MSG(p_offset != 0, false, "Loading self-contained executable with offset not supported.");
+ // Search for the header in the executable "pck" section - self contained executable.
+ if (!pck_header_found) {
+ // Loading with offset feature not supported for self contained exe files.
+ if (p_offset != 0) {
+ ERR_FAIL_V_MSG(false, "Loading self-contained executable with offset not supported.");
+ }
- //maybe at the end.... self contained exe
- f->seek_end();
- f->seek(f->get_position() - 4);
- magic = f->get_32();
- if (magic != PACK_HEADER_MAGIC) {
- return false;
+ int64_t pck_off = OS::get_singleton()->get_embedded_pck_offset();
+ if (pck_off != 0) {
+ // Search for the header, in case PCK start and section have different alignment.
+ for (int i = 0; i < 8; i++) {
+ f->seek(pck_off);
+ magic = f->get_32();
+ if (magic == PACK_HEADER_MAGIC) {
+#ifdef DEBUG_ENABLED
+ print_verbose("PCK header found in executable pck section, loading from offset 0x" + String::num_int64(pck_off - 4, 16));
+#endif
+ pck_header_found = true;
+ break;
+ }
+ pck_off++;
+ }
}
- f->seek(f->get_position() - 12);
+ }
- uint64_t ds = f->get_64();
- f->seek(f->get_position() - ds - 8);
+ // Search for the header at the end of file - self contained executable.
+ if (!pck_header_found) {
+ // Loading with offset feature not supported for self contained exe files.
+ if (p_offset != 0) {
+ ERR_FAIL_V_MSG(false, "Loading self-contained executable with offset not supported.");
+ }
+ f->seek_end();
+ f->seek(f->get_position() - 4);
magic = f->get_32();
- if (magic != PACK_HEADER_MAGIC) {
- return false;
+
+ if (magic == PACK_HEADER_MAGIC) {
+ f->seek(f->get_position() - 12);
+ uint64_t ds = f->get_64();
+ f->seek(f->get_position() - ds - 8);
+ magic = f->get_32();
+ if (magic == PACK_HEADER_MAGIC) {
+#ifdef DEBUG_ENABLED
+ print_verbose("PCK header found at the end of executable, loading from offset 0x" + String::num_int64(f->get_position() - 4, 16));
+#endif
+ pck_header_found = true;
+ }
}
}
+ if (!pck_header_found) {
+ return false;
+ }
+
uint32_t version = f->get_32();
uint32_t ver_major = f->get_32();
uint32_t ver_minor = f->get_32();
diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h
index 44df2029bd..17e87c835a 100644
--- a/core/io/file_access_pack.h
+++ b/core/io/file_access_pack.h
@@ -93,7 +93,7 @@ private:
PathMD5() {}
- PathMD5(const Vector<uint8_t> &p_buf) {
+ explicit PathMD5(const Vector<uint8_t> &p_buf) {
a = *((uint64_t *)&p_buf[0]);
b = *((uint64_t *)&p_buf[8]);
}
diff --git a/core/io/http_client_tcp.cpp b/core/io/http_client_tcp.cpp
index f920799677..d983d86b99 100644
--- a/core/io/http_client_tcp.cpp
+++ b/core/io/http_client_tcp.cpp
@@ -264,6 +264,9 @@ void HTTPClientTCP::close() {
}
Error HTTPClientTCP::poll() {
+ if (tcp_connection.is_valid()) {
+ tcp_connection->poll();
+ }
switch (status) {
case STATUS_RESOLVING: {
ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG);
diff --git a/core/io/logger.h b/core/io/logger.h
index e3ac00f11c..8ac086e376 100644
--- a/core/io/logger.h
+++ b/core/io/logger.h
@@ -67,7 +67,7 @@ public:
*/
class StdLogger : public Logger {
public:
- virtual void logv(const char *p_format, va_list p_list, bool p_err) _PRINTF_FORMAT_ATTRIBUTE_2_0;
+ virtual void logv(const char *p_format, va_list p_list, bool p_err) override _PRINTF_FORMAT_ATTRIBUTE_2_0;
virtual ~StdLogger() {}
};
@@ -87,19 +87,19 @@ class RotatedFileLogger : public Logger {
void rotate_file();
public:
- RotatedFileLogger(const String &p_base_path, int p_max_files = 10);
+ explicit RotatedFileLogger(const String &p_base_path, int p_max_files = 10);
- virtual void logv(const char *p_format, va_list p_list, bool p_err) _PRINTF_FORMAT_ATTRIBUTE_2_0;
+ virtual void logv(const char *p_format, va_list p_list, bool p_err) override _PRINTF_FORMAT_ATTRIBUTE_2_0;
};
class CompositeLogger : public Logger {
Vector<Logger *> loggers;
public:
- CompositeLogger(Vector<Logger *> p_loggers);
+ explicit CompositeLogger(Vector<Logger *> p_loggers);
- virtual void logv(const char *p_format, va_list p_list, bool p_err) _PRINTF_FORMAT_ATTRIBUTE_2_0;
- virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type = ERR_ERROR);
+ virtual void logv(const char *p_format, va_list p_list, bool p_err) override _PRINTF_FORMAT_ATTRIBUTE_2_0;
+ virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type = ERR_ERROR) override;
void add_logger(Logger *p_logger);
diff --git a/core/io/packet_peer_udp.cpp b/core/io/packet_peer_udp.cpp
index 503eb17cae..84d1f3ebd4 100644
--- a/core/io/packet_peer_udp.cpp
+++ b/core/io/packet_peer_udp.cpp
@@ -242,7 +242,7 @@ Error PacketPeerUDP::connect_to_host(const IPAddress &p_host, int p_port) {
return OK;
}
-bool PacketPeerUDP::is_connected_to_host() const {
+bool PacketPeerUDP::is_socket_connected() const {
return connected;
}
@@ -348,7 +348,7 @@ void PacketPeerUDP::_bind_methods() {
ClassDB::bind_method(D_METHOD("wait"), &PacketPeerUDP::wait);
ClassDB::bind_method(D_METHOD("is_bound"), &PacketPeerUDP::is_bound);
ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port"), &PacketPeerUDP::connect_to_host);
- ClassDB::bind_method(D_METHOD("is_connected_to_host"), &PacketPeerUDP::is_connected_to_host);
+ ClassDB::bind_method(D_METHOD("is_socket_connected"), &PacketPeerUDP::is_socket_connected);
ClassDB::bind_method(D_METHOD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip);
ClassDB::bind_method(D_METHOD("get_packet_port"), &PacketPeerUDP::get_packet_port);
ClassDB::bind_method(D_METHOD("get_local_port"), &PacketPeerUDP::get_local_port);
diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h
index 444a6dd5ba..a174cf5347 100644
--- a/core/io/packet_peer_udp.h
+++ b/core/io/packet_peer_udp.h
@@ -79,7 +79,7 @@ public:
void disconnect_shared_socket(); // Used by UDPServer
Error store_packet(IPAddress p_ip, uint32_t p_port, uint8_t *p_buf, int p_buf_size); // Used internally and by UDPServer
Error connect_to_host(const IPAddress &p_host, int p_port);
- bool is_connected_to_host() const;
+ bool is_socket_connected() const;
IPAddress get_packet_address() const;
int get_packet_port() const;
diff --git a/core/io/resource.cpp b/core/io/resource.cpp
index bf91438810..96efffd49b 100644
--- a/core/io/resource.cpp
+++ b/core/io/resource.cpp
@@ -257,7 +257,7 @@ Ref<Resource> Resource::duplicate(bool p_subresources) const {
List<PropertyInfo> plist;
get_property_list(&plist);
- Ref<Resource> r = (Resource *)ClassDB::instantiate(get_class());
+ Ref<Resource> r = static_cast<Resource *>(ClassDB::instantiate(get_class()));
ERR_FAIL_COND_V(r.is_null(), Ref<Resource>());
for (const PropertyInfo &E : plist) {
diff --git a/core/io/stream_peer_tcp.cpp b/core/io/stream_peer_tcp.cpp
index 6d5784a8ab..c5c2021e6e 100644
--- a/core/io/stream_peer_tcp.cpp
+++ b/core/io/stream_peer_tcp.cpp
@@ -32,8 +32,28 @@
#include "core/config/project_settings.h"
-Error StreamPeerTCP::_poll_connection() {
- ERR_FAIL_COND_V(status != STATUS_CONNECTING || !_sock.is_valid() || !_sock->is_open(), FAILED);
+Error StreamPeerTCP::poll() {
+ if (status == STATUS_CONNECTED) {
+ Error err;
+ err = _sock->poll(NetSocket::POLL_TYPE_IN, 0);
+ if (err == OK) {
+ // FIN received
+ if (_sock->get_available_bytes() == 0) {
+ disconnect_from_host();
+ return OK;
+ }
+ }
+ // Also poll write
+ err = _sock->poll(NetSocket::POLL_TYPE_IN_OUT, 0);
+ if (err != OK && err != ERR_BUSY) {
+ // Got an error
+ disconnect_from_host();
+ status = STATUS_ERROR;
+ return err;
+ }
+ } else if (status != STATUS_CONNECTING) {
+ return OK;
+ }
Error err = _sock->connect_to_host(peer_host, peer_port);
@@ -121,22 +141,7 @@ Error StreamPeerTCP::connect_to_host(const IPAddress &p_host, int p_port) {
Error StreamPeerTCP::write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block) {
ERR_FAIL_COND_V(!_sock.is_valid(), ERR_UNAVAILABLE);
- if (status == STATUS_NONE || status == STATUS_ERROR) {
- return FAILED;
- }
-
if (status != STATUS_CONNECTED) {
- if (_poll_connection() != OK) {
- return FAILED;
- }
-
- if (status != STATUS_CONNECTED) {
- r_sent = 0;
- return OK;
- }
- }
-
- if (!_sock->is_open()) {
return FAILED;
}
@@ -179,21 +184,10 @@ Error StreamPeerTCP::write(const uint8_t *p_data, int p_bytes, int &r_sent, bool
}
Error StreamPeerTCP::read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block) {
- if (!is_connected_to_host()) {
+ if (status != STATUS_CONNECTED) {
return FAILED;
}
- if (status == STATUS_CONNECTING) {
- if (_poll_connection() != OK) {
- return FAILED;
- }
-
- if (status != STATUS_CONNECTED) {
- r_received = 0;
- return OK;
- }
- }
-
Error err;
int to_read = p_bytes;
int total_read = 0;
@@ -243,36 +237,11 @@ Error StreamPeerTCP::read(uint8_t *p_buffer, int p_bytes, int &r_received, bool
}
void StreamPeerTCP::set_no_delay(bool p_enabled) {
- ERR_FAIL_COND(!is_connected_to_host());
+ ERR_FAIL_COND(!_sock.is_valid() || !_sock->is_open());
_sock->set_tcp_no_delay_enabled(p_enabled);
}
-bool StreamPeerTCP::is_connected_to_host() const {
- return _sock.is_valid() && _sock->is_open() && (status == STATUS_CONNECTED || status == STATUS_CONNECTING);
-}
-
-StreamPeerTCP::Status StreamPeerTCP::get_status() {
- if (status == STATUS_CONNECTING) {
- _poll_connection();
- } else if (status == STATUS_CONNECTED) {
- Error err;
- err = _sock->poll(NetSocket::POLL_TYPE_IN, 0);
- if (err == OK) {
- // FIN received
- if (_sock->get_available_bytes() == 0) {
- disconnect_from_host();
- return status;
- }
- }
- // Also poll write
- err = _sock->poll(NetSocket::POLL_TYPE_IN_OUT, 0);
- if (err != OK && err != ERR_BUSY) {
- // Got an error
- disconnect_from_host();
- status = STATUS_ERROR;
- }
- }
-
+StreamPeerTCP::Status StreamPeerTCP::get_status() const {
return status;
}
@@ -287,7 +256,7 @@ void StreamPeerTCP::disconnect_from_host() {
peer_port = 0;
}
-Error StreamPeerTCP::poll(NetSocket::PollType p_type, int timeout) {
+Error StreamPeerTCP::wait(NetSocket::PollType p_type, int timeout) {
ERR_FAIL_COND_V(_sock.is_null() || !_sock->is_open(), ERR_UNAVAILABLE);
return _sock->poll(p_type, timeout);
}
@@ -346,7 +315,7 @@ Error StreamPeerTCP::_connect(const String &p_address, int p_port) {
void StreamPeerTCP::_bind_methods() {
ClassDB::bind_method(D_METHOD("bind", "port", "host"), &StreamPeerTCP::bind, DEFVAL("*"));
ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port"), &StreamPeerTCP::_connect);
- ClassDB::bind_method(D_METHOD("is_connected_to_host"), &StreamPeerTCP::is_connected_to_host);
+ ClassDB::bind_method(D_METHOD("poll"), &StreamPeerTCP::poll);
ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerTCP::get_status);
ClassDB::bind_method(D_METHOD("get_connected_host"), &StreamPeerTCP::get_connected_host);
ClassDB::bind_method(D_METHOD("get_connected_port"), &StreamPeerTCP::get_connected_port);
diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h
index bf49cc8a5f..39c2e84346 100644
--- a/core/io/stream_peer_tcp.h
+++ b/core/io/stream_peer_tcp.h
@@ -55,7 +55,6 @@ protected:
uint16_t peer_port = 0;
Error _connect(const String &p_address, int p_port);
- Error _poll_connection();
Error write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block);
Error read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block);
@@ -66,19 +65,21 @@ public:
Error bind(int p_port, const IPAddress &p_host);
Error connect_to_host(const IPAddress &p_host, int p_port);
- bool is_connected_to_host() const;
IPAddress get_connected_host() const;
int get_connected_port() const;
int get_local_port() const;
void disconnect_from_host();
int get_available_bytes() const override;
- Status get_status();
+ Status get_status() const;
void set_no_delay(bool p_enabled);
- // Poll functions (wait or check for writable, readable)
- Error poll(NetSocket::PollType p_type, int timeout = 0);
+ // Poll socket updating its state.
+ Error poll();
+
+ // Wait or check for writable, readable.
+ Error wait(NetSocket::PollType p_type, int timeout = 0);
// Read/Write from StreamPeer
Error put_data(const uint8_t *p_data, int p_bytes) override;
diff --git a/core/math/convex_hull.cpp b/core/math/convex_hull.cpp
index bd292f4c2a..23a0b5dd54 100644
--- a/core/math/convex_hull.cpp
+++ b/core/math/convex_hull.cpp
@@ -509,7 +509,7 @@ public:
Face() {
}
- void init(Vertex *p_a, Vertex *p_b, Vertex *p_c) {
+ void init(Vertex *p_a, const Vertex *p_b, const Vertex *p_c) {
nearby_vertex = p_a;
origin = p_a->point;
dir0 = *p_b - *p_a;
@@ -614,7 +614,7 @@ private:
static Orientation get_orientation(const Edge *p_prev, const Edge *p_next, const Point32 &p_s, const Point32 &p_t);
Edge *find_max_angle(bool p_ccw, const Vertex *p_start, const Point32 &p_s, const Point64 &p_rxs, const Point64 &p_ssxrxs, Rational64 &p_min_cot);
- void find_edge_for_coplanar_faces(Vertex *p_c0, Vertex *p_c1, Edge *&p_e0, Edge *&p_e1, Vertex *p_stop0, Vertex *p_stop1);
+ void find_edge_for_coplanar_faces(Vertex *p_c0, Vertex *p_c1, Edge *&p_e0, Edge *&p_e1, const Vertex *p_stop0, const Vertex *p_stop1);
Edge *new_edge_pair(Vertex *p_from, Vertex *p_to);
@@ -1189,7 +1189,7 @@ ConvexHullInternal::Edge *ConvexHullInternal::find_max_angle(bool p_ccw, const V
return min_edge;
}
-void ConvexHullInternal::find_edge_for_coplanar_faces(Vertex *p_c0, Vertex *p_c1, Edge *&p_e0, Edge *&p_e1, Vertex *p_stop0, Vertex *p_stop1) {
+void ConvexHullInternal::find_edge_for_coplanar_faces(Vertex *p_c0, Vertex *p_c1, Edge *&p_e0, Edge *&p_e1, const Vertex *p_stop0, const Vertex *p_stop1) {
Edge *start0 = p_e0;
Edge *start1 = p_e1;
Point32 et0 = start0 ? start0->target->point : p_c0->point;
diff --git a/core/math/geometry_3d.cpp b/core/math/geometry_3d.cpp
index bd22bffb1f..f76de079e4 100644
--- a/core/math/geometry_3d.cpp
+++ b/core/math/geometry_3d.cpp
@@ -904,8 +904,8 @@ Vector<Vector3> Geometry3D::compute_convex_mesh_points(const Plane *p_planes, in
/* dt of 1d function using squared distance */
static void edt(float *f, int stride, int n) {
float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
- int *v = (int *)&(d[n]);
- float *z = (float *)&v[n];
+ int *v = reinterpret_cast<int *>(&(d[n]));
+ float *z = reinterpret_cast<float *>(&v[n]);
int k = 0;
v[0] = 0;
diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h
index b741277872..068bc0397e 100644
--- a/core/math/math_funcs.h
+++ b/core/math/math_funcs.h
@@ -103,6 +103,9 @@ public:
static _ALWAYS_INLINE_ double log(double p_x) { return ::log(p_x); }
static _ALWAYS_INLINE_ float log(float p_x) { return ::logf(p_x); }
+ static _ALWAYS_INLINE_ double log1p(double p_x) { return ::log1p(p_x); }
+ static _ALWAYS_INLINE_ float log1p(float p_x) { return ::log1pf(p_x); }
+
static _ALWAYS_INLINE_ double log2(double p_x) { return ::log2(p_x); }
static _ALWAYS_INLINE_ float log2(float p_x) { return ::log2f(p_x); }
diff --git a/core/object/class_db.cpp b/core/object/class_db.cpp
index fd86a02b90..61ce965bc3 100644
--- a/core/object/class_db.cpp
+++ b/core/object/class_db.cpp
@@ -37,6 +37,8 @@
#define OBJTYPE_RLOCK RWLockRead _rw_lockr_(lock);
#define OBJTYPE_WLOCK RWLockWrite _rw_lockw_(lock);
+#ifdef DEBUG_METHODS_ENABLED
+
MethodDefinition D_METHOD(const char *p_name) {
MethodDefinition md;
md.name = StaticCString::create(p_name);
@@ -224,6 +226,8 @@ MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_
return md;
}
+#endif
+
ClassDB::APIType ClassDB::current_api = API_CORE;
void ClassDB::set_current_api(APIType p_api) {
@@ -1420,8 +1424,13 @@ void ClassDB::bind_method_custom(const StringName &p_class, MethodBind *p_method
type->method_map[p_method->get_name()] = p_method;
}
+#ifdef DEBUG_METHODS_ENABLED
MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) {
StringName mdname = method_name.name;
+#else
+MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount) {
+ StringName mdname = StaticCString::create(method_name);
+#endif
OBJTYPE_WLOCK;
ERR_FAIL_COND_V(!p_bind, nullptr);
diff --git a/core/object/class_db.h b/core/object/class_db.h
index 5da8523743..333a3307e2 100644
--- a/core/object/class_db.h
+++ b/core/object/class_db.h
@@ -45,6 +45,8 @@
#define DEFVAL(m_defval) (m_defval)
+#ifdef DEBUG_METHODS_ENABLED
+
struct MethodDefinition {
StringName name;
Vector<StringName> args;
@@ -70,6 +72,14 @@ MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_
MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10, const char *p_arg11, const char *p_arg12);
MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10, const char *p_arg11, const char *p_arg12, const char *p_arg13);
+#else
+
+// When DEBUG_METHODS_ENABLED is set this will let the engine know
+// the argument names for easier debugging.
+#define D_METHOD(m_c, ...) m_c
+
+#endif
+
class ClassDB {
public:
enum APIType {
@@ -134,7 +144,11 @@ public:
static HashMap<StringName, StringName> resource_base_extensions;
static HashMap<StringName, StringName> compat_classes;
+#ifdef DEBUG_METHODS_ENABLED
static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount);
+#else
+ static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount);
+#endif
static APIType current_api;
diff --git a/core/object/method_bind.cpp b/core/object/method_bind.cpp
index a79adb7c6c..a208c1a2b2 100644
--- a/core/object/method_bind.cpp
+++ b/core/object/method_bind.cpp
@@ -69,8 +69,6 @@ PropertyInfo MethodBind::get_argument_info(int p_argument) const {
PropertyInfo info = _gen_argument_type_info(p_argument);
#ifdef DEBUG_METHODS_ENABLED
info.name = p_argument < arg_names.size() ? String(arg_names[p_argument]) : String("arg" + itos(p_argument));
-#else
- info.name = String("arg" + itos(p_argument));
#endif
return info;
}
diff --git a/core/object/method_bind.h b/core/object/method_bind.h
index bde6cba199..2870195911 100644
--- a/core/object/method_bind.h
+++ b/core/object/method_bind.h
@@ -152,7 +152,7 @@ protected:
MethodInfo method_info;
public:
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
if (p_arg < 0) {
return _gen_return_type_info();
} else if (p_arg < method_info.arguments.size()) {
@@ -162,23 +162,23 @@ public:
}
}
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
return _gen_argument_type_info(p_arg).type;
}
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int) const override {
return GodotTypeInfo::METADATA_NONE;
}
#endif
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
ERR_FAIL(); // Can't call.
}
virtual bool is_const() const { return false; }
- virtual bool is_vararg() const { return true; }
+ virtual bool is_vararg() const override { return true; }
MethodBindVarArgBase(
R (T::*p_method)(const Variant **, int, Callable::CallError &),
@@ -224,7 +224,7 @@ class MethodBindVarArgT : public MethodBindVarArgBase<MethodBindVarArgT<T>, T, v
friend class MethodBindVarArgBase<MethodBindVarArgT<T>, T, void, false>;
public:
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
(static_cast<T *>(p_object)->*MethodBindVarArgBase<MethodBindVarArgT<T>, T, void, false>::method)(p_args, p_arg_count, r_error);
return {};
}
@@ -255,7 +255,7 @@ class MethodBindVarArgTR : public MethodBindVarArgBase<MethodBindVarArgTR<T, R>,
friend class MethodBindVarArgBase<MethodBindVarArgTR<T, R>, T, R, true>;
public:
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
return (static_cast<T *>(p_object)->*MethodBindVarArgBase<MethodBindVarArgTR<T, R>, T, R, true>::method)(p_args, p_arg_count, r_error);
}
@@ -303,7 +303,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -314,7 +314,7 @@ protected:
#pragma GCC diagnostic pop
#endif
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
return pi;
@@ -322,25 +322,25 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
return call_get_argument_metadata<P...>(p_arg);
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
#ifdef TYPED_METHOD_BIND
call_with_variant_args_dv(static_cast<T *>(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
#else
- call_with_variant_args_dv((MB_T *)(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
+ call_with_variant_args_dv(reinterpret_cast<MB_T *>(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
#endif
return Variant();
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
#ifdef TYPED_METHOD_BIND
call_with_ptr_args<T, P...>(static_cast<T *>(p_object), method, p_args);
#else
- call_with_ptr_args<MB_T, P...>((MB_T *)(p_object), method, p_args);
+ call_with_ptr_args<MB_T, P...>(reinterpret_cast<MB_T *>(p_object), method, p_args);
#endif
}
@@ -378,7 +378,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -389,7 +389,7 @@ protected:
#pragma GCC diagnostic pop
#endif
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
return pi;
@@ -397,25 +397,25 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
return call_get_argument_metadata<P...>(p_arg);
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
#ifdef TYPED_METHOD_BIND
call_with_variant_argsc_dv(static_cast<T *>(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
#else
- call_with_variant_argsc_dv((MB_T *)(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
+ call_with_variant_argsc_dv(reinterpret_cast<MB_T *>(p_object), method, p_args, p_arg_count, r_error, get_default_arguments());
#endif
return Variant();
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
#ifdef TYPED_METHOD_BIND
call_with_ptr_argsc<T, P...>(static_cast<T *>(p_object), method, p_args);
#else
- call_with_ptr_argsc<MB_T, P...>((MB_T *)(p_object), method, p_args);
+ call_with_ptr_argsc<MB_T, P...>(reinterpret_cast<MB_T *>(p_object), method, p_args);
#endif
}
@@ -455,7 +455,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -463,7 +463,7 @@ protected:
}
}
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
@@ -478,7 +478,7 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
if (p_arg >= 0) {
return call_get_argument_metadata<P...>(p_arg);
} else {
@@ -487,21 +487,21 @@ public:
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
Variant ret;
#ifdef TYPED_METHOD_BIND
call_with_variant_args_ret_dv(static_cast<T *>(p_object), method, p_args, p_arg_count, ret, r_error, get_default_arguments());
#else
- call_with_variant_args_ret_dv((MB_T *)p_object, method, p_args, p_arg_count, ret, r_error, get_default_arguments());
+ call_with_variant_args_ret_dv(reinterpret_cast<MB_T *>(p_object), method, p_args, p_arg_count, ret, r_error, get_default_arguments());
#endif
return ret;
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
#ifdef TYPED_METHOD_BIND
call_with_ptr_args_ret<T, R, P...>(static_cast<T *>(p_object), method, p_args, r_ret);
#else
- call_with_ptr_args_ret<MB_T, R, P...>((MB_T *)(p_object), method, p_args, r_ret);
+ call_with_ptr_args_ret<MB_T, R, P...>(reinterpret_cast<MB_T *>(p_object), method, p_args, r_ret);
#endif
}
@@ -542,7 +542,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -550,7 +550,7 @@ protected:
}
}
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
@@ -565,7 +565,7 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
if (p_arg >= 0) {
return call_get_argument_metadata<P...>(p_arg);
} else {
@@ -574,21 +574,21 @@ public:
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
Variant ret;
#ifdef TYPED_METHOD_BIND
call_with_variant_args_retc_dv(static_cast<T *>(p_object), method, p_args, p_arg_count, ret, r_error, get_default_arguments());
#else
- call_with_variant_args_retc_dv((MB_T *)(p_object), method, p_args, p_arg_count, ret, r_error, get_default_arguments());
+ call_with_variant_args_retc_dv(reinterpret_cast<MB_T *>(p_object), method, p_args, p_arg_count, ret, r_error, get_default_arguments());
#endif
return ret;
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
#ifdef TYPED_METHOD_BIND
call_with_ptr_args_retc<T, R, P...>(static_cast<T *>(p_object), method, p_args, r_ret);
#else
- call_with_ptr_args_retc<MB_T, R, P...>((MB_T *)(p_object), method, p_args, r_ret);
+ call_with_ptr_args_retc<MB_T, R, P...>(reinterpret_cast<MB_T *>(p_object), method, p_args, r_ret);
#endif
}
@@ -626,7 +626,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -637,7 +637,7 @@ protected:
#pragma GCC diagnostic pop
#endif
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
return pi;
@@ -645,18 +645,18 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
return call_get_argument_metadata<P...>(p_arg);
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
(void)p_object; // unused
call_with_variant_args_static_dv(function, p_args, p_arg_count, r_error, get_default_arguments());
return Variant();
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
(void)p_object;
(void)r_ret;
call_with_ptr_args_static_method(function, p_args);
@@ -689,7 +689,7 @@ protected:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif
- virtual Variant::Type _gen_argument_type(int p_arg) const {
+ virtual Variant::Type _gen_argument_type(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
return call_get_argument_type<P...>(p_arg);
} else {
@@ -700,7 +700,7 @@ protected:
#pragma GCC diagnostic pop
#endif
- virtual PropertyInfo _gen_argument_type_info(int p_arg) const {
+ virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
PropertyInfo pi;
call_get_argument_type_info<P...>(p_arg, pi);
@@ -712,7 +712,7 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
- virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const {
+ virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
if (p_arg >= 0) {
return call_get_argument_metadata<P...>(p_arg);
} else {
@@ -721,13 +721,13 @@ public:
}
#endif
- virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) override {
Variant ret;
call_with_variant_args_static_ret_dv(function, p_args, p_arg_count, ret, r_error, get_default_arguments());
return ret;
}
- virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) override {
(void)p_object;
call_with_ptr_args_static_method_ret(function, p_args, r_ret);
}
diff --git a/core/os/keyboard.h b/core/os/keyboard.h
index a21d81b2e7..3176a8a210 100644
--- a/core/os/keyboard.h
+++ b/core/os/keyboard.h
@@ -294,7 +294,7 @@ enum class Key {
enum class KeyModifierMask {
CODE_MASK = ((1 << 25) - 1), ///< Apply this mask to any keycode to remove modifiers.
- MODIFIER_MASK = (0xFF << 24), ///< Apply this mask to isolate modifiers.
+ MODIFIER_MASK = (0x7F << 24), ///< Apply this mask to isolate modifiers.
SHIFT = (1 << 25),
ALT = (1 << 26),
META = (1 << 27),
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 846aeb16c5..4f7095b0fc 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -237,6 +237,11 @@ String OS::get_locale_language() const {
return get_locale().left(3).replace("_", "");
}
+// Embedded PCK offset.
+uint64_t OS::get_embedded_pck_offset() const {
+ return 0;
+}
+
// Helper function to ensure that a dir name/path will be valid on the OS
String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator) const {
Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
diff --git a/core/os/os.h b/core/os/os.h
index b3c66ff18c..9ec0dd7728 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -264,6 +264,8 @@ public:
virtual String get_locale() const;
String get_locale_language() const;
+ virtual uint64_t get_embedded_pck_offset() const;
+
String get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator = false) const;
virtual String get_godot_dir_name() const;
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp
index 7199121932..a2b1e4c428 100644
--- a/core/string/ustring.cpp
+++ b/core/string/ustring.cpp
@@ -4124,15 +4124,11 @@ String String::path_to(const String &p_path) const {
dst += "/";
}
- String base;
-
if (src.begins_with("res://") && dst.begins_with("res://")) {
- base = "res:/";
src = src.replace("res://", "/");
dst = dst.replace("res://", "/");
} else if (src.begins_with("user://") && dst.begins_with("user://")) {
- base = "user:/";
src = src.replace("user://", "/");
dst = dst.replace("user://", "/");
@@ -4147,7 +4143,6 @@ String String::path_to(const String &p_path) const {
return p_path; //impossible to do this
}
- base = src_begin;
src = src.substr(src_begin.length(), src.length());
dst = dst.substr(dst_begin.length(), dst.length());
}
diff --git a/core/templates/oa_hash_map.h b/core/templates/oa_hash_map.h
index e4d9323c45..25c21d1802 100644
--- a/core/templates/oa_hash_map.h
+++ b/core/templates/oa_hash_map.h
@@ -246,13 +246,17 @@ public:
return false;
}
- /**
- * returns true if the value was found, false otherwise.
- *
- * if r_data is not nullptr then the value will be written to the object
- * it points to.
- */
- TValue *lookup_ptr(const TKey &p_key) const {
+ const TValue *lookup_ptr(const TKey &p_key) const {
+ uint32_t pos = 0;
+ bool exists = _lookup_pos(p_key, pos);
+
+ if (exists) {
+ return &values[pos];
+ }
+ return nullptr;
+ }
+
+ TValue *lookup_ptr(const TKey &p_key) {
uint32_t pos = 0;
bool exists = _lookup_pos(p_key, pos);
diff --git a/core/variant/variant.cpp b/core/variant/variant.cpp
index b3e909b489..da5d73d519 100644
--- a/core/variant/variant.cpp
+++ b/core/variant/variant.cpp
@@ -184,7 +184,7 @@ bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) {
if (p_type_from == p_type_to) {
return true;
}
- if (p_type_to == NIL && p_type_from != NIL) { //nil can convert to anything
+ if (p_type_to == NIL) { //nil can convert to anything
return true;
}
@@ -490,7 +490,7 @@ bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type
if (p_type_from == p_type_to) {
return true;
}
- if (p_type_to == NIL && p_type_from != NIL) { //nil can convert to anything
+ if (p_type_to == NIL) { //nil can convert to anything
return true;
}
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index f1daf1de13..9dae0720d9 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -1239,10 +1239,10 @@ void Variant::get_method_list(List<MethodInfo> *p_list) const {
void Variant::get_constants_for_type(Variant::Type p_type, List<StringName> *p_constants) {
ERR_FAIL_INDEX(p_type, Variant::VARIANT_MAX);
- _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type];
+ const _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type];
#ifdef DEBUG_ENABLED
- for (List<StringName>::Element *E = cd.value_ordered.front(); E; E = E->next()) {
+ for (const List<StringName>::Element *E = cd.value_ordered.front(); E; E = E->next()) {
p_constants->push_back(E->get());
#else
for (const KeyValue<StringName, int> &E : cd.value) {
@@ -1251,7 +1251,7 @@ void Variant::get_constants_for_type(Variant::Type p_type, List<StringName> *p_c
}
#ifdef DEBUG_ENABLED
- for (List<StringName>::Element *E = cd.variant_value_ordered.front(); E; E = E->next()) {
+ for (const List<StringName>::Element *E = cd.variant_value_ordered.front(); E; E = E->next()) {
p_constants->push_back(E->get());
#else
for (const KeyValue<StringName, Variant> &E : cd.variant_value) {
diff --git a/core/variant/variant_parser.cpp b/core/variant/variant_parser.cpp
index e889a1bb40..5fc6df8f39 100644
--- a/core/variant/variant_parser.cpp
+++ b/core/variant/variant_parser.cpp
@@ -344,7 +344,6 @@ Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, Stri
if (string_name) {
r_token.type = TK_STRING_NAME;
r_token.value = StringName(str);
- string_name = false; //reset
} else {
r_token.type = TK_STRING;
r_token.value = str;
diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml
index da6513a08b..0021b2f857 100644
--- a/doc/classes/@GlobalScope.xml
+++ b/doc/classes/@GlobalScope.xml
@@ -266,7 +266,7 @@
- Greater than 1.0 (exclusive): Ease in
[/codeblock]
[url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/ease_cheatsheet.png]ease() curve values cheatsheet[/url]
- See also [method smoothstep]. If you need to perform more advanced transitions, use [Tween] or [AnimationPlayer].
+ See also [method smoothstep]. If you need to perform more advanced transitions, use [method Tween.interpolate_value].
</description>
</method>
<method name="error_string">
@@ -2013,7 +2013,7 @@
<constant name="KEY_CODE_MASK" value="33554431" enum="KeyModifierMask">
Key Code mask.
</constant>
- <constant name="KEY_MODIFIER_MASK" value="-16777216" enum="KeyModifierMask">
+ <constant name="KEY_MODIFIER_MASK" value="2130706432" enum="KeyModifierMask">
Modifier key mask.
</constant>
<constant name="KEY_MASK_SHIFT" value="33554432" enum="KeyModifierMask">
diff --git a/doc/classes/AspectRatioContainer.xml b/doc/classes/AspectRatioContainer.xml
index 742a7276d4..e7847ba05c 100644
--- a/doc/classes/AspectRatioContainer.xml
+++ b/doc/classes/AspectRatioContainer.xml
@@ -7,6 +7,7 @@
Arranges child controls in a way to preserve their aspect ratio automatically whenever the container is resized. Solves the problem where the container size is dynamic and the contents' size needs to adjust accordingly without losing proportions.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<members>
<member name="alignment_horizontal" type="int" setter="set_alignment_horizontal" getter="get_alignment_horizontal" enum="AspectRatioContainer.AlignmentMode" default="1">
diff --git a/doc/classes/BoxContainer.xml b/doc/classes/BoxContainer.xml
index 92fccaa884..c76a178368 100644
--- a/doc/classes/BoxContainer.xml
+++ b/doc/classes/BoxContainer.xml
@@ -7,6 +7,7 @@
Arranges child [Control] nodes vertically or horizontally, and rearranges them automatically when their minimum size changes.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<methods>
<method name="add_spacer">
diff --git a/doc/classes/CenterContainer.xml b/doc/classes/CenterContainer.xml
index 08cdf64cea..f5f32bd325 100644
--- a/doc/classes/CenterContainer.xml
+++ b/doc/classes/CenterContainer.xml
@@ -7,6 +7,7 @@
CenterContainer keeps children controls centered. This container keeps all children to their minimum size, in the center.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<members>
<member name="use_top_left" type="bool" setter="set_use_top_left" getter="is_using_top_left" default="false">
diff --git a/doc/classes/Container.xml b/doc/classes/Container.xml
index 11b20b5654..900997d119 100644
--- a/doc/classes/Container.xml
+++ b/doc/classes/Container.xml
@@ -8,6 +8,7 @@
A Control can inherit this to create custom container classes.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<methods>
<method name="_get_allowed_size_flags_horizontal" qualifiers="virtual const">
diff --git a/doc/classes/Directory.xml b/doc/classes/Directory.xml
index 7d72cd867c..bd16fd3936 100644
--- a/doc/classes/Directory.xml
+++ b/doc/classes/Directory.xml
@@ -196,7 +196,8 @@
<return type="int" enum="Error" />
<argument index="0" name="path" type="String" />
<description>
- Deletes the target file or an empty directory. The argument can be relative to the current directory, or an absolute path. If the target directory is not empty, the operation will fail.
+ Permanently deletes the target file or an empty directory. The argument can be relative to the current directory, or an absolute path. If the target directory is not empty, the operation will fail.
+ If you don't want to delete the file/directory permanently, use [method OS.move_to_trash] instead.
Returns one of the [enum Error] code constants ([code]OK[/code] on success).
</description>
</method>
diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml
index 0d99c600d5..ede3a1e199 100644
--- a/doc/classes/DisplayServer.xml
+++ b/doc/classes/DisplayServer.xml
@@ -814,6 +814,93 @@
[b]Note:[/b] This method is implemented on Windows.
</description>
</method>
+ <method name="tts_get_voices" qualifiers="const">
+ <return type="Array" />
+ <description>
+ Returns an [Array] of voice information dictionaries.
+ Each [Dictionary] contains two [String] entries:
+ - [code]name[/code] is voice name.
+ - [code]id[/code] is voice identifier.
+ - [code]language[/code] is language code in [code]lang_Variant[/code] format. [code]lang[/code] part is a 2 or 3-letter code based on the ISO-639 standard, in lowercase. And [code]Variant[/code] part is an engine dependent string describing country, region or/and dialect.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_get_voices_for_language" qualifiers="const">
+ <return type="PackedStringArray" />
+ <argument index="0" name="language" type="String" />
+ <description>
+ Returns an [PackedStringArray] of voice identifiers for the [code]language[/code].
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_is_paused" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if the synthesizer is in a paused state.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_is_speaking" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if the synthesizer is generating speech, or have utterance waiting in the queue.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_pause">
+ <return type="void" />
+ <description>
+ Puts the synthesizer into a paused state.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_resume">
+ <return type="void" />
+ <description>
+ Resumes the synthesizer if it was paused.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_set_utterance_callback">
+ <return type="void" />
+ <argument index="0" name="event" type="int" enum="DisplayServer.TTSUtteranceEvent" />
+ <argument index="1" name="callable" type="Callable" />
+ <description>
+ Adds a callback, which is called when the utterance has started, finished, canceled or reached a text boundary.
+ - [code]TTS_UTTERANCE_STARTED[/code], [code]TTS_UTTERANCE_ENDED[/code], and [code]TTS_UTTERANCE_CANCELED[/code] callable's method should take one [int] parameter, the utterance id.
+ - [code]TTS_UTTERANCE_BOUNDARY[/code] callable's method should take two [int] parameters, the index of the character and the utterance id.
+ [b]Note:[/b] The granularity of the boundary callbacks is engine dependent.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_speak">
+ <return type="void" />
+ <argument index="0" name="text" type="String" />
+ <argument index="1" name="voice" type="String" />
+ <argument index="2" name="volume" type="int" default="50" />
+ <argument index="3" name="pitch" type="float" default="1.0" />
+ <argument index="4" name="rate" type="float" default="1.0" />
+ <argument index="5" name="utterance_id" type="int" default="0" />
+ <argument index="6" name="interrupt" type="bool" default="false" />
+ <description>
+ Adds an utterance to the queue. If [code]interrupt[/code] is [code]true[/code], the queue is cleared first.
+ - [code]voice[/code] identifier is one of the [code]"id"[/code] values returned by [method tts_get_voices] or one of the values returned by [method tts_get_voices_for_language].
+ - [code]volume[/code] ranges from [code]0[/code] (lowest) to [code]100[/code] (highest).
+ - [code]pitch[/code] ranges from [code]0.0[/code] (lowest) to [code]2.0[/code] (highest), [code]1.0[/code] is default pitch for the current voice.
+ - [code]rate[/code] ranges from [code]0.1[/code] (lowest) to [code]10.0[/code] (highest), [code]1.0[/code] is a normal speaking rate. Other values act as a percentage relative.
+ - [code]utterance_id[/code] is passed as a parameter to the callback functions.
+ [b]Note:[/b] On Windows and Linux, utterance [code]text[/code] can use SSML markup. SSML support is engine and voice dependent. If the engine does not support SSML, you should strip out all XML markup before calling [method tts_speak].
+ [b]Note:[/b] The granularity of pitch, rate, and volume is engine and voice dependent. Values may be truncated.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
+ <method name="tts_stop">
+ <return type="void" />
+ <description>
+ Stops synthesis in progress and removes all utterances from the queue.
+ [b]Note:[/b] This method is implemented on Android, iOS, HTML5, Linux, macOS, and Windows.
+ </description>
+ </method>
<method name="virtual_keyboard_get_height" qualifiers="const">
<return type="int" />
<description>
@@ -1184,6 +1271,9 @@
</constant>
<constant name="FEATURE_CLIPBOARD_PRIMARY" value="18" enum="Feature">
</constant>
+ <constant name="FEATURE_TEXT_TO_SPEECH" value="19" enum="Feature">
+ Display server supports text-to-speech. See [code]tts_*[/code] methods.
+ </constant>
<constant name="MOUSE_MODE_VISIBLE" value="0" enum="MouseMode">
Makes the mouse cursor visible if it is hidden.
</constant>
@@ -1335,5 +1425,17 @@
- MacOS: [code]NSView*[/code] for the window main view.
- iOS: [code]UIView*[/code] for the window main view.
</constant>
+ <constant name="TTS_UTTERANCE_STARTED" value="0" enum="TTSUtteranceEvent">
+ Utterance has begun to be spoken.
+ </constant>
+ <constant name="TTS_UTTERANCE_ENDED" value="1" enum="TTSUtteranceEvent">
+ Utterance was successfully finished.
+ </constant>
+ <constant name="TTS_UTTERANCE_CANCELED" value="2" enum="TTSUtteranceEvent">
+ Utterance was canceled, or TTS service was unable to process it.
+ </constant>
+ <constant name="TTS_UTTERANCE_BOUNDARY" value="3" enum="TTSUtteranceEvent">
+ Utterance reached a word or sentence boundary.
+ </constant>
</constants>
</class>
diff --git a/doc/classes/EditorPlugin.xml b/doc/classes/EditorPlugin.xml
index d28bf80a1e..7bbb2ae26c 100644
--- a/doc/classes/EditorPlugin.xml
+++ b/doc/classes/EditorPlugin.xml
@@ -470,6 +470,12 @@
Returns the [EditorInterface] object that gives you control over Godot editor's window and its functionalities.
</description>
</method>
+ <method name="get_export_as_menu">
+ <return type="PopupMenu" />
+ <description>
+ Returns the [PopupMenu] under [b]Scene &gt; Export As...[/b].
+ </description>
+ </method>
<method name="get_script_create_dialog">
<return type="ScriptCreateDialog" />
<description>
diff --git a/doc/classes/GPUParticles2D.xml b/doc/classes/GPUParticles2D.xml
index 3de0d0dbe9..53894bad87 100644
--- a/doc/classes/GPUParticles2D.xml
+++ b/doc/classes/GPUParticles2D.xml
@@ -57,6 +57,9 @@
<member name="fract_delta" type="bool" setter="set_fractional_delta" getter="get_fractional_delta" default="true">
If [code]true[/code], results in fractional delta calculation which has a smoother particles display effect.
</member>
+ <member name="interpolate" type="bool" setter="set_interpolate" getter="get_interpolate" default="true">
+ Enables particle interpolation, which makes the particle movement smoother when their [member fixed_fps] is lower than the screen refresh rate.
+ </member>
<member name="lifetime" type="float" setter="set_lifetime" getter="get_lifetime" default="1.0">
Amount of time each particle will exist.
</member>
diff --git a/doc/classes/GPUParticles3D.xml b/doc/classes/GPUParticles3D.xml
index 899b5dec27..c4bd18db69 100644
--- a/doc/classes/GPUParticles3D.xml
+++ b/doc/classes/GPUParticles3D.xml
@@ -90,6 +90,7 @@
If [code]true[/code], results in fractional delta calculation which has a smoother particles display effect.
</member>
<member name="interpolate" type="bool" setter="set_interpolate" getter="get_interpolate" default="true">
+ Enables particle interpolation, which makes the particle movement smoother when their [member fixed_fps] is lower than the screen refresh rate.
</member>
<member name="lifetime" type="float" setter="set_lifetime" getter="get_lifetime" default="1.0">
Amount of time each particle will exist.
diff --git a/doc/classes/GridContainer.xml b/doc/classes/GridContainer.xml
index bb27c35785..8b7a0fe407 100644
--- a/doc/classes/GridContainer.xml
+++ b/doc/classes/GridContainer.xml
@@ -9,6 +9,7 @@
[b]Note:[/b] GridContainer only works with child nodes inheriting from Control. It won't rearrange child nodes inheriting from Node2D.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
<link title="OS Test Demo">https://godotengine.org/asset-library/asset/677</link>
</tutorials>
<members>
diff --git a/doc/classes/HBoxContainer.xml b/doc/classes/HBoxContainer.xml
index 0af9f7a0f4..21267215eb 100644
--- a/doc/classes/HBoxContainer.xml
+++ b/doc/classes/HBoxContainer.xml
@@ -7,6 +7,7 @@
Horizontal box container. See [BoxContainer].
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<theme_items>
<theme_item name="separation" data_type="constant" type="int" default="4">
diff --git a/doc/classes/HSplitContainer.xml b/doc/classes/HSplitContainer.xml
index f240718176..8137e26b8c 100644
--- a/doc/classes/HSplitContainer.xml
+++ b/doc/classes/HSplitContainer.xml
@@ -7,6 +7,7 @@
Horizontal split container. See [SplitContainer]. This goes from left to right.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<theme_items>
<theme_item name="autohide" data_type="constant" type="int" default="1">
diff --git a/doc/classes/Input.xml b/doc/classes/Input.xml
index c3552c9f62..948c4b253f 100644
--- a/doc/classes/Input.xml
+++ b/doc/classes/Input.xml
@@ -376,7 +376,8 @@
<argument index="0" name="duration_ms" type="int" default="500" />
<description>
Vibrate Android and iOS devices.
- [b]Note:[/b] It needs [code]VIBRATE[/code] permission for Android at export settings. iOS does not support duration.
+ [b]Note:[/b] For Android, it requires enabling the [code]VIBRATE[/code] permission in the export preset.
+ [b]Note:[/b] For iOS, specifying the duration is supported in iOS 13 and later.
</description>
</method>
<method name="warp_mouse">
diff --git a/doc/classes/Label3D.xml b/doc/classes/Label3D.xml
index c95b691bf3..fbb53715c4 100644
--- a/doc/classes/Label3D.xml
+++ b/doc/classes/Label3D.xml
@@ -92,6 +92,9 @@
<member name="no_depth_test" type="bool" setter="set_draw_flag" getter="get_draw_flag" default="false">
If [code]true[/code], depth testing is disabled and the object will be drawn in render order.
</member>
+ <member name="offset" type="Vector2" setter="set_offset" getter="get_offset" default="Vector2(0, 0)">
+ The text drawing offset (in pixels).
+ </member>
<member name="outline_modulate" type="Color" setter="set_outline_modulate" getter="get_outline_modulate" default="Color(0, 0, 0, 1)">
The tint of [Font]'s outline.
</member>
diff --git a/doc/classes/MarginContainer.xml b/doc/classes/MarginContainer.xml
index 3f9f93a39b..3b2ace8475 100644
--- a/doc/classes/MarginContainer.xml
+++ b/doc/classes/MarginContainer.xml
@@ -26,6 +26,7 @@
[/codeblocks]
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<theme_items>
<theme_item name="margin_bottom" data_type="constant" type="int" default="0">
diff --git a/doc/classes/MultiplayerAPI.xml b/doc/classes/MultiplayerAPI.xml
index ac17886183..059d147979 100644
--- a/doc/classes/MultiplayerAPI.xml
+++ b/doc/classes/MultiplayerAPI.xml
@@ -6,7 +6,7 @@
<description>
This class implements the high-level multiplayer API. See also [MultiplayerPeer].
By default, [SceneTree] has a reference to this class that is used to provide multiplayer capabilities (i.e. RPCs) across the whole scene.
- It is possible to override the MultiplayerAPI instance used by specific Nodes by setting the [member Node.custom_multiplayer] property, effectively allowing to run both client and server in the same scene.
+ It is possible to override the MultiplayerAPI instance used by specific tree branches by calling the [method SceneTree.set_multiplayer] method, effectively allowing to run both client and server in the same scene.
[b]Note:[/b] The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice.
[b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android.
</description>
@@ -53,7 +53,7 @@
<method name="poll">
<return type="void" />
<description>
- Method used for polling the MultiplayerAPI. You only need to worry about this if you are using [member Node.custom_multiplayer] override or you set [member SceneTree.multiplayer_poll] to [code]false[/code]. By default, [SceneTree] will poll its MultiplayerAPI for you.
+ Method used for polling the MultiplayerAPI. You only need to worry about this if you set [member SceneTree.multiplayer_poll] to [code]false[/code]. By default, [SceneTree] will poll its MultiplayerAPI(s) for you.
[b]Note:[/b] This method results in RPCs being called, so they will be executed in the same context of this function (e.g. [code]_process[/code], [code]physics[/code], [Thread]).
</description>
</method>
diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml
index 75f16e0c1c..c9795856d5 100644
--- a/doc/classes/Node.xml
+++ b/doc/classes/Node.xml
@@ -193,28 +193,45 @@
[b]Note:[/b] It will not work properly if the node contains a script with constructor arguments (i.e. needs to supply arguments to [method Object._init] method). In that case, the node will be duplicated without a script.
</description>
</method>
- <method name="find_nodes" qualifiers="const">
+ <method name="find_child" qualifiers="const">
+ <return type="Node" />
+ <argument index="0" name="pattern" type="String" />
+ <argument index="1" name="recursive" type="bool" default="true" />
+ <argument index="2" name="owned" type="bool" default="true" />
+ <description>
+ Finds the first descendant of this node whose name matches [code]pattern[/code] as in [method String.match].
+ [code]pattern[/code] does not match against the full path, just against individual node names. It is case-sensitive, with [code]"*"[/code] matching zero or more characters and [code]"?"[/code] matching any single character except [code]"."[/code]).
+ If [code]recursive[/code] is [code]true[/code], all child nodes are included, even if deeply nested. Nodes are checked in tree order, so this node's first direct child is checked first, then its own direct children, etc., before moving to the second direct child, and so on. If [code]recursive[/code] is [code]false[/code], only this node's direct children are matched.
+ If [code]owned[/code] is [code]true[/code], this method only finds nodes who have an assigned [member Node.owner]. This is especially important for scenes instantiated through a script, because those scenes don't have an owner.
+ Returns [code]null[/code] if no matching [Node] is found.
+ [b]Note:[/b] As this method walks through all the descendants of the node, it is the slowest way to get a reference to another node. Whenever possible, consider using [method get_node] with unique names instead (see [member unique_name_in_owner]), or caching the node references into variable.
+ [b]Note:[/b] To find all descendant nodes matching a pattern or a class type, see [method find_children].
+ </description>
+ </method>
+ <method name="find_children" qualifiers="const">
<return type="Node[]" />
- <argument index="0" name="mask" type="String" />
+ <argument index="0" name="pattern" type="String" />
<argument index="1" name="type" type="String" default="&quot;&quot;" />
<argument index="2" name="recursive" type="bool" default="true" />
<argument index="3" name="owned" type="bool" default="true" />
<description>
- Finds descendants of this node whose, name matches [code]mask[/code] as in [method String.match], and/or type matches [code]type[/code] as in [method Object.is_class].
- [code]mask[/code] does not match against the full path, just against individual node names. It is case-sensitive, with [code]"*"[/code] matching zero or more characters and [code]"?"[/code] matching any single character except [code]"."[/code]).
- [code]type[/code] will check equality or inheritance. It is case-sensitive, [code]"Object"[/code] will match a node whose type is [code]"Node"[/code] but not the other way around.
- 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 a script, because those scenes don't have an owner.
- Returns an empty array, if no matching nodes are found.
- [b]Note:[/b] As this method walks through all the descendants of the node, it is the slowest way to get references to other nodes. To avoid using [method find_nodes] too often, consider caching the node references into variables.
+ Finds descendants of this node whose name matches [code]pattern[/code] as in [method String.match], and/or type matches [code]type[/code] as in [method Object.is_class].
+ [code]pattern[/code] does not match against the full path, just against individual node names. It is case-sensitive, with [code]"*"[/code] matching zero or more characters and [code]"?"[/code] matching any single character except [code]"."[/code]).
+ [code]type[/code] will check equality or inheritance, and is case-sensitive. [code]"Object"[/code] will match a node whose type is [code]"Node"[/code] but not the other way around.
+ If [code]recursive[/code] is [code]true[/code], all child nodes are included, even if deeply nested. Nodes are checked in tree order, so this node's first direct child is checked first, then its own direct children, etc., before moving to the second direct child, and so on. If [code]recursive[/code] is [code]false[/code], only this node's direct children are matched.
+ If [code]owned[/code] is [code]true[/code], this method only finds nodes who have an assigned [member Node.owner]. This is especially important for scenes instantiated through a script, because those scenes don't have an owner.
+ Returns an empty array if no matching nodes are found.
+ [b]Note:[/b] As this method walks through all the descendants of the node, it is the slowest way to get references to other nodes. Whenever possible, consider caching the node references into variables.
+ [b]Note:[/b] If you only want to find the first descendant node that matches a pattern, see [method find_child].
</description>
</method>
<method name="find_parent" qualifiers="const">
<return type="Node" />
- <argument index="0" name="mask" type="String" />
+ <argument index="0" name="pattern" type="String" />
<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 [code]"*"[/code] matches zero or more characters and [code]"?"[/code] matches any single character except [code]"."[/code]).
- [b]Note:[/b] It does not match against the full path, just against individual node names.
- [b]Note:[/b] As this method walks upwards in the scene tree, it can be slow in large, deeply nested scene trees. Whenever possible, consider using [method get_node] instead. To avoid using [method find_parent] too often, consider caching the node reference into a variable.
+ Finds the first parent of the current node whose name matches [code]pattern[/code] as in [method String.match].
+ [code]pattern[/code] does not match against the full path, just against individual node names. It is case-sensitive, with [code]"*"[/code] matching zero or more characters and [code]"?"[/code] matching any single character except [code]"."[/code]).
+ [b]Note:[/b] As this method walks upwards in the scene tree, it can be slow in large, deeply nested scene trees. Whenever possible, consider using [method get_node] with unique names instead (see [member unique_name_in_owner]), or caching the node references into variable.
</description>
</method>
<method name="get_child" qualifiers="const">
@@ -492,12 +509,6 @@
Returns [code]true[/code] if the node is processing unhandled key input (see [method set_process_unhandled_key_input]).
</description>
</method>
- <method name="is_unique_name_in_owner" qualifiers="const">
- <return type="bool" />
- <description>
- Returns whether the node is an unique name for all the other nodes owned by its [member owner].
- </description>
- </method>
<method name="move_child">
<return type="void" />
<argument index="0" name="child_node" type="Node" />
@@ -725,13 +736,6 @@
Sets whether this is an instance load placeholder. See [InstancePlaceholder].
</description>
</method>
- <method name="set_unique_name_in_owner">
- <return type="void" />
- <argument index="0" name="enable" type="bool" />
- <description>
- Sets this node's name as the unique name in its [member owner]. This allows the node to be accessed as [code]%Name[/code] instead of the full path, from any node within that scene.
- </description>
- </method>
<method name="update_configuration_warnings">
<return type="void" />
<description>
@@ -741,14 +745,11 @@
</method>
</methods>
<members>
- <member name="custom_multiplayer" type="MultiplayerAPI" setter="set_custom_multiplayer" getter="get_custom_multiplayer">
- The override to the default [MultiplayerAPI]. Set to [code]null[/code] to use the default [SceneTree] one.
- </member>
<member name="editor_description" type="String" setter="set_editor_description" getter="get_editor_description" default="&quot;&quot;">
Add a custom description to a node. It will be displayed in a tooltip when hovered in editor's scene tree.
</member>
<member name="multiplayer" type="MultiplayerAPI" setter="" getter="get_multiplayer">
- The [MultiplayerAPI] instance associated with this node. Either the [member custom_multiplayer], or the default SceneTree one (if inside tree).
+ The [MultiplayerAPI] instance associated with this node. See [method SceneTree.get_multiplayer].
</member>
<member name="name" type="StringName" setter="set_name" getter="get_name">
The name of the node. This name is unique among the siblings (other child nodes from the same parent). When set to an existing name, the node will be automatically renamed.
@@ -767,6 +768,10 @@
<member name="scene_file_path" type="String" setter="set_scene_file_path" getter="get_scene_file_path">
If a scene is instantiated from a file, its topmost node contains the absolute file path from which it was loaded in [member scene_file_path] (e.g. [code]res://levels/1.tscn[/code]). Otherwise, [member scene_file_path] is set to an empty string.
</member>
+ <member name="unique_name_in_owner" type="bool" setter="set_unique_name_in_owner" getter="is_unique_name_in_owner" default="false">
+ Sets this node's name as a unique name in its [member owner]. This allows the node to be accessed as [code]%Name[/code] instead of the full path, from any node within that scene.
+ If another node with the same owner already had that name declared as unique, that other node's name will no longer be set as having a unique name.
+ </member>
</members>
<signals>
<signal name="child_entered_tree">
diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index b2e325d226..f45bee4db4 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -455,6 +455,14 @@
[b]Note:[/b] This method is implemented on Android, iOS, Linux, macOS and Windows.
</description>
</method>
+ <method name="move_to_trash" qualifiers="const">
+ <return type="int" enum="Error" />
+ <argument index="0" name="path" type="String" />
+ <description>
+ Moves the file or directory to the system's recycle bin. See also [method Directory.remove].
+ [b]Note:[/b] If the user has disabled the recycle bin on their system, the file will be permanently deleted instead.
+ </description>
+ </method>
<method name="open_midi_inputs">
<return type="void" />
<description>
diff --git a/doc/classes/PacketPeerUDP.xml b/doc/classes/PacketPeerUDP.xml
index 580bf60518..7c6622be3c 100644
--- a/doc/classes/PacketPeerUDP.xml
+++ b/doc/classes/PacketPeerUDP.xml
@@ -61,7 +61,7 @@
Returns whether this [PacketPeerUDP] is bound to an address and can receive packets.
</description>
</method>
- <method name="is_connected_to_host" qualifiers="const">
+ <method name="is_socket_connected" qualifiers="const">
<return type="bool" />
<description>
Returns [code]true[/code] if the UDP socket is open and has been connected to a remote address. See [method connect_to_host].
diff --git a/doc/classes/PanelContainer.xml b/doc/classes/PanelContainer.xml
index 1bb26045d9..fff30e0dc0 100644
--- a/doc/classes/PanelContainer.xml
+++ b/doc/classes/PanelContainer.xml
@@ -7,6 +7,7 @@
Panel container type. This container fits controls inside of the delimited area of a stylebox. It's useful for giving controls an outline.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
<link title="2D Role Playing Game Demo">https://godotengine.org/asset-library/asset/520</link>
</tutorials>
<members>
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index ee32677b3a..7c6d6d1c10 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -578,9 +578,19 @@
<member name="gui/theme/default_font_antialiased" type="bool" setter="" getter="" default="true">
If set to [code]true[/code], default font uses 8-bit anitialiased glyph rendering. See [member FontData.antialiased].
</member>
+ <member name="gui/theme/default_font_generate_mipmaps" type="bool" setter="" getter="" default="false">
+ If set to [code]true[/code], the default font will have mipmaps generated. This prevents text from looking grainy when a [Control] is scaled down, or when a [Label3D] is viewed from a long distance (if [member Label3D.texture_filter] is set to a mode that displays mipmaps).
+ Enabling [member gui/theme/default_font_generate_mipmaps] increases font generation time and memory usage. Only enable this setting if you actually need it.
+ [b]Note:[/b] This setting does not affect custom [Font]s used within the project.
+ </member>
<member name="gui/theme/default_font_hinting" type="int" setter="" getter="" default="1">
Default font hinting mode. See [member FontData.hinting].
</member>
+ <member name="gui/theme/default_font_multichannel_signed_distance_field" type="bool" setter="" getter="" default="false">
+ If set to [code]true[/code], the default font will use multichannel signed distance field (MSDF) for crisp rendering at any size. Since this approach does not rely on rasterizing the font every time its size changes, this allows for resizing the font in real-time without any performance penalty. Text will also not look grainy for [Control]s that are scaled down (or for [Label3D]s viewed from a long distance).
+ MSDF font rendering can be combined with [member gui/theme/default_font_generate_mipmaps] to further improve font rendering quality when scaled down.
+ [b]Note:[/b] This setting does not affect custom [Font]s used within the project.
+ </member>
<member name="gui/theme/default_font_subpixel_positioning" type="int" setter="" getter="" default="1">
Default font glyph sub-pixel positioning mode. See [member FontData.subpixel_positioning].
</member>
diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml
index 77023d2126..ddff766b17 100644
--- a/doc/classes/SceneTree.xml
+++ b/doc/classes/SceneTree.xml
@@ -99,6 +99,13 @@
Returns the current frame number, i.e. the total frame count since the application started.
</description>
</method>
+ <method name="get_multiplayer" qualifiers="const">
+ <return type="MultiplayerAPI" />
+ <argument index="0" name="for_path" type="NodePath" default="NodePath(&quot;&quot;)" />
+ <description>
+ Return the [MultiplayerAPI] configured for the given path, or the default one if [code]for_path[/code] is empty.
+ </description>
+ </method>
<method name="get_node_count" qualifiers="const">
<return type="int" />
<description>
@@ -193,6 +200,14 @@
Sets the given [code]property[/code] to [code]value[/code] on all members of the given group, respecting the given [enum GroupCallFlags].
</description>
</method>
+ <method name="set_multiplayer">
+ <return type="void" />
+ <argument index="0" name="multiplayer" type="MultiplayerAPI" />
+ <argument index="1" name="root_path" type="NodePath" default="NodePath(&quot;&quot;)" />
+ <description>
+ Sets a custom [MultiplayerAPI] with the given [code]root_path[/code] (controlling also the relative subpaths), or override the default one if [code]root_path[/code] is empty.
+ </description>
+ </method>
<method name="set_quit_on_go_back">
<return type="void" />
<argument index="0" name="enabled" type="bool" />
@@ -215,9 +230,6 @@
<member name="edited_scene_root" type="Node" setter="set_edited_scene_root" getter="get_edited_scene_root">
The root of the edited scene.
</member>
- <member name="multiplayer" type="MultiplayerAPI" setter="set_multiplayer" getter="get_multiplayer">
- The default [MultiplayerAPI] instance for this [SceneTree].
- </member>
<member name="multiplayer_poll" type="bool" setter="set_multiplayer_poll_enabled" getter="is_multiplayer_poll_enabled" default="true">
If [code]true[/code] (default value), enables automatic polling of the [MultiplayerAPI] for this SceneTree during [signal process_frame].
If [code]false[/code], you need to manually call [method MultiplayerAPI.poll] to process network packets and deliver RPCs. This allows running RPCs in a different loop (e.g. physics, thread, specific time step) and for manual [Mutex] protection when accessing the [MultiplayerAPI] from threads.
diff --git a/doc/classes/ScrollContainer.xml b/doc/classes/ScrollContainer.xml
index 95255ed79f..658793c4c0 100644
--- a/doc/classes/ScrollContainer.xml
+++ b/doc/classes/ScrollContainer.xml
@@ -9,6 +9,7 @@
Works great with a [Panel] control. You can set [code]EXPAND[/code] on the children's size flags, so they will upscale to the ScrollContainer's size if it's larger (scroll is invisible for the chosen dimension).
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<methods>
<method name="ensure_control_visible">
diff --git a/doc/classes/Skeleton3D.xml b/doc/classes/Skeleton3D.xml
index 80a36acacc..f271220989 100644
--- a/doc/classes/Skeleton3D.xml
+++ b/doc/classes/Skeleton3D.xml
@@ -111,6 +111,14 @@
<return type="Transform3D" />
<argument index="0" name="bone_idx" type="int" />
<description>
+ Returns the global pose override transform for [code]bone_idx[/code].
+ </description>
+ </method>
+ <method name="get_bone_global_rest" qualifiers="const">
+ <return type="Transform3D" />
+ <argument index="0" name="bone_idx" type="int" />
+ <description>
+ Returns the global rest transform for [code]bone_idx[/code].
</description>
</method>
<method name="get_bone_local_pose_override" qualifiers="const">
diff --git a/doc/classes/SplitContainer.xml b/doc/classes/SplitContainer.xml
index b2fcd46731..f2bc65f8df 100644
--- a/doc/classes/SplitContainer.xml
+++ b/doc/classes/SplitContainer.xml
@@ -7,6 +7,7 @@
Container for splitting two [Control]s vertically or horizontally, with a grabber that allows adjusting the split offset or ratio.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<methods>
<method name="clamp_split_offset">
diff --git a/doc/classes/StreamPeerTCP.xml b/doc/classes/StreamPeerTCP.xml
index a1f1f1be79..f06cf5c7a2 100644
--- a/doc/classes/StreamPeerTCP.xml
+++ b/doc/classes/StreamPeerTCP.xml
@@ -51,16 +51,16 @@
Returns the local port to which this peer is bound.
</description>
</method>
- <method name="get_status">
+ <method name="get_status" qualifiers="const">
<return type="int" enum="StreamPeerTCP.Status" />
<description>
Returns the status of the connection, see [enum Status].
</description>
</method>
- <method name="is_connected_to_host" qualifiers="const">
- <return type="bool" />
+ <method name="poll">
+ <return type="int" enum="Error" />
<description>
- Returns [code]true[/code] if this peer is currently connected or is connecting to a host, [code]false[/code] otherwise.
+ Poll the socket, updating its state. See [method get_status].
</description>
</method>
<method name="set_no_delay">
diff --git a/doc/classes/StyleBoxFlat.xml b/doc/classes/StyleBoxFlat.xml
index 20430f3205..c80f8dcbb1 100644
--- a/doc/classes/StyleBoxFlat.xml
+++ b/doc/classes/StyleBoxFlat.xml
@@ -119,7 +119,7 @@
</methods>
<members>
<member name="anti_aliasing" type="bool" setter="set_anti_aliased" getter="is_anti_aliased" default="true">
- Antialiasing draws a small ring around the edges, which fades to transparency. As a result, edges look much smoother. This is only noticeable when using rounded corners.
+ Antialiasing draws a small ring around the edges, which fades to transparency. As a result, edges look much smoother. This is only noticeable when using rounded corners or [member skew].
[b]Note:[/b] When using beveled corners with 45-degree angles ([member corner_detail] = 1), it is recommended to set [member anti_aliasing] to [code]false[/code] to ensure crisp visuals and avoid possible visual glitches.
</member>
<member name="anti_aliasing_size" type="float" setter="set_aa_size" getter="get_aa_size" default="0.625">
@@ -168,15 +168,19 @@
</member>
<member name="expand_margin_bottom" type="float" setter="set_expand_margin" getter="get_expand_margin" default="0.0">
Expands the stylebox outside of the control rect on the bottom edge. Useful in combination with [member border_width_bottom] to draw a border outside the control rect.
+ [b]Note:[/b] Unlike [member StyleBox.content_margin_bottom], [member expand_margin_bottom] does [i]not[/i] affect the size of the clickable area for [Control]s. This can negatively impact usability if used wrong, as the user may try to click an area of the StyleBox that cannot actually receive clicks.
</member>
<member name="expand_margin_left" type="float" setter="set_expand_margin" getter="get_expand_margin" default="0.0">
Expands the stylebox outside of the control rect on the left edge. Useful in combination with [member border_width_left] to draw a border outside the control rect.
+ [b]Note:[/b] Unlike [member StyleBox.content_margin_left], [member expand_margin_left] does [i]not[/i] affect the size of the clickable area for [Control]s. This can negatively impact usability if used wrong, as the user may try to click an area of the StyleBox that cannot actually receive clicks.
</member>
<member name="expand_margin_right" type="float" setter="set_expand_margin" getter="get_expand_margin" default="0.0">
Expands the stylebox outside of the control rect on the right edge. Useful in combination with [member border_width_right] to draw a border outside the control rect.
+ [b]Note:[/b] Unlike [member StyleBox.content_margin_right], [member expand_margin_right] does [i]not[/i] affect the size of the clickable area for [Control]s. This can negatively impact usability if used wrong, as the user may try to click an area of the StyleBox that cannot actually receive clicks.
</member>
<member name="expand_margin_top" type="float" setter="set_expand_margin" getter="get_expand_margin" default="0.0">
Expands the stylebox outside of the control rect on the top edge. Useful in combination with [member border_width_top] to draw a border outside the control rect.
+ [b]Note:[/b] Unlike [member StyleBox.content_margin_top], [member expand_margin_top] does [i]not[/i] affect the size of the clickable area for [Control]s. This can negatively impact usability if used wrong, as the user may try to click an area of the StyleBox that cannot actually receive clicks.
</member>
<member name="shadow_color" type="Color" setter="set_shadow_color" getter="get_shadow_color" default="Color(0, 0, 0, 0.6)">
The color of the shadow. This has no effect if [member shadow_size] is lower than 1.
@@ -187,5 +191,9 @@
<member name="shadow_size" type="int" setter="set_shadow_size" getter="get_shadow_size" default="0">
The shadow size in pixels.
</member>
+ <member name="skew" type="Vector2" setter="set_skew" getter="get_skew" default="Vector2(0, 0)">
+ If set to a non-zero value on either axis, [member skew] distorts the StyleBox horizontally and/or vertically. This can be used for "futuristic"-style UIs. Positive values skew the StyleBox towards the right (X axis) and upwards (Y axis), while negative values skew the StyleBox towards the left (X axis) and downwards (Y axis).
+ [b]Note:[/b] To ensure text does not touch the StyleBox's edges, consider increasing the [StyleBox]'s content margin (see [member StyleBox.content_margin_bottom]). It is preferable to increase the content margin instead of the expand margin (see [member expand_margin_bottom]), as increasing the expand margin does not increase the size of the clickable area for [Control]s.
+ </member>
</members>
</class>
diff --git a/doc/classes/TabContainer.xml b/doc/classes/TabContainer.xml
index 011b716dfc..10b5f730ad 100644
--- a/doc/classes/TabContainer.xml
+++ b/doc/classes/TabContainer.xml
@@ -9,6 +9,7 @@
[b]Note:[/b] The drawing of the clickable tabs themselves is handled by this node. Adding [TabBar]s as children is not needed.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<methods>
<method name="get_current_tab_control" qualifiers="const">
diff --git a/doc/classes/TextServer.xml b/doc/classes/TextServer.xml
index dba4bd24a5..2f57b76374 100644
--- a/doc/classes/TextServer.xml
+++ b/doc/classes/TextServer.xml
@@ -1441,6 +1441,14 @@
Aligns shaped text to the given tab-stops.
</description>
</method>
+ <method name="string_get_word_breaks" qualifiers="const">
+ <return type="PackedInt32Array" />
+ <argument index="0" name="string" type="String" />
+ <argument index="1" name="language" type="String" default="&quot;&quot;" />
+ <description>
+ Returns array of the word break character offsets.
+ </description>
+ </method>
<method name="string_to_lower" qualifiers="const">
<return type="String" />
<argument index="0" name="string" type="String" />
diff --git a/doc/classes/TextServerExtension.xml b/doc/classes/TextServerExtension.xml
index ef522d08a7..434d6f909c 100644
--- a/doc/classes/TextServerExtension.xml
+++ b/doc/classes/TextServerExtension.xml
@@ -1461,6 +1461,14 @@
[b]Note:[/b] This method is used by default line/word breaking methods, and its implementation might be omitted if custom line breaking in implemented.
</description>
</method>
+ <method name="string_get_word_breaks" qualifiers="virtual const">
+ <return type="PackedInt32Array" />
+ <argument index="0" name="string" type="String" />
+ <argument index="1" name="language" type="String" />
+ <description>
+ Returns array of the word break character offsets.
+ </description>
+ </method>
<method name="string_to_lower" qualifiers="virtual const">
<return type="String" />
<argument index="0" name="string" type="String" />
diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml
index 9453bb9e2a..259c800a78 100644
--- a/doc/classes/TileMap.xml
+++ b/doc/classes/TileMap.xml
@@ -330,10 +330,10 @@
[b]Note:[/b] Enabling [code]collision_animatable[/code] may have a small performance impact, only do it if the TileMap is moving and has colliding tiles.
</member>
<member name="collision_visibility_mode" type="int" setter="set_collision_visibility_mode" getter="get_collision_visibility_mode" enum="TileMap.VisibilityMode" default="0">
- Show or hide the TileMap's collision shapes. If set to [code]VISIBILITY_MODE_DEFAULT[/code], this depends on the show collision debug settings.
+ Show or hide the TileMap's collision shapes. If set to [constant VISIBILITY_MODE_DEFAULT], this depends on the show collision debug settings.
</member>
<member name="navigation_visibility_mode" type="int" setter="set_navigation_visibility_mode" getter="get_navigation_visibility_mode" enum="TileMap.VisibilityMode" default="0">
- Show or hide the TileMap's collision shapes. If set to [code]VISIBILITY_MODE_DEFAULT[/code], this depends on the show navigation debug settings.
+ Show or hide the TileMap's collision shapes. If set to [constant VISIBILITY_MODE_DEFAULT], this depends on the show navigation debug settings.
</member>
<member name="tile_set" type="TileSet" setter="set_tileset" getter="get_tileset">
The assigned [TileSet].
diff --git a/doc/classes/Tween.xml b/doc/classes/Tween.xml
index 72f32f39c2..f9ec0d115d 100644
--- a/doc/classes/Tween.xml
+++ b/doc/classes/Tween.xml
@@ -6,7 +6,7 @@
<description>
Tweens are mostly useful for animations requiring a numerical property to be interpolated over a range of values. The name [i]tween[/i] comes from [i]in-betweening[/i], an animation technique where you specify [i]keyframes[/i] and the computer interpolates the frames that appear between them.
[Tween] is more suited than [AnimationPlayer] for animations where you don't know the final values in advance. For example, interpolating a dynamically-chosen camera zoom value is best done with a [Tween]; it would be difficult to do the same thing with an [AnimationPlayer] node. Tweens are also more light-weight than [AnimationPlayer], so they are very much suited for simple animations or general tasks that don't require visual tweaking provided by the editor. They can be used in a fire-and-forget manner for some logic that normally would be done by code. You can e.g. make something shoot periodically by using a looped [CallbackTweener] with a delay.
- A [Tween] can be created by using either [method SceneTree.create_tween] or [method Node.create_tween]. [Tween]s created manually (i.e. by using [code]Tween.new()[/code]) are invalid. They can't be used for tweening values, but you can do manual interpolation with [method interpolate_value].
+ A [Tween] can be created by using either [method SceneTree.create_tween] or [method Node.create_tween]. [Tween]s created manually (i.e. by using [code]Tween.new()[/code]) are invalid and can't be used for tweening values.
A [Tween] animation is composed of a sequence of [Tweener]s, which by default are executed one after another. You can create a sequence by appending [Tweener]s to the [Tween]. Animating something with a [Tweener] is called tweening. Example tweening sequence looks like this:
[codeblock]
var tween = get_tree().create_tween()
@@ -76,10 +76,10 @@
<return type="float" />
<description>
Returns the total time in seconds the [Tween] has been animating (i.e. time since it started, not counting pauses etc.). The time is affected by [method set_speed_scale] and [method stop] will reset it to [code]0[/code].
- [b]Note:[/code] As it results from accumulating frame deltas, the time returned after the [Tween] has finished animating will be slightly greater than the actual [Tween] duration.
+ [b]Note:[/b] As it results from accumulating frame deltas, the time returned after the [Tween] has finished animating will be slightly greater than the actual [Tween] duration.
</description>
</method>
- <method name="interpolate_value">
+ <method name="interpolate_value" qualifiers="static">
<return type="Variant" />
<argument index="0" name="initial_value" type="Variant" />
<argument index="1" name="delta_value" type="Variant" />
@@ -105,7 +105,7 @@
<method name="is_valid">
<return type="bool" />
<description>
- Returns whether the [Tween] is valid. A valid [Tween] is a [Tween] contained by the scene tree (i.e. the array from [method SceneTree.get_processed_tweens] will contain this [Tween]). [Tween] might become invalid when it has finished tweening or was killed, also when created with [code]Tween.new()[/code]. Invalid [Tween] can't have [Tweener]s appended, because it can't animate them. You can however still use [method interpolate_value].
+ Returns whether the [Tween] is valid. A valid [Tween] is a [Tween] contained by the scene tree (i.e. the array from [method SceneTree.get_processed_tweens] will contain this [Tween]). [Tween] might become invalid when it has finished tweening or was killed, also when created with [code]Tween.new()[/code]. Invalid [Tween] can't have [Tweener]s appended, because it can't animate them.
</description>
</method>
<method name="kill">
@@ -231,10 +231,10 @@
Example: creating an object that moves back and forth and jumps every few seconds.
[codeblock]
var tween = create_tween().set_loops()
- tween.tween_property("position:x", 200, 1).as_relative()
+ tween.tween_property($Sprite, "position:x", 200.0, 1).as_relative()
tween.tween_callback(jump)
tween.tween_interval(2)
- tween.tween_property("position:x", -200, 1).as_relative()
+ tween.tween_property($Sprite, "position:x", -200.0, 1).as_relative()
tween.tween_callback(jump)
tween.tween_interval(2)
[/codeblock]
@@ -274,16 +274,16 @@
Creates and appends a [PropertyTweener]. This method tweens a [code]property[/code] of an [code]object[/code] between an initial value and [code]final_val[/code] in a span of time equal to [code]duration[/code], in seconds. The initial value by default is a value at the time the tweening of the [PropertyTweener] start. For example:
[codeblock]
var tween = create_tween()
- tween.tween_property($Sprite, "position", Vector2(100, 200)
- tween.tween_property($Sprite, "position", Vector2(200, 300)
+ tween.tween_property($Sprite, "position", Vector2(100, 200), 1)
+ tween.tween_property($Sprite, "position", Vector2(200, 300), 1)
[/codeblock]
will move the sprite to position (100, 200) and then to (200, 300). If you use [method PropertyTweener.from] or [method PropertyTweener.from_current], the starting position will be overwritten by the given value instead. See other methods in [PropertyTweener] to see how the tweening can be tweaked further.
[b]Note:[/b] You can find the correct property name by hovering over the property in the Inspector. You can also provide the components of a property directly by using [code]"property:component"[/code] (eg. [code]position:x[/code]), where it would only apply to that particular component.
Example: moving object twice from the same position, with different transition types.
[codeblock]
var tween = create_tween()
- tween.tween_property($Sprite, "position", Vector2.RIGHT * 300).as_relative().set_trans(Tween.TRANS_SINE)
- tween.tween_property($Sprite, "position", Vector2.RIGHT * 300).as_relative().from_current().set_trans(Tween.TRANS_EXPO)
+ tween.tween_property($Sprite, "position", Vector2.RIGHT * 300, 1).as_relative().set_trans(Tween.TRANS_SINE)
+ tween.tween_property($Sprite, "position", Vector2.RIGHT * 300, 1).as_relative().from_current().set_trans(Tween.TRANS_EXPO)
[/codeblock]
</description>
</method>
diff --git a/doc/classes/Tweener.xml b/doc/classes/Tweener.xml
index 3392f9ee23..721ed4e13e 100644
--- a/doc/classes/Tweener.xml
+++ b/doc/classes/Tweener.xml
@@ -4,7 +4,7 @@
Abstract class for all Tweeners used by [Tween].
</brief_description>
<description>
- Tweeners are objects that perform a specific animating task, e.g. interpolating a property or calling a method at a given time. A [Tweener] can't be created manually, you need to use a dedicated method from [Tween] or [Node].
+ Tweeners are objects that perform a specific animating task, e.g. interpolating a property or calling a method at a given time. A [Tweener] can't be created manually, you need to use a dedicated method from [Tween].
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/VBoxContainer.xml b/doc/classes/VBoxContainer.xml
index 4821791f50..a345668f91 100644
--- a/doc/classes/VBoxContainer.xml
+++ b/doc/classes/VBoxContainer.xml
@@ -7,6 +7,7 @@
Vertical box container. See [BoxContainer].
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
<link title="3D Voxel Demo">https://godotengine.org/asset-library/asset/676</link>
</tutorials>
<theme_items>
diff --git a/doc/classes/VSplitContainer.xml b/doc/classes/VSplitContainer.xml
index 32b7637c7e..b933fb2805 100644
--- a/doc/classes/VSplitContainer.xml
+++ b/doc/classes/VSplitContainer.xml
@@ -7,6 +7,7 @@
Vertical split container. See [SplitContainer]. This goes from top to bottom.
</description>
<tutorials>
+ <link title="GUI containers">$DOCS_URL/tutorials/ui/gui_containers.html</link>
</tutorials>
<theme_items>
<theme_item name="autohide" data_type="constant" type="int" default="1">
diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp
index 441b049b50..e14018c562 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.cpp
+++ b/drivers/gles3/rasterizer_canvas_gles3.cpp
@@ -117,6 +117,7 @@ void RasterizerCanvasGLES3::_update_transform_to_mat4(const Transform3D &p_trans
void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_list, const Transform2D &p_canvas_transform, RS::CanvasItemTextureFilter p_default_filter, RS::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used) {
GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
+ GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
texture_storage->frame.current_rt = nullptr;
@@ -155,7 +156,7 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
- state_buffer.time = texture_storage->frame.time;
+ state_buffer.time = state.time;
state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;
state_buffer.directional_light_count = 0; //directional_light_count;
@@ -178,8 +179,12 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
//print_line("w: " + itos(ssize.width) + " s: " + rtos(canvas_scale));
state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);
- glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.canvas_state_buffer);
+ glBindBufferBase(GL_UNIFORM_BUFFER, BASE_UNIFORM_BUFFER_OBJECT, state.canvas_state_buffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), &state_buffer, GL_STREAM_DRAW);
+
+ GLuint global_buffer = material_storage->global_variables_get_uniform_buffer();
+
+ glBindBufferBase(GL_UNIFORM_BUFFER, GLOBAL_UNIFORM_BUFFER_OBJECT, global_buffer);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
@@ -197,8 +202,6 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
r_sdf_used = false;
int item_count = 0;
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
Item *ci = p_item_list;
while (ci) {
// just add all items for now
@@ -215,7 +218,6 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
}
void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool p_to_backbuffer) {
- GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
Item *current_clip = nullptr;
@@ -229,88 +231,31 @@ void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_cou
RID prev_material;
uint32_t index = 0;
+ state.current_shader_version = state.canvas_shader_default_version;
+
for (int i = 0; i < p_item_count; i++) {
Item *ci = items[i];
RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
- GLES3::Material *material_ptr = material_storage->get_material(material);
if (material.is_null() && ci->canvas_group != nullptr) {
material = default_canvas_group_material;
}
if (material != prev_material) {
- GLES3::Shader *shader_ptr = nullptr;
-
- if (material_ptr) {
- shader_ptr = material_ptr->shader;
-
- if (shader_ptr && shader_ptr->mode != RS::SHADER_CANVAS_ITEM) {
- shader_ptr = nullptr; // not a canvas item shader, don't use.
- }
+ GLES3::CanvasMaterialData *material_data = nullptr;
+ if (material.is_valid()) {
+ material_data = static_cast<GLES3::CanvasMaterialData *>(material_storage->material_get_data(material, RS::SHADER_CANVAS_ITEM));
}
-
- if (shader_ptr) {
- if (true) { //check that shader has changed
- if (shader_ptr->canvas_item.uses_time) {
- RenderingServerDefault::redraw_request();
- }
- //state.canvas_shader.version_bind_shader(shader_ptr->version, CanvasShaderGLES3::MODE_QUAD);
- state.current_shader_version = shader_ptr->version;
- }
-
- int tc = material_ptr->textures.size();
- Pair<StringName, RID> *textures = material_ptr->textures.ptrw();
-
- ShaderCompiler::GeneratedCode::Texture *texture_uniforms = shader_ptr->texture_uniforms.ptrw();
-
- for (int ti = 0; ti < tc; i++) {
- glActiveTexture(GL_TEXTURE0 + ti);
-
- GLES3::Texture *t = texture_storage->get_texture(textures[ti].second);
-
- if (!t) {
- switch (texture_uniforms[i].hint) {
- case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
- case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
- glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex);
- } break;
- case ShaderLanguage::ShaderNode::Uniform::HINT_ANISOTROPY: {
- glBindTexture(GL_TEXTURE_2D, storage->resources.aniso_tex);
- } break;
- case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
- glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex);
- } break;
- default: {
- glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
- } break;
- }
-
- continue;
- }
-
- //Set texture filter and repeat texture_uniforms[i].filter texture_uniforms[i].repeat
-
- if (t->redraw_if_visible) {
- RenderingServerDefault::redraw_request();
- }
-
- t = t->get_ptr();
-
-#ifdef TOOLS_ENABLED
- if (t->detect_normal && texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) {
- t->detect_normal(t->detect_normal_ud);
- }
-#endif
- if (t->render_target) {
- t->render_target->used_in_frame = true;
- }
-
- glBindTexture(t->target, t->tex_id);
+ if (material_data) {
+ if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
+ // Bind uniform buffer and textures
+ material_data->bind_uniforms();
+ state.current_shader_version = material_data->shader_data->version;
+ } else {
+ state.current_shader_version = state.canvas_shader_default_version;
}
-
} else {
- //state.canvas_shader.version_bind_shader(state.canvas_shader_default_version, CanvasShaderGLES3::MODE_QUAD);
state.current_shader_version = state.canvas_shader_default_version;
}
prev_material = material;
@@ -389,7 +334,7 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item
state.current_command = Item::Command::TYPE_RECT;
}
_bind_canvas_texture(rect->texture, current_filter, current_repeat, r_index, last_texture, texpixel_size);
- state.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_QUAD);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_QUAD);
Rect2 src_rect;
Rect2 dst_rect;
@@ -552,7 +497,7 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item
state.current_command = Item::Command::TYPE_POLYGON;
}
_bind_canvas_texture(polygon->texture, current_filter, current_repeat, r_index, last_texture, texpixel_size);
- state.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_ATTRIBUTES);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_ATTRIBUTES);
state.current_primitive = polygon->primitive;
state.instance_data_array[r_index].modulation[0] = base_color.r;
@@ -566,16 +511,18 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item
state.instance_data_array[r_index].ninepatch_margins[j] = 0;
}
- // If the previous operation is not done yet, allocated a new buffer
- GLint syncStatus;
- glGetSynciv(state.fences[state.current_buffer], GL_SYNC_STATUS, sizeof(GLint), nullptr, &syncStatus);
- if (syncStatus == GL_UNSIGNALED) {
- _allocate_instance_data_buffer();
- } else {
- glDeleteSync(state.fences[state.current_buffer]);
+ // If the previous operation is not done yet, allocate a new buffer
+ if (state.fences[state.current_buffer] != GLsync()) {
+ GLint syncStatus;
+ glGetSynciv(state.fences[state.current_buffer], GL_SYNC_STATUS, sizeof(GLint), nullptr, &syncStatus);
+ if (syncStatus == GL_UNSIGNALED) {
+ _allocate_instance_data_buffer();
+ } else {
+ glDeleteSync(state.fences[state.current_buffer]);
+ }
}
- glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.canvas_instance_data_buffers[state.current_buffer]);
+ glBindBufferBase(GL_UNIFORM_BUFFER, INSTANCE_UNIFORM_BUFFER_OBJECT, state.canvas_instance_data_buffers[state.current_buffer]);
#ifdef JAVASCRIPT_ENABLED
//WebGL 2.0 does not support mapping buffers, so use slow glBufferData instead
glBufferData(GL_UNIFORM_BUFFER, sizeof(InstanceData), &state.instance_data_array[0], GL_DYNAMIC_DRAW);
@@ -609,7 +556,7 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item
state.current_command = Item::Command::TYPE_PRIMITIVE;
}
_bind_canvas_texture(RID(), current_filter, current_repeat, r_index, last_texture, texpixel_size);
- state.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_PRIMITIVE);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(state.current_shader_version, CanvasShaderGLES3::MODE_PRIMITIVE);
for (uint32_t j = 0; j < MIN(3u, primitive->point_count); j++) {
state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j].x;
@@ -771,15 +718,17 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item
void RasterizerCanvasGLES3::_render_batch(uint32_t &r_index) {
if (state.end_batch && r_index > 0) {
// If the previous operation is not done yet, allocate a new buffer
- GLint syncStatus;
- glGetSynciv(state.fences[state.current_buffer], GL_SYNC_STATUS, sizeof(GLint), nullptr, &syncStatus);
- if (syncStatus == GL_UNSIGNALED) {
- _allocate_instance_data_buffer();
- } else {
- glDeleteSync(state.fences[state.current_buffer]);
+ if (state.fences[state.current_buffer] != GLsync()) {
+ GLint syncStatus;
+ glGetSynciv(state.fences[state.current_buffer], GL_SYNC_STATUS, sizeof(GLint), nullptr, &syncStatus);
+ if (syncStatus == GL_UNSIGNALED) {
+ _allocate_instance_data_buffer();
+ } else {
+ glDeleteSync(state.fences[state.current_buffer]);
+ }
}
- glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.canvas_instance_data_buffers[state.current_buffer]);
+ glBindBufferBase(GL_UNIFORM_BUFFER, INSTANCE_UNIFORM_BUFFER_OBJECT, state.canvas_instance_data_buffers[state.current_buffer]);
#ifdef JAVASCRIPT_ENABLED
//WebGL 2.0 does not support mapping buffers, so use slow glBufferData instead
glBufferData(GL_UNIFORM_BUFFER, sizeof(InstanceData) * r_index, state.instance_data_array, GL_DYNAMIC_DRAW);
@@ -823,24 +772,24 @@ void RasterizerCanvasGLES3::_render_batch(uint32_t &r_index) {
}
// TODO maybe dont use
-void RasterizerCanvasGLES3::_end_batch(uint32_t &r_index) {
+void RasterizerCanvasGLES3::_end_batch(const uint32_t p_index) {
for (int i = 0; i < 4; i++) {
- state.instance_data_array[r_index].modulation[i] = 0.0;
- state.instance_data_array[r_index].ninepatch_margins[i] = 0.0;
- state.instance_data_array[r_index].src_rect[i] = 0.0;
- state.instance_data_array[r_index].dst_rect[i] = 0.0;
+ state.instance_data_array[p_index].modulation[i] = 0.0;
+ state.instance_data_array[p_index].ninepatch_margins[i] = 0.0;
+ state.instance_data_array[p_index].src_rect[i] = 0.0;
+ state.instance_data_array[p_index].dst_rect[i] = 0.0;
}
- state.instance_data_array[r_index].flags = uint32_t(0);
- state.instance_data_array[r_index].color_texture_pixel_size[0] = 0.0;
- state.instance_data_array[r_index].color_texture_pixel_size[1] = 0.0;
+ state.instance_data_array[p_index].flags = uint32_t(0);
+ state.instance_data_array[p_index].color_texture_pixel_size[0] = 0.0;
+ state.instance_data_array[p_index].color_texture_pixel_size[1] = 0.0;
- state.instance_data_array[r_index].pad[0] = 0.0;
- state.instance_data_array[r_index].pad[1] = 0.0;
+ state.instance_data_array[p_index].pad[0] = 0.0;
+ state.instance_data_array[p_index].pad[1] = 0.0;
- state.instance_data_array[r_index].lights[0] = uint32_t(0);
- state.instance_data_array[r_index].lights[1] = uint32_t(0);
- state.instance_data_array[r_index].lights[2] = uint32_t(0);
- state.instance_data_array[r_index].lights[3] = uint32_t(0);
+ state.instance_data_array[p_index].lights[0] = uint32_t(0);
+ state.instance_data_array[p_index].lights[1] = uint32_t(0);
+ state.instance_data_array[p_index].lights[2] = uint32_t(0);
+ state.instance_data_array[p_index].lights[3] = uint32_t(0);
}
RID RasterizerCanvasGLES3::light_create() {
@@ -903,7 +852,8 @@ void RasterizerCanvasGLES3::canvas_begin() {
reset_canvas();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
+ GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
+ glBindTexture(GL_TEXTURE_2D, tex->tex_id);
}
void RasterizerCanvasGLES3::canvas_end() {
@@ -961,11 +911,9 @@ void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTe
ct->size_cache = Size2i(1, 1);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
-
+ GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
+ glBindTexture(GL_TEXTURE_2D, tex->tex_id);
} else {
- texture = texture->get_ptr();
-
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->tex_id);
@@ -973,8 +921,8 @@ void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTe
state.current_tex_ptr = texture;
ct->size_cache = Size2i(texture->width, texture->height);
- texture->GLSetFilter(GL_TEXTURE_2D, filter);
- texture->GLSetRepeat(GL_TEXTURE_2D, repeat);
+ texture->gl_set_filter(filter);
+ texture->gl_set_repeat(repeat);
}
GLES3::Texture *normal_map = texture_storage->get_texture(ct->normal_map);
@@ -983,17 +931,16 @@ void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTe
state.current_normal = RID();
ct->use_normal_cache = false;
glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 6);
- glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex);
+ GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_NORMAL));
+ glBindTexture(GL_TEXTURE_2D, tex->tex_id);
} else {
- normal_map = normal_map->get_ptr();
-
glActiveTexture(GL_TEXTURE0 + storage->config->max_texture_image_units - 6);
glBindTexture(GL_TEXTURE_2D, normal_map->tex_id);
state.current_normal = ct->normal_map;
ct->use_normal_cache = true;
- texture->GLSetFilter(GL_TEXTURE_2D, filter);
- texture->GLSetRepeat(GL_TEXTURE_2D, repeat);
+ texture->gl_set_filter(filter);
+ texture->gl_set_repeat(repeat);
}
GLES3::Texture *specular_map = texture_storage->get_texture(ct->specular);
@@ -1002,17 +949,15 @@ void RasterizerCanvasGLES3::_bind_canvas_texture(RID p_texture, RS::CanvasItemTe
state.current_specular = RID();
ct->use_specular_cache = false;
glActiveTexture(GL_TEXTURE0 + storage->config->max_texture_image_units - 7);
- glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
-
+ GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
+ glBindTexture(GL_TEXTURE_2D, tex->tex_id);
} else {
- specular_map = specular_map->get_ptr();
-
glActiveTexture(GL_TEXTURE0 + storage->config->max_texture_image_units - 7);
glBindTexture(GL_TEXTURE_2D, specular_map->tex_id);
state.current_specular = ct->specular;
ct->use_specular_cache = true;
- texture->GLSetFilter(GL_TEXTURE_2D, filter);
- texture->GLSetRepeat(GL_TEXTURE_2D, repeat);
+ texture->gl_set_filter(filter);
+ texture->gl_set_repeat(repeat);
}
if (ct->use_specular_cache) {
@@ -1102,8 +1047,8 @@ RendererCanvasRender::PolygonID RasterizerCanvasGLES3::request_polygon(const Vec
{
glBindBuffer(GL_ARRAY_BUFFER, pb.vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, stride * vertex_count * sizeof(float), nullptr, GL_STATIC_DRAW); // TODO may not be necessary
- const uint8_t *r = polygon_buffer.ptr();
- float *fptr = (float *)r;
+ uint8_t *r = polygon_buffer.ptrw();
+ float *fptr = reinterpret_cast<float *>(r);
uint32_t *uptr = (uint32_t *)r;
uint32_t base_offset = 0;
{
@@ -1260,7 +1205,19 @@ void RasterizerCanvasGLES3::_allocate_instance_data_buffer() {
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
-void RasterizerCanvasGLES3::initialize() {
+void RasterizerCanvasGLES3::set_time(double p_time) {
+ state.time = p_time;
+}
+
+RasterizerCanvasGLES3 *RasterizerCanvasGLES3::singleton = nullptr;
+
+RasterizerCanvasGLES3 *RasterizerCanvasGLES3::get_singleton() {
+ return singleton;
+}
+
+RasterizerCanvasGLES3::RasterizerCanvasGLES3(RasterizerStorageGLES3 *p_storage) {
+ singleton = this;
+ storage = p_storage;
GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
@@ -1386,9 +1343,7 @@ void RasterizerCanvasGLES3::initialize() {
}
//state.canvas_shadow_shader.init();
-
- int uniform_max_size;
- glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &uniform_max_size);
+ int uniform_max_size = storage->config->max_uniform_buffer_size;
if (uniform_max_size < 65536) {
state.max_lights_per_render = 64;
state.max_instances_per_batch = 128;
@@ -1402,6 +1357,7 @@ void RasterizerCanvasGLES3::initialize() {
state.fences.resize(64);
glGenBuffers(64, state.canvas_instance_data_buffers.ptr());
for (int i = 0; i < 64; i++) {
+ state.fences[i] = GLsync();
glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_instance_data_buffers[i]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(InstanceData) * state.max_instances_per_batch, nullptr, GL_DYNAMIC_DRAW);
}
@@ -1419,9 +1375,9 @@ void RasterizerCanvasGLES3::initialize() {
global_defines += "#define MAX_LIGHTS " + itos(state.max_instances_per_batch) + "\n";
global_defines += "#define MAX_DRAW_DATA_INSTANCES " + itos(state.max_instances_per_batch) + "\n";
- state.canvas_shader.initialize(global_defines);
- state.canvas_shader_default_version = state.canvas_shader.version_create();
- state.canvas_shader.version_bind_shader(state.canvas_shader_default_version, CanvasShaderGLES3::MODE_QUAD);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.initialize(global_defines);
+ state.canvas_shader_default_version = GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_create();
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(state.canvas_shader_default_version, CanvasShaderGLES3::MODE_QUAD);
//state.canvas_shader.set_conditional(CanvasOldShaderGLES3::USE_RGBA_SHADOWS, storage->config->use_rgba_2d_shadows);
@@ -1463,32 +1419,19 @@ void fragment() {
state.using_transparent_rt = false;
state.using_skeleton = false;
state.current_shader_version = state.canvas_shader_default_version;
-}
-
-RasterizerCanvasGLES3 *RasterizerCanvasGLES3::singleton = nullptr;
-
-RasterizerCanvasGLES3 *RasterizerCanvasGLES3::get_singleton() {
- return singleton;
-}
-
-RasterizerCanvasGLES3::RasterizerCanvasGLES3(RasterizerStorageGLES3 *p_storage) {
- singleton = this;
- storage = p_storage;
- initialize();
+ state.time = 0.0;
}
RasterizerCanvasGLES3::~RasterizerCanvasGLES3() {
GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
- state.canvas_shader.version_free(state.canvas_shader_default_version);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_free(state.canvas_shader_default_version);
material_storage->material_free(default_canvas_group_material);
material_storage->shader_free(default_canvas_group_shader);
texture_storage->canvas_texture_free(default_canvas_texture);
singleton = nullptr;
-}
-void RasterizerCanvasGLES3::finalize() {
glDeleteBuffers(1, &data.canvas_quad_vertices);
glDeleteVertexArrays(1, &data.canvas_quad_array);
diff --git a/drivers/gles3/rasterizer_canvas_gles3.h b/drivers/gles3/rasterizer_canvas_gles3.h
index a962796b2f..b77b295de9 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.h
+++ b/drivers/gles3/rasterizer_canvas_gles3.h
@@ -54,13 +54,6 @@ class RasterizerCanvasGLES3 : public RendererCanvasRender {
_FORCE_INLINE_ void _update_transform_to_mat4(const Transform3D &p_transform, float *p_mat4);
enum {
- BASE_UNIFORM_BUFFER_OBJECT = 0,
- MATERIAL_UNIFORM_BUFFER_OBJECT = 1,
- TRANSFORMS_UNIFORM_BUFFER_OBJECT = 2,
- CANVAS_TEXTURE_UNIFORM_BUFFER_OBJECT = 3,
- };
-
- enum {
FLAGS_INSTANCING_MASK = 0x7F,
FLAGS_INSTANCING_HAS_COLORS = (1 << 7),
@@ -104,6 +97,15 @@ class RasterizerCanvasGLES3 : public RendererCanvasRender {
};
public:
+ //TODO move to Material storage
+ enum {
+ BASE_UNIFORM_BUFFER_OBJECT = 0,
+ GLOBAL_UNIFORM_BUFFER_OBJECT = 1,
+ LIGHT_UNIFORM_BUFFER_OBJECT = 2,
+ INSTANCE_UNIFORM_BUFFER_OBJECT = 3,
+ MATERIAL_UNIFORM_BUFFER_OBJECT = 4,
+ };
+
struct StateBuffer {
float canvas_transform[16];
float screen_transform[16];
@@ -170,7 +172,7 @@ public:
InstanceData *instance_data_array = nullptr;
bool canvas_texscreen_used;
- CanvasShaderGLES3 canvas_shader;
+ //CanvasShaderGLES3 canvas_shader;
RID canvas_shader_current_version;
RID canvas_shader_default_version;
//CanvasShadowShaderGLES3 canvas_shadow_shader;
@@ -203,6 +205,8 @@ public:
// FROM RD Renderer
+ double time = 0.0;
+
uint32_t max_lights_per_render;
uint32_t max_lights_per_item;
uint32_t max_instances_per_batch;
@@ -270,14 +274,13 @@ public:
void _render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool p_to_backbuffer = false);
void _render_item(RID p_render_target, const Item *p_item, const Transform2D &p_canvas_transform_inverse, Item *&current_clip, Light *p_lights, uint32_t &r_index);
void _render_batch(uint32_t &p_max_index);
- void _end_batch(uint32_t &p_max_index);
+ void _end_batch(const uint32_t p_index);
void _allocate_instance_data_buffer();
- void initialize();
- void finalize();
+ void set_time(double p_time);
static RasterizerCanvasGLES3 *get_singleton();
- RasterizerCanvasGLES3(RasterizerStorageGLES3 *storage);
+ RasterizerCanvasGLES3(RasterizerStorageGLES3 *p_storage);
~RasterizerCanvasGLES3();
};
diff --git a/drivers/gles3/rasterizer_gles3.cpp b/drivers/gles3/rasterizer_gles3.cpp
index a8133c1317..e09355e433 100644
--- a/drivers/gles3/rasterizer_gles3.cpp
+++ b/drivers/gles3/rasterizer_gles3.cpp
@@ -88,8 +88,6 @@
#endif
void RasterizerGLES3::begin_frame(double frame_step) {
- GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
-
frame++;
delta = frame_step;
@@ -98,11 +96,8 @@ void RasterizerGLES3::begin_frame(double frame_step) {
double time_roll_over = GLOBAL_GET("rendering/limits/time/time_rollover_secs");
time_total = Math::fmod(time_total, time_roll_over);
- texture_storage->frame.time = time_total;
- texture_storage->frame.count++;
- texture_storage->frame.delta = frame_step;
-
- storage->update_dirty_resources();
+ canvas->set_time(time_total);
+ scene->set_time(time_total, frame_step);
storage->info.render_final = storage->info.render;
storage->info.render.reset();
@@ -197,10 +192,18 @@ typedef void (*DebugMessageCallbackARB)(DEBUGPROCARB callback, const void *userP
void RasterizerGLES3::initialize() {
print_line("OpenGL Renderer: " + RS::get_singleton()->get_video_adapter_name());
+}
- texture_storage->set_main_thread_id(Thread::get_caller_id());
- // make sure the OS knows to only access the renderer from the main thread
- OS::get_singleton()->set_render_main_thread_mode(OS::RENDER_MAIN_THREAD_ONLY);
+void RasterizerGLES3::finalize() {
+ memdelete(scene);
+ memdelete(canvas);
+ memdelete(storage);
+ memdelete(light_storage);
+ memdelete(particles_storage);
+ memdelete(mesh_storage);
+ memdelete(material_storage);
+ memdelete(texture_storage);
+ memdelete(config);
}
RasterizerGLES3::RasterizerGLES3() {
@@ -264,19 +267,14 @@ RasterizerGLES3::RasterizerGLES3() {
light_storage = memnew(GLES3::LightStorage);
storage = memnew(RasterizerStorageGLES3);
canvas = memnew(RasterizerCanvasGLES3(storage));
- scene = memnew(RasterizerSceneGLES3);
+ scene = memnew(RasterizerSceneGLES3(storage));
+
+ texture_storage->set_main_thread_id(Thread::get_caller_id());
+ // make sure the OS knows to only access the renderer from the main thread
+ OS::get_singleton()->set_render_main_thread_mode(OS::RENDER_MAIN_THREAD_ONLY);
}
RasterizerGLES3::~RasterizerGLES3() {
- memdelete(scene);
- memdelete(canvas);
- memdelete(storage);
- memdelete(light_storage);
- memdelete(particles_storage);
- memdelete(mesh_storage);
- memdelete(material_storage);
- memdelete(texture_storage);
- memdelete(config);
}
void RasterizerGLES3::prepare_for_blitting_render_targets() {
@@ -298,7 +296,7 @@ void RasterizerGLES3::_blit_render_target_to_screen(RID p_render_target, Display
}
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
- glBlitFramebuffer(0, 0, rt->width, rt->height, 0, p_screen_rect.size.y, p_screen_rect.size.x, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+ glBlitFramebuffer(0, 0, rt->size.x, rt->size.y, 0, p_screen_rect.size.y, p_screen_rect.size.x, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
// is this p_screen useless in a multi window environment?
@@ -340,10 +338,8 @@ void RasterizerGLES3::set_boot_image(const Ref<Image> &p_image, const Color &p_c
canvas->canvas_begin();
- RID texture = texture_storage->texture_create();
- //texture_storage.texture_allocate(texture, p_image->get_width(), p_image->get_height(), 0, p_image->get_format(), VS::TEXTURE_TYPE_2D, p_use_filter ? VS::TEXTURE_FLAG_FILTER : 0);
- texture_storage->_texture_allocate_internal(texture, p_image->get_width(), p_image->get_height(), 0, p_image->get_format(), RenderingDevice::TEXTURE_TYPE_2D);
- texture_storage->texture_set_data(texture, p_image);
+ RID texture = texture_storage->texture_allocate();
+ texture_storage->texture_2d_initialize(texture, p_image);
Rect2 imgrect(0, 0, p_image->get_width(), p_image->get_height());
Rect2 screenrect;
diff --git a/drivers/gles3/rasterizer_gles3.h b/drivers/gles3/rasterizer_gles3.h
index 139695165e..33bb97d105 100644
--- a/drivers/gles3/rasterizer_gles3.h
+++ b/drivers/gles3/rasterizer_gles3.h
@@ -84,7 +84,7 @@ public:
void end_frame(bool p_swap_buffers);
- void finalize() {}
+ void finalize();
static RendererCompositor *_create_current() {
return memnew(RasterizerGLES3);
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index 1382573461..09a02b786c 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -29,10 +29,18 @@
/*************************************************************************/
#include "rasterizer_scene_gles3.h"
+#include "core/config/project_settings.h"
+#include "servers/rendering/rendering_server_default.h"
#ifdef GLES3_ENABLED
-// TODO: 3D support not implemented yet.
+uint64_t RasterizerSceneGLES3::auto_exposure_counter = 2;
+
+RasterizerSceneGLES3 *RasterizerSceneGLES3::singleton = nullptr;
+
+RasterizerSceneGLES3 *RasterizerSceneGLES3::get_singleton() {
+ return singleton;
+}
RasterizerSceneGLES3::GeometryInstance *RasterizerSceneGLES3::geometry_instance_create(RID p_base) {
return nullptr;
@@ -137,39 +145,130 @@ int RasterizerSceneGLES3::get_directional_light_shadow_size(RID p_light_intance)
void RasterizerSceneGLES3::set_directional_shadow_count(int p_count) {
}
-/* SDFGI UPDATE */
+/* SKY API */
-void RasterizerSceneGLES3::sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) {
+void RasterizerSceneGLES3::Sky::free() {
+ if (radiance != 0) {
+ glDeleteTextures(1, &radiance);
+ radiance = 0;
+ glDeleteFramebuffers(1, &radiance_framebuffer);
+ radiance_framebuffer = 0;
+ }
}
-int RasterizerSceneGLES3::sdfgi_get_pending_region_count(RID p_render_buffers) const {
- return 0;
+RID RasterizerSceneGLES3::sky_allocate() {
+ return sky_owner.allocate_rid();
}
-AABB RasterizerSceneGLES3::sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const {
- return AABB();
+void RasterizerSceneGLES3::sky_initialize(RID p_rid) {
+ sky_owner.initialize_rid(p_rid);
}
-uint32_t RasterizerSceneGLES3::sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const {
- return 0;
+void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
+ Sky *sky = sky_owner.get_or_null(p_sky);
+ ERR_FAIL_COND(!sky);
+ ERR_FAIL_COND_MSG(p_radiance_size < 32 || p_radiance_size > 2048, "Sky radiance size must be between 32 and 2048");
+
+ if (sky->radiance_size == p_radiance_size) {
+ return; // No need to update
+ }
+
+ sky->radiance_size = p_radiance_size;
+
+ sky->free();
}
-/* SKY API */
+void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
+ Sky *sky = sky_owner.get_or_null(p_sky);
+ ERR_FAIL_COND(!sky);
-RID RasterizerSceneGLES3::sky_allocate() {
- return RID();
+ if (sky->mode == p_mode) {
+ return;
+ }
+
+ sky->mode = p_mode;
+
+ if (sky->mode == RS::SKY_MODE_REALTIME) {
+ WARN_PRINT_ONCE("The OpenGL renderer does not support the Real Time Sky Update Mode yet. Please use High Quality Mode instead");
+ }
}
-void RasterizerSceneGLES3::sky_initialize(RID p_rid) {
+void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) {
+ Sky *sky = sky_owner.get_or_null(p_sky);
+ ERR_FAIL_COND(!sky);
+
+ if (sky->material == p_material) {
+ return;
+ }
+
+ sky->material = p_material;
}
-void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
+void RasterizerSceneGLES3::_invalidate_sky(Sky *p_sky) {
+ if (!p_sky->dirty) {
+ p_sky->dirty = true;
+ p_sky->dirty_list = dirty_sky_list;
+ dirty_sky_list = p_sky;
+ }
}
-void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_samples) {
+void RasterizerSceneGLES3::_update_dirty_skys() {
+ Sky *sky = dirty_sky_list;
+
+ while (sky) {
+ if (sky->radiance == 0) {
+ //int mipmaps = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBAH) + 1;
+
+ //uint32_t w = sky->radiance_size, h = sky->radiance_size;
+ //int layers = sky_globals.roughness_layers;
+ glGenFramebuffers(1, &sky->radiance_framebuffer);
+
+ glGenTextures(1, &sky->radiance);
+ }
+
+ sky->reflection_dirty = true;
+ sky->processing_layer = 0;
+
+ Sky *next = sky->dirty_list;
+ sky->dirty_list = nullptr;
+ sky->dirty = false;
+ sky = next;
+ }
+
+ dirty_sky_list = nullptr;
}
-void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) {
+void RasterizerSceneGLES3::_draw_sky(Sky *p_sky, const CameraMatrix &p_projection, const Transform3D &p_transform, float p_custom_fov, float p_energy, const Basis &p_sky_orientation) {
+ ERR_FAIL_COND(!p_sky);
+
+ glDepthMask(GL_TRUE);
+ glEnable(GL_DEPTH_TEST);
+ glDisable(GL_CULL_FACE);
+ glDisable(GL_BLEND);
+ glDepthFunc(GL_LEQUAL);
+ glColorMask(1, 1, 1, 1);
+
+ //state.sky_shader.version_bind_shader(sky_globals.default_shader, SkyShaderGLES3::MODE_BACKGROUND);
+ //glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.canvas_instance_data_buffers[state.current_buffer]); // Canvas data updated here
+ //glBindBufferBase(GL_UNIFORM_BUFFER, 1, state.canvas_instance_data_buffers[state.current_buffer]); // Global data
+ //glBindBufferBase(GL_UNIFORM_BUFFER, 2, state.canvas_instance_data_buffers[state.current_buffer]); // Directional light data
+ //glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.canvas_instance_data_buffers[state.current_buffer]); // Material uniforms
+
+ // Camera
+ CameraMatrix camera;
+
+ if (p_custom_fov) {
+ float near_plane = p_projection.get_z_near();
+ float far_plane = p_projection.get_z_far();
+ float aspect = p_projection.get_aspect();
+
+ camera.set_perspective(p_custom_fov, aspect, near_plane, far_plane);
+
+ } else {
+ camera = p_projection;
+ }
+
+ glDrawArrays(GL_TRIANGLES, 0, 3);
}
Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
@@ -179,52 +278,107 @@ Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bo
/* ENVIRONMENT API */
RID RasterizerSceneGLES3::environment_allocate() {
- return RID();
+ return environment_owner.allocate_rid();
}
void RasterizerSceneGLES3::environment_initialize(RID p_rid) {
+ environment_owner.initialize_rid(p_rid);
}
void RasterizerSceneGLES3::environment_set_background(RID p_env, RS::EnvironmentBG p_bg) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->background = p_bg;
}
void RasterizerSceneGLES3::environment_set_sky(RID p_env, RID p_sky) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->sky = p_sky;
}
void RasterizerSceneGLES3::environment_set_sky_custom_fov(RID p_env, float p_scale) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->sky_custom_fov = p_scale;
}
void RasterizerSceneGLES3::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->sky_orientation = p_orientation;
}
void RasterizerSceneGLES3::environment_set_bg_color(RID p_env, const Color &p_color) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->bg_color = p_color;
}
void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env, float p_energy) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->bg_energy = p_energy;
}
void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->canvas_max_layer = p_max_layer;
}
void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color &p_color, RS::EnvironmentAmbientSource p_ambient, float p_energy, float p_sky_contribution, RS::EnvironmentReflectionSource p_reflection_source) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->ambient_light = p_color;
+ env->ambient_source = p_ambient;
+ env->ambient_light_energy = p_energy;
+ env->ambient_sky_contribution = p_sky_contribution;
+ env->reflection_source = p_reflection_source;
}
void RasterizerSceneGLES3::environment_set_glow(RID p_env, bool p_enable, Vector<float> p_levels, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap, float p_glow_map_strength, RID p_glow_map) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ ERR_FAIL_COND_MSG(p_levels.size() != 7, "Size of array of glow levels must be 7");
+ env->glow_enabled = p_enable;
+ env->glow_levels = p_levels;
+ env->glow_intensity = p_intensity;
+ env->glow_strength = p_strength;
+ env->glow_mix = p_mix;
+ env->glow_bloom = p_bloom_threshold;
+ env->glow_blend_mode = p_blend_mode;
+ env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold;
+ env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
+ env->glow_hdr_luminance_cap = p_hdr_luminance_cap;
+ env->glow_map_strength = p_glow_map_strength;
+ env->glow_map = p_glow_map;
}
void RasterizerSceneGLES3::environment_glow_set_use_bicubic_upscale(bool p_enable) {
+ glow_bicubic_upscale = p_enable;
}
void RasterizerSceneGLES3::environment_glow_set_use_high_quality(bool p_enable) {
+ glow_high_quality = p_enable;
}
void RasterizerSceneGLES3::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->ssr_enabled = p_enable;
+ env->ssr_max_steps = p_max_steps;
+ env->ssr_fade_in = p_fade_int;
+ env->ssr_fade_out = p_fade_out;
+ env->ssr_depth_tolerance = p_depth_tolerance;
}
void RasterizerSceneGLES3::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
}
void RasterizerSceneGLES3::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_power, float p_detail, float p_horizon, float p_sharpness, float p_light_affect, float p_ao_channel_affect) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
}
void RasterizerSceneGLES3::environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) {
@@ -248,12 +402,43 @@ void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_update_light(RS::Envi
}
void RasterizerSceneGLES3::environment_set_tonemap(RID p_env, RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->exposure = p_exposure;
+ env->tone_mapper = p_tone_mapper;
+ if (!env->auto_exposure && p_auto_exposure) {
+ env->auto_exposure_version = ++auto_exposure_counter;
+ }
+ env->auto_exposure = p_auto_exposure;
+ env->white = p_white;
+ env->min_luminance = p_min_luminance;
+ env->max_luminance = p_max_luminance;
+ env->auto_exp_speed = p_auto_exp_speed;
+ env->auto_exp_scale = p_auto_exp_scale;
}
void RasterizerSceneGLES3::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, bool p_use_1d_color_correction, RID p_color_correction) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->adjustments_enabled = p_enable;
+ env->adjustments_brightness = p_brightness;
+ env->adjustments_contrast = p_contrast;
+ env->adjustments_saturation = p_saturation;
+ env->use_1d_color_correction = p_use_1d_color_correction;
+ env->color_correction = p_color_correction;
}
void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, const Color &p_light_color, float p_light_energy, float p_sun_scatter, float p_density, float p_height, float p_height_density, float p_aerial_perspective) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND(!env);
+ env->fog_enabled = p_enable;
+ env->fog_light_color = p_light_color;
+ env->fog_light_energy = p_light_energy;
+ env->fog_sun_scatter = p_sun_scatter;
+ env->fog_density = p_density;
+ env->fog_height = p_height;
+ env->fog_height_density = p_height_density;
+ env->fog_aerial_perspective = p_aerial_perspective;
}
void RasterizerSceneGLES3::environment_set_volumetric_fog(RID p_env, bool p_enable, float p_density, const Color &p_albedo, const Color &p_emission, float p_emission_energy, float p_anisotropy, float p_length, float p_detail_spread, float p_gi_inject, bool p_temporal_reprojection, float p_temporal_reprojection_amount, float p_ambient_inject) {
@@ -266,19 +451,25 @@ void RasterizerSceneGLES3::environment_set_volumetric_fog_filter_active(bool p_e
}
Ref<Image> RasterizerSceneGLES3::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND_V(!env, Ref<Image>());
return Ref<Image>();
}
bool RasterizerSceneGLES3::is_environment(RID p_env) const {
- return false;
+ return environment_owner.owns(p_env);
}
RS::EnvironmentBG RasterizerSceneGLES3::environment_get_background(RID p_env) const {
- return RS::ENV_BG_KEEP;
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND_V(!env, RS::ENV_BG_MAX);
+ return env->background;
}
int RasterizerSceneGLES3::environment_get_canvas_max_layer(RID p_env) const {
- return 0;
+ Environment *env = environment_owner.get_or_null(p_env);
+ ERR_FAIL_COND_V(!env, 0);
+ return env->canvas_max_layer;
}
RID RasterizerSceneGLES3::camera_effects_allocate() {
@@ -409,28 +600,353 @@ void RasterizerSceneGLES3::voxel_gi_set_quality(RS::VoxelGIQuality) {
}
void RasterizerSceneGLES3::render_scene(RID p_render_buffers, const CameraData *p_camera_data, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data, RendererScene::RenderInfo *r_render_info) {
-}
-
-void RasterizerSceneGLES3::render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
+ GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
+ RENDER_TIMESTAMP("Setup 3D Scene");
+ // assign render data
+ // Use the format from rendererRD
+ RenderDataGLES3 render_data;
+ {
+ render_data.render_buffers = p_render_buffers;
+
+ // Our first camera is used by default
+ render_data.cam_transform = p_camera_data->main_transform;
+ render_data.cam_projection = p_camera_data->main_projection;
+ render_data.view_projection[0] = p_camera_data->main_projection;
+ render_data.cam_ortogonal = p_camera_data->is_orthogonal;
+
+ render_data.view_count = p_camera_data->view_count;
+ for (uint32_t v = 0; v < p_camera_data->view_count; v++) {
+ render_data.view_projection[v] = p_camera_data->view_projection[v];
+ }
+
+ render_data.z_near = p_camera_data->main_projection.get_z_near();
+ render_data.z_far = p_camera_data->main_projection.get_z_far();
+
+ render_data.instances = &p_instances;
+ render_data.lights = &p_lights;
+ render_data.reflection_probes = &p_reflection_probes;
+ //render_data.voxel_gi_instances = &p_voxel_gi_instances;
+ //render_data.decals = &p_decals;
+ //render_data.lightmaps = &p_lightmaps;
+ //render_data.fog_volumes = &p_fog_volumes;
+ render_data.environment = p_environment;
+ render_data.camera_effects = p_camera_effects;
+ render_data.shadow_atlas = p_shadow_atlas;
+ render_data.reflection_atlas = p_reflection_atlas;
+ render_data.reflection_probe = p_reflection_probe;
+ render_data.reflection_probe_pass = p_reflection_probe_pass;
+
+ // this should be the same for all cameras..
+ render_data.lod_distance_multiplier = p_camera_data->main_projection.get_lod_multiplier();
+ render_data.lod_camera_plane = Plane(-p_camera_data->main_transform.basis.get_axis(Vector3::AXIS_Z), p_camera_data->main_transform.get_origin());
+
+ if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
+ render_data.screen_mesh_lod_threshold = 0.0;
+ } else {
+ render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
+ }
+ render_data.render_info = r_render_info;
+ }
+
+ PagedArray<RID> empty;
+
+ if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
+ render_data.lights = &empty;
+ render_data.reflection_probes = &empty;
+ }
+
+ RenderBuffers *rb = nullptr;
+ //RasterizerStorageGLES3::RenderTarget *rt = nullptr;
+ if (p_render_buffers.is_valid()) {
+ rb = render_buffers_owner.get_or_null(p_render_buffers);
+ ERR_FAIL_COND(!rb);
+ //rt = texture_storage->render_target_owner.get_or_null(rb->render_target);
+ //ERR_FAIL_COND(!rt);
+ }
+
+ Color clear_color;
+ if (p_render_buffers.is_valid()) {
+ clear_color = texture_storage->render_target_get_clear_request_color(rb->render_target);
+ } else {
+ clear_color = storage->get_default_clear_color();
+ }
+
+ Environment *env = environment_owner.get_or_null(p_environment);
+
+ bool fb_cleared = false;
+
+ glDepthFunc(GL_LEQUAL);
+
+ /* Depth Prepass */
+
+ glBindFramebuffer(GL_FRAMEBUFFER, rb->framebuffer);
+
+ if (!fb_cleared) {
+ glClearDepth(1.0f);
+ glClear(GL_DEPTH_BUFFER_BIT);
+ }
+
+ bool draw_sky = false;
+ bool keep_color = false;
+
+ if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW) {
+ clear_color = Color(0, 0, 0, 1);
+ }
+ if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW) {
+ clear_color = Color(0, 0, 0, 1); //in overdraw mode, BG should always be black
+ } else if (is_environment(p_environment)) {
+ RS::EnvironmentBG bg_mode = environment_get_background(p_environment);
+ float bg_energy = env->bg_energy; //environment_get_bg_energy(p_environment);
+ switch (bg_mode) {
+ case RS::ENV_BG_CLEAR_COLOR: {
+ clear_color.r *= bg_energy;
+ clear_color.g *= bg_energy;
+ clear_color.b *= bg_energy;
+ } break;
+ case RS::ENV_BG_COLOR: {
+ clear_color = env->bg_color; //environment_get_bg_color(p_environment);
+ clear_color.r *= bg_energy;
+ clear_color.g *= bg_energy;
+ clear_color.b *= bg_energy;
+ } break;
+ case RS::ENV_BG_SKY: {
+ draw_sky = true;
+ } break;
+ case RS::ENV_BG_CANVAS: {
+ keep_color = true;
+ } break;
+ case RS::ENV_BG_KEEP: {
+ keep_color = true;
+ } break;
+ case RS::ENV_BG_CAMERA_FEED: {
+ } break;
+ default: {
+ }
+ }
+ }
+
+ if (!keep_color) {
+ glClearBufferfv(GL_COLOR, 0, clear_color.components);
+ }
+
+ if (draw_sky) {
+ //_draw_sky(sky, render_data.cam_projection, render_data.cam_transform, env->sky_custom_fov, env->bg_energy, env->sky_orientation);
+ }
+
+ if (p_render_buffers.is_valid()) {
+ /*
+ RENDER_TIMESTAMP("Tonemap");
+ _render_buffers_post_process_and_tonemap(&render_data);
+ */
+
+ _render_buffers_debug_draw(p_render_buffers, p_shadow_atlas, p_occluder_debug_tex);
+ }
+ texture_storage->render_target_disable_clear_request(rb->render_target);
+}
+
+void RasterizerSceneGLES3::render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
}
void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) {
}
-void RasterizerSceneGLES3::set_scene_pass(uint64_t p_pass) {
-}
-
void RasterizerSceneGLES3::set_time(double p_time, double p_step) {
+ time = p_time;
+ time_step = p_step;
}
void RasterizerSceneGLES3::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
+ debug_draw = p_debug_draw;
}
RID RasterizerSceneGLES3::render_buffers_create() {
- return RID();
+ RenderBuffers rb;
+ return render_buffers_owner.make_rid(rb);
+}
+
+/* BACK FBO */
+/* For MSAA */
+/*
+#ifndef JAVASCRIPT_ENABLED
+ if (rt->msaa >= RS::VIEWPORT_MSAA_2X && rt->msaa <= RS::VIEWPORT_MSAA_8X) {
+ rt->multisample_active = true;
+
+ static const int msaa_value[] = { 0, 2, 4, 8, 16 };
+ int msaa = msaa_value[rt->msaa];
+
+ int max_samples = 0;
+ glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
+ if (msaa > max_samples) {
+ WARN_PRINT("MSAA must be <= GL_MAX_SAMPLES, falling-back to GL_MAX_SAMPLES = " + itos(max_samples));
+ msaa = max_samples;
+ }
+
+ //regular fbo
+ glGenFramebuffers(1, &rt->multisample_fbo);
+ bind_framebuffer(rt->multisample_fbo);
+
+ glGenRenderbuffers(1, &rt->multisample_depth);
+ glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_depth);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, config.depth_buffer_internalformat, rt->size.x, rt->size.y);
+
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->multisample_depth);
+
+ glGenRenderbuffers(1, &rt->multisample_color);
+ glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_color);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->size.x, rt->size.y);
+
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rt->multisample_color);
+
+ GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+
+ if (status != GL_FRAMEBUFFER_COMPLETE) {
+ // Delete allocated resources and default to no MSAA
+ WARN_PRINT_ONCE("Cannot allocate back framebuffer for MSAA");
+ printf("err status: %x\n", status);
+ rt->multisample_active = false;
+
+ glDeleteFramebuffers(1, &rt->multisample_fbo);
+ rt->multisample_fbo = 0;
+
+ glDeleteRenderbuffers(1, &rt->multisample_depth);
+ rt->multisample_depth = 0;
+
+ glDeleteRenderbuffers(1, &rt->multisample_color);
+ rt->multisample_color = 0;
+ }
+
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
+ bind_framebuffer(0);
+
+ } else
+#endif // JAVASCRIPT_ENABLED
+ {
+ rt->multisample_active = false;
+ }
+ */
+
+// copy texscreen buffers
+// if (!(rt->flags[RendererStorage::RENDER_TARGET_NO_SAMPLING])) {
+/*
+if (false) {
+glGenTextures(1, &rt->copy_screen_effect.color);
+glBindTexture(GL_TEXTURE_2D, rt->copy_screen_effect.color);
+
+if (rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) {
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rt->size.x, rt->size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+} else {
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rt->size.x, rt->size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
}
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+glGenFramebuffers(1, &rt->copy_screen_effect.fbo);
+bind_framebuffer(rt->copy_screen_effect.fbo);
+glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->copy_screen_effect.color, 0);
+
+glClearColor(0, 0, 0, 0);
+glClear(GL_COLOR_BUFFER_BIT);
+
+GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+if (status != GL_FRAMEBUFFER_COMPLETE) {
+ _clear_render_target(rt);
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
+}
+}
+*/
+
void RasterizerSceneGLES3::render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_internal_width, int p_internal_height, int p_width, int p_height, float p_fsr_sharpness, float p_fsr_mipmap_bias, RS::ViewportMSAA p_msaa, RS::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding, uint32_t p_view_count) {
+ GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
+
+ RenderBuffers *rb = render_buffers_owner.get_or_null(p_render_buffers);
+ ERR_FAIL_COND(!rb);
+
+ //rb->internal_width = p_internal_width; // ignore for now
+ //rb->internal_height = p_internal_height;
+ rb->width = p_width;
+ rb->height = p_height;
+ //rb->fsr_sharpness = p_fsr_sharpness;
+ rb->render_target = p_render_target;
+ //rb->msaa = p_msaa;
+ //rb->screen_space_aa = p_screen_space_aa;
+ //rb->use_debanding = p_use_debanding;
+ //rb->view_count = p_view_count;
+
+ _free_render_buffer_data(rb);
+
+ GLES3::RenderTarget *rt = texture_storage->get_render_target(p_render_target);
+
+ // framebuffer
+ glGenFramebuffers(1, &rb->framebuffer);
+ glBindFramebuffer(GL_FRAMEBUFFER, rb->framebuffer);
+
+ glBindTexture(GL_TEXTURE_2D, rt->color);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
+
+ glGenTextures(1, &rb->depth_texture);
+ glBindTexture(GL_TEXTURE_2D, rb->depth_texture);
+
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, rt->size.x, rt->size.y, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rb->depth_texture, 0);
+
+ GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+
+ glBindTexture(GL_TEXTURE_2D, 0);
+ glBindFramebuffer(GL_FRAMEBUFFER, texture_storage->system_fbo);
+
+ if (status != GL_FRAMEBUFFER_COMPLETE) {
+ _free_render_buffer_data(rb);
+ WARN_PRINT("Could not create 3D renderbuffer, status: " + texture_storage->get_framebuffer_error(status));
+ return;
+ }
+}
+
+void RasterizerSceneGLES3::_free_render_buffer_data(RenderBuffers *rb) {
+ if (rb->depth_texture) {
+ glDeleteTextures(1, &rb->depth_texture);
+ rb->depth_texture = 0;
+ }
+ if (rb->framebuffer) {
+ glDeleteFramebuffers(1, &rb->framebuffer);
+ rb->framebuffer = 0;
+ }
+}
+
+//clear render buffers
+/*
+
+
+ if (rt->copy_screen_effect.color) {
+ glDeleteFramebuffers(1, &rt->copy_screen_effect.fbo);
+ rt->copy_screen_effect.fbo = 0;
+
+ glDeleteTextures(1, &rt->copy_screen_effect.color);
+ rt->copy_screen_effect.color = 0;
+ }
+
+ if (rt->multisample_active) {
+ glDeleteFramebuffers(1, &rt->multisample_fbo);
+ rt->multisample_fbo = 0;
+
+ glDeleteRenderbuffers(1, &rt->multisample_depth);
+ rt->multisample_depth = 0;
+
+ glDeleteRenderbuffers(1, &rt->multisample_color);
+
+ rt->multisample_color = 0;
+ }
+*/
+
+void RasterizerSceneGLES3::_render_buffers_debug_draw(RID p_render_buffers, RID p_shadow_atlas, RID p_occlusion_buffer) {
}
void RasterizerSceneGLES3::gi_set_use_half_resolution(bool p_enable) {
@@ -454,10 +970,27 @@ TypedArray<Image> RasterizerSceneGLES3::bake_render_uv2(RID p_base, const Vector
}
bool RasterizerSceneGLES3::free(RID p_rid) {
- return false;
+ if (environment_owner.owns(p_rid)) {
+ environment_owner.free(p_rid);
+ } else if (sky_owner.owns(p_rid)) {
+ Sky *sky = sky_owner.get_or_null(p_rid);
+ ERR_FAIL_COND_V(!sky, false);
+ sky->free();
+ sky_owner.free(p_rid);
+ } else if (render_buffers_owner.owns(p_rid)) {
+ RenderBuffers *rb = render_buffers_owner.get_or_null(p_rid);
+ ERR_FAIL_COND_V(!rb, false);
+ _free_render_buffer_data(rb);
+ render_buffers_owner.free(p_rid);
+
+ } else {
+ return false;
+ }
+ return true;
}
void RasterizerSceneGLES3::update() {
+ _update_dirty_skys();
}
void RasterizerSceneGLES3::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
@@ -469,7 +1002,48 @@ void RasterizerSceneGLES3::decals_set_filter(RS::DecalFilter p_filter) {
void RasterizerSceneGLES3::light_projectors_set_filter(RS::LightProjectorFilter p_filter) {
}
-RasterizerSceneGLES3::RasterizerSceneGLES3() {
+RasterizerSceneGLES3::RasterizerSceneGLES3(RasterizerStorageGLES3 *p_storage) {
+ GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
+ storage = p_storage;
+
+ {
+ // Initialize Sky stuff
+ sky_globals.roughness_layers = GLOBAL_GET("rendering/reflections/sky_reflections/roughness_layers");
+ sky_globals.ggx_samples = GLOBAL_GET("rendering/reflections/sky_reflections/ggx_samples");
+
+ String global_defines;
+ global_defines += "#define MAX_GLOBAL_VARIABLES 256\n"; // TODO: this is arbitrary for now
+ global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_globals.max_directional_lights) + "\n";
+ state.sky_shader.initialize(global_defines);
+ sky_globals.shader_default_version = state.sky_shader.version_create();
+ state.sky_shader.version_bind_shader(sky_globals.shader_default_version, SkyShaderGLES3::MODE_BACKGROUND);
+ }
+
+ {
+ sky_globals.default_shader = material_storage->shader_allocate();
+
+ material_storage->shader_initialize(sky_globals.default_shader);
+
+ material_storage->shader_set_code(sky_globals.default_shader, R"(
+// Default sky shader.
+
+shader_type sky;
+
+void sky() {
+ COLOR = vec3(0.0);
+}
+)");
+ sky_globals.default_material = material_storage->material_allocate();
+ material_storage->material_initialize(sky_globals.default_material);
+
+ material_storage->material_set_shader(sky_globals.default_material, sky_globals.default_shader);
+ }
+}
+
+RasterizerSceneGLES3::~RasterizerSceneGLES3() {
+ state.sky_shader.version_free(sky_globals.shader_default_version);
+ storage->free(sky_globals.default_material);
+ storage->free(sky_globals.default_shader);
}
#endif // GLES3_ENABLED
diff --git a/drivers/gles3/rasterizer_scene_gles3.h b/drivers/gles3/rasterizer_scene_gles3.h
index 12bb21a5a0..ed529beb25 100644
--- a/drivers/gles3/rasterizer_scene_gles3.h
+++ b/drivers/gles3/rasterizer_scene_gles3.h
@@ -36,15 +36,314 @@
#include "core/math/camera_matrix.h"
#include "core/templates/rid_owner.h"
#include "core/templates/self_list.h"
+#include "rasterizer_storage_gles3.h"
#include "scene/resources/mesh.h"
#include "servers/rendering/renderer_compositor.h"
#include "servers/rendering/renderer_scene_render.h"
#include "servers/rendering_server.h"
+#include "shader_gles3.h"
+#include "shaders/sky.glsl.gen.h"
+
+// Copied from renderer_scene_render_rd
+struct RenderDataGLES3 {
+ RID render_buffers = RID();
+
+ Transform3D cam_transform = Transform3D();
+ CameraMatrix cam_projection = CameraMatrix();
+ bool cam_ortogonal = false;
+
+ // For stereo rendering
+ uint32_t view_count = 1;
+ CameraMatrix view_projection[RendererSceneRender::MAX_RENDER_VIEWS];
+
+ float z_near = 0.0;
+ float z_far = 0.0;
+
+ const PagedArray<RendererSceneRender::GeometryInstance *> *instances = nullptr;
+ const PagedArray<RID> *lights = nullptr;
+ const PagedArray<RID> *reflection_probes = nullptr;
+ //const PagedArray<RID> *voxel_gi_instances = nullptr;
+ //const PagedArray<RID> *decals = nullptr;
+ //const PagedArray<RID> *lightmaps = nullptr;
+ //const PagedArray<RID> *fog_volumes = nullptr;
+ RID environment = RID();
+ RID camera_effects = RID();
+ RID shadow_atlas = RID();
+ RID reflection_atlas = RID();
+ RID reflection_probe = RID();
+ int reflection_probe_pass = 0;
+
+ float lod_distance_multiplier = 0.0;
+ Plane lod_camera_plane = Plane();
+ float screen_mesh_lod_threshold = 0.0;
+
+ uint32_t directional_light_count = 0;
+
+ RendererScene::RenderInfo *render_info = nullptr;
+};
+
+class RasterizerStorageGLES3;
+class RasterizerCanvasGLES3;
class RasterizerSceneGLES3 : public RendererSceneRender {
+private:
+ static RasterizerSceneGLES3 *singleton;
+ RS::ViewportDebugDraw debug_draw = RS::VIEWPORT_DEBUG_DRAW_DISABLED;
+ uint64_t scene_pass = 0;
+
+ /* Sky */
+ struct SkyGlobals {
+ RID shader_current_version;
+ RID shader_default_version;
+ RID default_material;
+ RID default_shader;
+ uint32_t max_directional_lights = 4;
+ uint32_t roughness_layers = 8;
+ uint32_t ggx_samples = 128;
+ } sky_globals;
+
+protected:
+ double time;
+ double time_step = 0;
+
+ struct RenderBuffers {
+ int internal_width = 0;
+ int internal_height = 0;
+ int width = 0;
+ int height = 0;
+ //float fsr_sharpness = 0.2f;
+ RS::ViewportMSAA msaa = RS::VIEWPORT_MSAA_DISABLED;
+ //RS::ViewportScreenSpaceAA screen_space_aa = RS::VIEWPORT_SCREEN_SPACE_AA_DISABLED;
+ //bool use_debanding = false;
+ //uint32_t view_count = 1;
+
+ RID render_target;
+ GLuint internal_texture = 0; // Used for rendering when post effects are enabled
+ GLuint depth_texture = 0; // Main depth texture
+ GLuint framebuffer = 0; // Main framebuffer, contains internal_texture and depth_texture or render_target->color and depth_texture
+
+ //built-in textures used for ping pong image processing and blurring
+ struct Blur {
+ RID texture;
+
+ struct Mipmap {
+ RID texture;
+ int width;
+ int height;
+ GLuint fbo;
+ };
+
+ Vector<Mipmap> mipmaps;
+ };
+
+ Blur blur[2]; //the second one starts from the first mipmap
+
+ /*
+ GLuint fbo = 0;
+ GLuint color = 0;
+ GLuint depth = 0;
+
+ GLuint multisample_fbo = 0;
+ GLuint multisample_color = 0;
+ GLuint multisample_depth = 0;
+ bool multisample_active = false;
+
+ struct Effect {
+ GLuint fbo = 0;
+ int width = 0;
+ int height = 0;
+
+ GLuint color = 0;
+
+ Effect() {
+ }
+ };
+
+ Effect copy_screen_effect;
+
+ struct MipMaps {
+ struct Size {
+ GLuint fbo;
+ GLuint color;
+ int width;
+ int height;
+ };
+
+ Vector<Size> sizes;
+ GLuint color = 0;
+ int levels = 0;
+
+ MipMaps() {
+ }
+ };
+
+ MipMaps mip_maps[2];
+
+ */
+ };
+
+ bool screen_space_roughness_limiter = false;
+ float screen_space_roughness_limiter_amount = 0.25;
+ float screen_space_roughness_limiter_limit = 0.18;
+
+ mutable RID_Owner<RenderBuffers, true> render_buffers_owner;
+
+ void _free_render_buffer_data(RenderBuffers *rb);
+ void _allocate_blur_textures(RenderBuffers *rb);
+ void _allocate_depth_backbuffer_textures(RenderBuffers *rb);
+
+ void _render_buffers_debug_draw(RID p_render_buffers, RID p_shadow_atlas, RID p_occlusion_buffer);
+
+ /* Environment */
+
+ struct Environment {
+ // BG
+ RS::EnvironmentBG background = RS::ENV_BG_CLEAR_COLOR;
+ RID sky;
+ float sky_custom_fov = 0.0;
+ Basis sky_orientation;
+ Color bg_color;
+ float bg_energy = 1.0;
+ int canvas_max_layer = 0;
+ RS::EnvironmentAmbientSource ambient_source = RS::ENV_AMBIENT_SOURCE_BG;
+ Color ambient_light;
+ float ambient_light_energy = 1.0;
+ float ambient_sky_contribution = 1.0;
+ RS::EnvironmentReflectionSource reflection_source = RS::ENV_REFLECTION_SOURCE_BG;
+ Color ao_color;
+
+ /// Tonemap
+
+ RS::EnvironmentToneMapper tone_mapper;
+ float exposure = 1.0;
+ float white = 1.0;
+ bool auto_exposure = false;
+ float min_luminance = 0.2;
+ float max_luminance = 8.0;
+ float auto_exp_speed = 0.2;
+ float auto_exp_scale = 0.5;
+ uint64_t auto_exposure_version = 0;
+
+ // Fog
+ bool fog_enabled = false;
+ Color fog_light_color = Color(0.5, 0.6, 0.7);
+ float fog_light_energy = 1.0;
+ float fog_sun_scatter = 0.0;
+ float fog_density = 0.001;
+ float fog_height = 0.0;
+ float fog_height_density = 0.0; //can be negative to invert effect
+ float fog_aerial_perspective = 0.0;
+
+ /// Glow
+ bool glow_enabled = false;
+ Vector<float> glow_levels;
+ float glow_intensity = 0.8;
+ float glow_strength = 1.0;
+ float glow_bloom = 0.0;
+ float glow_mix = 0.01;
+ RS::EnvironmentGlowBlendMode glow_blend_mode = RS::ENV_GLOW_BLEND_MODE_SOFTLIGHT;
+ float glow_hdr_bleed_threshold = 1.0;
+ float glow_hdr_luminance_cap = 12.0;
+ float glow_hdr_bleed_scale = 2.0;
+ float glow_map_strength = 1.0;
+ RID glow_map = RID();
+
+ /// SSAO
+ bool ssao_enabled = false;
+ float ssao_radius = 1.0;
+ float ssao_intensity = 2.0;
+ float ssao_power = 1.5;
+ float ssao_detail = 0.5;
+ float ssao_horizon = 0.06;
+ float ssao_sharpness = 0.98;
+ float ssao_direct_light_affect = 0.0;
+ float ssao_ao_channel_affect = 0.0;
+
+ /// SSR
+ bool ssr_enabled = false;
+ int ssr_max_steps = 64;
+ float ssr_fade_in = 0.15;
+ float ssr_fade_out = 2.0;
+ float ssr_depth_tolerance = 0.2;
+
+ /// Adjustments
+ bool adjustments_enabled = false;
+ float adjustments_brightness = 1.0f;
+ float adjustments_contrast = 1.0f;
+ float adjustments_saturation = 1.0f;
+ bool use_1d_color_correction = false;
+ RID color_correction = RID();
+ };
+
+ RS::EnvironmentSSAOQuality ssao_quality = RS::ENV_SSAO_QUALITY_MEDIUM;
+ bool ssao_half_size = false;
+ bool ssao_using_half_size = false;
+ float ssao_adaptive_target = 0.5;
+ int ssao_blur_passes = 2;
+ float ssao_fadeout_from = 50.0;
+ float ssao_fadeout_to = 300.0;
+
+ bool glow_bicubic_upscale = false;
+ bool glow_high_quality = false;
+ RS::EnvironmentSSRRoughnessQuality ssr_roughness_quality = RS::ENV_SSR_ROUGHNESS_QUALITY_LOW;
+
+ static uint64_t auto_exposure_counter;
+
+ mutable RID_Owner<Environment, true> environment_owner;
+
+ /* Sky */
+
+ struct Sky {
+ // Screen Buffers
+ GLuint half_res_pass = 0;
+ GLuint half_res_framebuffer = 0;
+ GLuint quarter_res_pass = 0;
+ GLuint quarter_res_framebuffer = 0;
+ Size2i screen_size = Size2i(0, 0);
+
+ // Radiance Cubemap
+ GLuint radiance = 0;
+ GLuint radiance_framebuffer = 0;
+
+ RID material;
+ RID uniform_buffer;
+
+ int radiance_size = 256;
+
+ RS::SkyMode mode = RS::SKY_MODE_AUTOMATIC;
+
+ //ReflectionData reflection;
+ bool reflection_dirty = false;
+ bool dirty = false;
+ int processing_layer = 0;
+ Sky *dirty_list = nullptr;
+
+ //State to track when radiance cubemap needs updating
+ //SkyMaterialData *prev_material;
+ Vector3 prev_position = Vector3(0.0, 0.0, 0.0);
+ float prev_time = 0.0f;
+
+ void free();
+ bool set_radiance_size(int p_radiance_size);
+ bool set_mode(RS::SkyMode p_mode);
+ bool set_material(RID p_material);
+ Ref<Image> bake_panorama(float p_energy, int p_roughness_layers, const Size2i &p_size);
+ };
+
+ Sky *dirty_sky_list = nullptr;
+ mutable RID_Owner<Sky, true> sky_owner;
+
+ void _invalidate_sky(Sky *p_sky);
+ void _update_dirty_skys();
+ void _draw_sky(Sky *p_sky, const CameraMatrix &p_projection, const Transform3D &p_transform, float p_custom_fov, float p_energy, const Basis &p_sky_orientation);
+
public:
+ RasterizerStorageGLES3 *storage;
+ RasterizerCanvasGLES3 *canvas;
+
+ // References to shaders are needed in public space so they can be accessed in RasterizerStorageGLES3
struct State {
- //SceneShaderGLES3 scene_shader;
+ SkyShaderGLES3 sky_shader;
} state;
GeometryInstance *geometry_instance_create(RID p_base) override;
@@ -88,17 +387,17 @@ public:
/* SDFGI UPDATE */
- void sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) override;
- int sdfgi_get_pending_region_count(RID p_render_buffers) const override;
- AABB sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const override;
- uint32_t sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const override;
+ void sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) override {}
+ int sdfgi_get_pending_region_count(RID p_render_buffers) const override { return 0; }
+ AABB sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const override { return AABB(); }
+ uint32_t sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const override { return 0; }
/* SKY API */
RID sky_allocate() override;
void sky_initialize(RID p_rid) override;
void sky_set_radiance_size(RID p_sky, int p_radiance_size) override;
- void sky_set_mode(RID p_sky, RS::SkyMode p_samples) override;
+ void sky_set_mode(RID p_sky, RS::SkyMode p_mode) override;
void sky_set_material(RID p_sky, RID p_material) override;
Ref<Image> sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) override;
@@ -196,12 +495,22 @@ public:
void voxel_gi_set_quality(RS::VoxelGIQuality) override;
void render_scene(RID p_render_buffers, const CameraData *p_camera_data, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data = nullptr, RendererScene::RenderInfo *r_render_info = nullptr) override;
- void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
+ void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
void render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) override;
- void set_scene_pass(uint64_t p_pass) override;
+ void set_scene_pass(uint64_t p_pass) override {
+ scene_pass = p_pass;
+ }
+
+ _FORCE_INLINE_ uint64_t get_scene_pass() {
+ return scene_pass;
+ }
+
void set_time(double p_time, double p_step) override;
void set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) override;
+ _FORCE_INLINE_ RS::ViewportDebugDraw get_debug_draw_mode() const {
+ return debug_draw;
+ }
RID render_buffers_create() override;
void render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_internal_width, int p_internal_height, int p_width, int p_height, float p_fsr_sharpness, float p_fsr_mipmap_bias, RS::ViewportMSAA p_msaa, RS::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding, uint32_t p_view_count) override;
@@ -222,7 +531,9 @@ public:
void decals_set_filter(RS::DecalFilter p_filter) override;
void light_projectors_set_filter(RS::LightProjectorFilter p_filter) override;
- RasterizerSceneGLES3();
+ static RasterizerSceneGLES3 *get_singleton();
+ RasterizerSceneGLES3(RasterizerStorageGLES3 *p_storage);
+ ~RasterizerSceneGLES3();
};
#endif // GLES3_ENABLED
diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp
index 124c2330c2..0049e74a7c 100644
--- a/drivers/gles3/rasterizer_storage_gles3.cpp
+++ b/drivers/gles3/rasterizer_storage_gles3.cpp
@@ -38,24 +38,6 @@
#include "rasterizer_scene_gles3.h"
#include "servers/rendering/shader_language.h"
-void RasterizerStorageGLES3::bind_quad_array() const {
- //glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
- //glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0);
- //glVertexAttribPointer(RS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8));
-
- //glEnableVertexAttribArray(RS::ARRAY_VERTEX);
- //glEnableVertexAttribArray(RS::ARRAY_TEX_UV);
-}
-
-RID RasterizerStorageGLES3::sky_create() {
- Sky *sky = memnew(Sky);
- sky->radiance = 0;
- return sky_owner.make_rid(sky);
-}
-
-void RasterizerStorageGLES3::sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size) {
-}
-
void RasterizerStorageGLES3::base_update_dependency(RID p_base, DependencyTracker *p_instance) {
}
@@ -236,13 +218,9 @@ RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) {
glGenTextures(1, &cls->distance);
glBindTexture(GL_TEXTURE_2D, cls->distance);
if (config->use_rgba_2d_shadows) {
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
} else {
-#ifdef GLES_OVER_GL
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, _RED_OES, GL_FLOAT, nullptr);
-#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_FLOAT, cls->size, cls->height, 0, _RED_OES, GL_FLOAT, NULL);
-#endif
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, GL_RED, GL_FLOAT, nullptr);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
@@ -395,13 +373,6 @@ bool RasterizerStorageGLES3::free(RID p_rid) {
} else if (GLES3::TextureStorage::get_singleton()->owns_canvas_texture(p_rid)) {
GLES3::TextureStorage::get_singleton()->canvas_texture_free(p_rid);
return true;
- } else if (sky_owner.owns(p_rid)) {
- Sky *sky = sky_owner.get_or_null(p_rid);
- sky_set_texture(p_rid, RID(), 256);
- sky_owner.free(p_rid);
- memdelete(sky);
-
- return true;
} else if (GLES3::MaterialStorage::get_singleton()->owns_shader(p_rid)) {
GLES3::MaterialStorage::get_singleton()->shader_free(p_rid);
return true;
@@ -468,7 +439,7 @@ bool RasterizerStorageGLES3::free(RID p_rid) {
multimesh_allocate(p_rid, 0, RS::MULTIMESH_TRANSFORM_3D, RS::MULTIMESH_COLOR_NONE);
- update_dirty_multimeshes();
+ _update_dirty_multimeshes();
multimesh_owner.free(p_rid);
memdelete(multimesh);
@@ -535,16 +506,23 @@ bool RasterizerStorageGLES3::free(RID p_rid) {
}
bool RasterizerStorageGLES3::has_os_feature(const String &p_feature) const {
+ if (p_feature == "rgtc") {
+ return config->rgtc_supported;
+ }
+
if (p_feature == "s3tc") {
return config->s3tc_supported;
}
+ if (p_feature == "bptc") {
+ return config->bptc_supported;
+ }
if (p_feature == "etc") {
return config->etc_supported;
}
- if (p_feature == "skinning_fallback") {
- return config->use_skeleton_software;
+ if (p_feature == "etc2") {
+ return config->etc2_supported;
}
return false;
@@ -652,100 +630,6 @@ RenderingDevice::DeviceType RasterizerStorageGLES3::get_video_adapter_type() con
void RasterizerStorageGLES3::initialize() {
config = GLES3::Config::get_singleton();
- //picky requirements for these
- config->support_shadow_cubemaps = config->support_depth_texture && config->support_write_depth && config->support_depth_cubemaps;
-
- // the use skeleton software path should be used if either float texture is not supported,
- // OR max_vertex_texture_image_units is zero
- config->use_skeleton_software = (config->float_texture_supported == false) || (config->max_vertex_texture_image_units == 0);
-
- {
- // quad for copying stuff
-
- glGenBuffers(1, &resources.quadie);
- glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
- {
- const float qv[16] = {
- -1,
- -1,
- 0,
- 0,
- -1,
- 1,
- 0,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- -1,
- 1,
- 0,
- };
-
- glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW);
- }
-
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- }
-
- {
- //default textures
-
- glGenTextures(1, &resources.white_tex);
- unsigned char whitetexdata[8 * 8 * 3];
- for (int i = 0; i < 8 * 8 * 3; i++) {
- whitetexdata[i] = 255;
- }
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, resources.white_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
- glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- glGenTextures(1, &resources.black_tex);
- unsigned char blacktexdata[8 * 8 * 3];
- for (int i = 0; i < 8 * 8 * 3; i++) {
- blacktexdata[i] = 0;
- }
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, resources.black_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, blacktexdata);
- glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- glGenTextures(1, &resources.normal_tex);
- unsigned char normaltexdata[8 * 8 * 3];
- for (int i = 0; i < 8 * 8 * 3; i += 3) {
- normaltexdata[i + 0] = 128;
- normaltexdata[i + 1] = 128;
- normaltexdata[i + 2] = 255;
- }
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, resources.normal_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, normaltexdata);
- glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- glGenTextures(1, &resources.aniso_tex);
- unsigned char anisotexdata[8 * 8 * 3];
- for (int i = 0; i < 8 * 8 * 3; i += 3) {
- anisotexdata[i + 0] = 255;
- anisotexdata[i + 1] = 128;
- anisotexdata[i + 2] = 0;
- }
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, resources.aniso_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, anisotexdata);
- glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, 0);
- }
-
// skeleton buffer
{
resources.skeleton_transform_buffer_size = 0;
@@ -754,49 +638,41 @@ void RasterizerStorageGLES3::initialize() {
// radical inverse vdc cache texture
// used for cubemap filtering
- if (true /*||config->float_texture_supported*/) { //uint8 is similar and works everywhere
- glGenTextures(1, &resources.radical_inverse_vdc_cache_tex);
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, resources.radical_inverse_vdc_cache_tex);
-
- uint8_t radical_inverse[512];
+ glGenTextures(1, &resources.radical_inverse_vdc_cache_tex);
- for (uint32_t i = 0; i < 512; i++) {
- uint32_t bits = i;
-
- bits = (bits << 16) | (bits >> 16);
- bits = ((bits & 0x55555555) << 1) | ((bits & 0xAAAAAAAA) >> 1);
- bits = ((bits & 0x33333333) << 2) | ((bits & 0xCCCCCCCC) >> 2);
- bits = ((bits & 0x0F0F0F0F) << 4) | ((bits & 0xF0F0F0F0) >> 4);
- bits = ((bits & 0x00FF00FF) << 8) | ((bits & 0xFF00FF00) >> 8);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, resources.radical_inverse_vdc_cache_tex);
+ /*
+ uint8_t radical_inverse[512];
- float value = float(bits) * 2.3283064365386963e-10;
- radical_inverse[i] = uint8_t(CLAMP(value * 255.0, 0, 255));
- }
+ for (uint32_t i = 0; i < 512; i++) {
+ uint32_t bits = i;
- glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 512, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, radical_inverse);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //need this for proper sampling
+ bits = (bits << 16) | (bits >> 16);
+ bits = ((bits & 0x55555555) << 1) | ((bits & 0xAAAAAAAA) >> 1);
+ bits = ((bits & 0x33333333) << 2) | ((bits & 0xCCCCCCCC) >> 2);
+ bits = ((bits & 0x0F0F0F0F) << 4) | ((bits & 0xF0F0F0F0) >> 4);
+ bits = ((bits & 0x00FF00FF) << 8) | ((bits & 0xFF00FF00) >> 8);
- glBindTexture(GL_TEXTURE_2D, 0);
+ float value = float(bits) * 2.3283064365386963e-10;
+ radical_inverse[i] = uint8_t(CLAMP(value * 255.0, 0, 255));
}
+ //glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 512, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, radical_inverse);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //need this for proper sampling
+ */
+ glBindTexture(GL_TEXTURE_2D, 0);
+
{
glGenFramebuffers(1, &resources.mipmap_blur_fbo);
glGenTextures(1, &resources.mipmap_blur_color);
}
#ifdef GLES_OVER_GL
- //this needs to be enabled manually in OpenGL 2.1
-
- if (config->extensions.has("GL_ARB_seamless_cube_map")) {
- glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
- }
- glEnable(GL_POINT_SPRITE);
- glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
+ glEnable(GL_PROGRAM_POINT_SIZE);
#endif
}
@@ -804,10 +680,8 @@ void RasterizerStorageGLES3::finalize() {
}
void RasterizerStorageGLES3::_copy_screen() {
- bind_quad_array();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
-
void RasterizerStorageGLES3::update_memory_info() {
}
@@ -816,10 +690,10 @@ uint64_t RasterizerStorageGLES3::get_rendering_info(RS::RenderingInfo p_info) {
}
void RasterizerStorageGLES3::update_dirty_resources() {
- GLES3::MaterialStorage::get_singleton()->update_dirty_shaders();
- GLES3::MaterialStorage::get_singleton()->update_dirty_materials();
- // update_dirty_skeletons();
- // update_dirty_multimeshes();
+ GLES3::MaterialStorage::get_singleton()->_update_global_variables();
+ GLES3::MaterialStorage::get_singleton()->_update_queued_materials();
+ //GLES3::MeshStorage::get_singleton()->_update_dirty_skeletons();
+ GLES3::MeshStorage::get_singleton()->_update_dirty_multimeshes();
}
RasterizerStorageGLES3::RasterizerStorageGLES3() {
diff --git a/drivers/gles3/rasterizer_storage_gles3.h b/drivers/gles3/rasterizer_storage_gles3.h
index da1dd0e66b..0aa486cbb5 100644
--- a/drivers/gles3/rasterizer_storage_gles3.h
+++ b/drivers/gles3/rasterizer_storage_gles3.h
@@ -42,6 +42,7 @@
#include "servers/rendering/shader_language.h"
#include "storage/config.h"
#include "storage/material_storage.h"
+#include "storage/mesh_storage.h"
#include "storage/texture_storage.h"
// class RasterizerCanvasGLES3;
@@ -55,19 +56,12 @@ public:
GLES3::Config *config;
struct Resources {
- GLuint white_tex;
- GLuint black_tex;
- GLuint normal_tex;
- GLuint aniso_tex;
-
GLuint mipmap_blur_fbo;
GLuint mipmap_blur_color;
GLuint radical_inverse_vdc_cache_tex;
bool use_rgba_2d_shadows;
- GLuint quadie;
-
size_t skeleton_transform_buffer_size;
GLuint skeleton_transform_buffer;
LocalVector<float> skeleton_transform_cpu_buffer;
@@ -107,8 +101,6 @@ public:
} info;
- void bind_quad_array() const;
-
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////API////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
@@ -116,20 +108,6 @@ public:
public:
virtual void base_update_dependency(RID p_base, DependencyTracker *p_instance) override;
- /* SKY API */
- // not sure if used in godot 4?
- struct Sky {
- RID self;
- RID panorama;
- GLuint radiance;
- int radiance_size;
- };
-
- mutable RID_PtrOwner<Sky> sky_owner;
-
- RID sky_create();
- void sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size);
-
/* VOXEL GI API */
RID voxel_gi_allocate() override;
@@ -278,6 +256,9 @@ public:
void buffer_orphan_and_upload(unsigned int p_buffer_size, unsigned int p_offset, unsigned int p_data_size, const void *p_data, GLenum p_target = GL_ARRAY_BUFFER, GLenum p_usage = GL_DYNAMIC_DRAW, bool p_optional_orphan = false) const;
bool safe_buffer_sub_data(unsigned int p_total_buffer_size, GLenum p_target, unsigned int p_offset, unsigned int p_data_size, const void *p_data, unsigned int &r_offset_after) const;
+ //bool validate_framebuffer(); // Validate currently bound framebuffer, does not touch global state
+ String get_framebuffer_error(GLenum p_status);
+
RasterizerStorageGLES3();
~RasterizerStorageGLES3();
};
@@ -319,6 +300,21 @@ inline void RasterizerStorageGLES3::buffer_orphan_and_upload(unsigned int p_buff
glBufferSubData(p_target, p_offset, p_data_size, p_data);
}
+inline String RasterizerStorageGLES3::get_framebuffer_error(GLenum p_status) {
+#ifdef DEBUG_ENABLED
+ if (p_status == GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER";
+ }
+#endif
+ return itos(p_status);
+}
+
#endif // GLES3_ENABLED
#endif // RASTERIZER_STORAGE_OPENGL_H
diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp
index 1c946895a5..e356fa8c1f 100644
--- a/drivers/gles3/shader_gles3.cpp
+++ b/drivers/gles3/shader_gles3.cpp
@@ -165,6 +165,7 @@ void ShaderGLES3::_build_variant_code(StringBuilder &builder, uint32_t p_variant
builder.append("\n"); //make sure defines begin at newline
builder.append(general_defines.get_data());
builder.append(variant_defines[p_variant]);
+ builder.append("\n");
for (int j = 0; j < p_version->custom_defines.size(); j++) {
builder.append(p_version->custom_defines[j].get_data());
}
@@ -327,7 +328,7 @@ void ShaderGLES3::_compile_specialization(Version::Specialization &spec, uint32_
glDeleteProgram(spec.id);
spec.id = 0;
- ERR_PRINT("No OpenGL program link log. What the frick?");
+ ERR_PRINT("No OpenGL program link log. Something is wrong.");
ERR_FAIL();
}
@@ -552,9 +553,11 @@ void ShaderGLES3::_clear_version(Version *p_version) {
for (int i = 0; i < variant_count; i++) {
for (OAHashMap<uint64_t, Version::Specialization>::Iterator it = p_version->variants[i].iter(); it.valid; it = p_version->variants[i].next_iter(it)) {
- glDeleteShader(it.value->vert_id);
- glDeleteShader(it.value->frag_id);
- glDeleteProgram(it.value->id);
+ if (it.value->id != 0) {
+ glDeleteShader(it.value->vert_id);
+ glDeleteShader(it.value->frag_id);
+ glDeleteProgram(it.value->id);
+ }
}
}
diff --git a/drivers/gles3/shader_gles3.h b/drivers/gles3/shader_gles3.h
index f344ea047f..14579e6535 100644
--- a/drivers/gles3/shader_gles3.h
+++ b/drivers/gles3/shader_gles3.h
@@ -111,7 +111,7 @@ private:
void _clear_version(Version *p_version);
void _initialize_version(Version *p_version);
- RID_Owner<Version> version_owner;
+ RID_Owner<Version, true> version_owner;
struct StageTemplate {
struct Chunk {
diff --git a/drivers/gles3/shaders/SCsub b/drivers/gles3/shaders/SCsub
index 2f56b77bdc..8443b5df85 100644
--- a/drivers/gles3/shaders/SCsub
+++ b/drivers/gles3/shaders/SCsub
@@ -5,3 +5,4 @@ Import("env")
if "GLES3_GLSL" in env["BUILDERS"]:
env.GLES3_GLSL("canvas.glsl")
env.GLES3_GLSL("copy.glsl")
+ env.GLES3_GLSL("sky.glsl")
diff --git a/drivers/gles3/shaders/canvas.glsl b/drivers/gles3/shaders/canvas.glsl
index f7db1d950c..41d308b776 100644
--- a/drivers/gles3/shaders/canvas.glsl
+++ b/drivers/gles3/shaders/canvas.glsl
@@ -286,7 +286,7 @@ in vec2 pixel_size_interp;
layout(location = 0) out vec4 frag_color;
#ifdef MATERIAL_UNIFORMS_USED
-uniform MaterialUniforms{
+layout(std140) uniform MaterialUniforms{
//ubo:4
#MATERIAL_UNIFORMS
diff --git a/drivers/gles3/shaders/sky.glsl b/drivers/gles3/shaders/sky.glsl
new file mode 100644
index 0000000000..0faa3eb70c
--- /dev/null
+++ b/drivers/gles3/shaders/sky.glsl
@@ -0,0 +1,179 @@
+/* clang-format off */
+#[modes]
+
+mode_background =
+mode_half_res = #define USE_HALF_RES_PASS
+mode_quarter_res = #define USE_QUARTER_RES_PASS
+mode_cubemap = #define USE_CUBEMAP_PASS
+mode_cubemap_half_res = #define USE_CUBEMAP_PASS \n#define USE_HALF_RES_PASS
+mode_cubemap_quarter_res = #define USE_CUBEMAP_PASS \n#define USE_QUARTER_RES_PASS
+
+#[specializations]
+
+#[vertex]
+
+#ifdef USE_GLES_OVER_GL
+#define lowp
+#define mediump
+#define highp
+#else
+precision highp float;
+precision highp int;
+#endif
+
+out vec2 uv_interp;
+/* clang-format on */
+
+void main() {
+ // One big triangle to cover the whole screen
+ vec2 base_arr[3] = vec2[](vec2(-1.0, -2.0), vec2(-1.0, 2.0), vec2(2.0, 2.0));
+ uv_interp = base_arr[gl_VertexID];
+ gl_Position = vec4(uv_interp, 1.0, 1.0);
+}
+
+/* clang-format off */
+#[fragment]
+
+#define M_PI 3.14159265359
+
+#ifdef USE_GLES_OVER_GL
+#define lowp
+#define mediump
+#define highp
+#else
+#if defined(USE_HIGHP_PRECISION)
+precision highp float;
+precision highp int;
+#else
+precision mediump float;
+precision mediump int;
+#endif
+#endif
+
+in vec2 uv_interp;
+
+/* clang-format on */
+
+uniform samplerCube radiance; //texunit:-1
+#ifdef USE_CUBEMAP_PASS
+uniform samplerCube half_res; //texunit:-2
+uniform samplerCube quarter_res; //texunit:-3
+#else
+uniform sampler2D half_res; //texunit:-2
+uniform sampler2D quarter_res; //texunit:-3
+#endif
+
+layout(std140) uniform CanvasData { //ubo:0
+ mat3 orientation;
+ vec4 projection;
+ vec4 position_multiplier;
+ float time;
+ float luminance_multiplier;
+ float pad1;
+ float pad2;
+};
+
+layout(std140) uniform GlobalVariableData { //ubo:1
+ vec4 global_variables[MAX_GLOBAL_VARIABLES];
+};
+
+struct DirectionalLightData {
+ vec4 direction_energy;
+ vec4 color_size;
+ bool enabled;
+};
+
+layout(std140) uniform DirectionalLights { //ubo:2
+ DirectionalLightData data[MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS];
+}
+directional_lights;
+
+#ifdef MATERIAL_UNIFORMS_USED
+layout(std140) uniform MaterialUniforms{
+//ubo:3
+
+#MATERIAL_UNIFORMS
+
+} material;
+#endif
+
+#GLOBALS
+
+#ifdef USE_CUBEMAP_PASS
+#define AT_CUBEMAP_PASS true
+#else
+#define AT_CUBEMAP_PASS false
+#endif
+
+#ifdef USE_HALF_RES_PASS
+#define AT_HALF_RES_PASS true
+#else
+#define AT_HALF_RES_PASS false
+#endif
+
+#ifdef USE_QUARTER_RES_PASS
+#define AT_QUARTER_RES_PASS true
+#else
+#define AT_QUARTER_RES_PASS false
+#endif
+
+layout(location = 0) out vec4 frag_color;
+
+void main() {
+ vec3 cube_normal;
+ cube_normal.z = -1.0;
+ cube_normal.x = (uv_interp.x + projection.x) / projection.y;
+ cube_normal.y = (-uv_interp.y - projection.z) / projection.w;
+ cube_normal = mat3(orientation) * cube_normal;
+ cube_normal.z = -cube_normal.z;
+ cube_normal = normalize(cube_normal);
+
+ vec2 uv = uv_interp * 0.5 + 0.5;
+
+ vec2 panorama_coords = vec2(atan(cube_normal.x, cube_normal.z), acos(cube_normal.y));
+
+ if (panorama_coords.x < 0.0) {
+ panorama_coords.x += M_PI * 2.0;
+ }
+
+ panorama_coords /= vec2(M_PI * 2.0, M_PI);
+
+ vec3 color = vec3(0.0, 0.0, 0.0);
+ float alpha = 1.0; // Only available to subpasses
+ vec4 half_res_color = vec4(1.0);
+ vec4 quarter_res_color = vec4(1.0);
+ vec4 custom_fog = vec4(0.0);
+
+#ifdef USE_CUBEMAP_PASS
+ vec3 inverted_cube_normal = cube_normal;
+ inverted_cube_normal.z *= -1.0;
+#ifdef USES_HALF_RES_COLOR
+ half_res_color = texture(samplerCube(half_res, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), inverted_cube_normal) * luminance_multiplier;
+#endif
+#ifdef USES_QUARTER_RES_COLOR
+ quarter_res_color = texture(samplerCube(quarter_res, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), inverted_cube_normal) * luminance_multiplier;
+#endif
+#else
+#ifdef USES_HALF_RES_COLOR
+ half_res_color = textureLod(sampler2D(half_res, material_samplers[SAMPLER_LINEAR_CLAMP]), uv, 0.0) * luminance_multiplier;
+#endif
+#ifdef USES_QUARTER_RES_COLOR
+ quarter_res_color = textureLod(sampler2D(quarter_res, material_samplers[SAMPLER_LINEAR_CLAMP]), uv, 0.0) * luminance_multiplier;
+#endif
+#endif
+
+ {
+
+#CODE : SKY
+
+ }
+
+ frag_color.rgb = color * position_multiplier.w / luminance_multiplier;
+ frag_color.a = alpha;
+
+ // Blending is disabled for Sky, so alpha doesn't blend
+ // alpha is used for subsurface scattering so make sure it doesn't get applied to Sky
+ if (!AT_CUBEMAP_PASS && !AT_HALF_RES_PASS && !AT_QUARTER_RES_PASS) {
+ frag_color.a = 0.0;
+ }
+}
diff --git a/drivers/gles3/storage/config.cpp b/drivers/gles3/storage/config.cpp
index a83ad34d4c..369e523cc4 100644
--- a/drivers/gles3/storage/config.cpp
+++ b/drivers/gles3/storage/config.cpp
@@ -31,40 +31,50 @@
#ifdef GLES3_ENABLED
#include "config.h"
+#include "core/config/project_settings.h"
#include "core/templates/vector.h"
using namespace GLES3;
+#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+
Config *Config::singleton = nullptr;
Config::Config() {
singleton = this;
{
- const GLubyte *extension_string = glGetString(GL_EXTENSIONS);
-
- Vector<String> exts = String((const char *)extension_string).split(" ");
-
- for (int i = 0; i < exts.size(); i++) {
- extensions.insert(exts[i]);
+ int max_extensions = 0;
+ glGetIntegerv(GL_NUM_EXTENSIONS, &max_extensions);
+ for (int i = 0; i < max_extensions; i++) {
+ const GLubyte *s = glGetStringi(GL_EXTENSIONS, i);
+ if (!s) {
+ break;
+ }
+ extensions.insert((const char *)s);
}
}
keep_original_textures = true; // false
- shrink_textures_x2 = false;
depth_internalformat = GL_DEPTH_COMPONENT;
depth_type = GL_UNSIGNED_INT;
+ srgb_decode_supported = extensions.has("GL_EXT_texture_sRGB_decode");
+ etc2_supported = true;
#ifdef GLES_OVER_GL
float_texture_supported = true;
s3tc_supported = true;
- etc_supported = false;
+ etc_supported = false; // extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
+ bptc_supported = extensions.has("GL_ARB_texture_compression_bptc") || extensions.has("EXT_texture_compression_bptc");
+ rgtc_supported = extensions.has("GL_EXT_texture_compression_rgtc") || extensions.has("GL_ARB_texture_compression_rgtc") || extensions.has("EXT_texture_compression_rgtc");
support_npot_repeat_mipmap = true;
depth_buffer_internalformat = GL_DEPTH_COMPONENT24;
#else
float_texture_supported = extensions.has("GL_ARB_texture_float") || extensions.has("GL_OES_texture_float");
s3tc_supported = extensions.has("GL_EXT_texture_compression_s3tc") || extensions.has("WEBGL_compressed_texture_s3tc");
etc_supported = extensions.has("GL_OES_compressed_ETC1_RGB8_texture") || extensions.has("WEBGL_compressed_texture_etc1");
+ bptc_supported = false;
+ rgtc_supported = false;
support_npot_repeat_mipmap = extensions.has("GL_OES_texture_npot");
#ifdef JAVASCRIPT_ENABLED
@@ -87,22 +97,12 @@ Config::Config() {
#endif
#ifdef GLES_OVER_GL
- //TODO: causes huge problems with desktop video drivers. Making false for now, needs to be true to render SCREEN_TEXTURE mipmaps
- render_to_mipmap_supported = false;
-#else
- //check if mipmaps can be used for SCREEN_TEXTURE and Glow on Mobile and web platforms
- render_to_mipmap_supported = extensions.has("GL_OES_fbo_render_mipmap") && extensions.has("GL_EXT_texture_lod");
-#endif
-
-#ifdef GLES_OVER_GL
use_rgba_2d_shadows = false;
- support_depth_texture = true;
use_rgba_3d_shadows = false;
support_depth_cubemaps = true;
#else
use_rgba_2d_shadows = !(float_texture_supported && extensions.has("GL_EXT_texture_rg"));
- support_depth_texture = extensions.has("GL_OES_depth_texture") || extensions.has("WEBGL_depth_texture");
- use_rgba_3d_shadows = !support_depth_texture;
+ use_rgba_3d_shadows = false;
support_depth_cubemaps = extensions.has("GL_OES_depth_texture_cube_map");
#endif
@@ -130,20 +130,25 @@ Config::Config() {
support_half_float_vertices = false;
}
- etc_supported = extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
- latc_supported = extensions.has("GL_EXT_texture_compression_latc");
- bptc_supported = extensions.has("GL_ARB_texture_compression_bptc");
- rgtc_supported = extensions.has("GL_EXT_texture_compression_rgtc") || extensions.has("GL_ARB_texture_compression_rgtc") || extensions.has("EXT_texture_compression_rgtc");
- bptc_supported = extensions.has("GL_ARB_texture_compression_bptc") || extensions.has("EXT_texture_compression_bptc");
- srgb_decode_supported = extensions.has("GL_EXT_texture_sRGB_decode");
+ //picky requirements for these
+ support_shadow_cubemaps = support_write_depth && support_depth_cubemaps;
+ // the use skeleton software path should be used if either float texture is not supported,
+ // OR max_vertex_texture_image_units is zero
+ use_skeleton_software = (float_texture_supported == false) || (max_vertex_texture_image_units == 0);
glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &max_vertex_texture_image_units);
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_image_units);
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
+ glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &max_uniform_buffer_size);
+
+ support_anisotropic_filter = extensions.has("GL_EXT_texture_filter_anisotropic");
+ if (support_anisotropic_filter) {
+ glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropic_level);
+ anisotropic_level = MIN(float(1 << int(ProjectSettings::get_singleton()->get("rendering/textures/default_filters/anisotropic_filtering_level"))), anisotropic_level);
+ }
force_vertex_shading = false; //GLOBAL_GET("rendering/quality/shading/force_vertex_shading");
- use_fast_texture_filter = false; //GLOBAL_GET("rendering/quality/filters/use_nearest_mipmap_filter");
- // should_orphan = GLOBAL_GET("rendering/options/api_usage_legacy/orphan_buffers");
+ use_nearest_mip_filter = GLOBAL_GET("rendering/textures/default_filters/use_nearest_mipmap_filter");
}
Config::~Config() {
diff --git a/drivers/gles3/storage/config.h b/drivers/gles3/storage/config.h
index 11a7cc8499..bb4352ce9a 100644
--- a/drivers/gles3/storage/config.h
+++ b/drivers/gles3/storage/config.h
@@ -51,13 +51,13 @@ private:
static Config *singleton;
public:
- bool shrink_textures_x2;
- bool use_fast_texture_filter;
+ bool use_nearest_mip_filter;
bool use_skeleton_software;
int max_vertex_texture_image_units;
int max_texture_image_units;
int max_texture_size;
+ int max_uniform_buffer_size;
// TODO implement wireframe in OpenGL
// bool generate_wireframes;
@@ -84,12 +84,10 @@ public:
bool support_write_depth;
bool support_half_float_vertices;
bool support_npot_repeat_mipmap;
- bool support_depth_texture;
bool support_depth_cubemaps;
-
bool support_shadow_cubemaps;
-
- bool render_to_mipmap_supported;
+ bool support_anisotropic_filter;
+ float anisotropic_level;
GLuint depth_internalformat;
GLuint depth_type;
diff --git a/drivers/gles3/storage/material_storage.cpp b/drivers/gles3/storage/material_storage.cpp
index 0a2922fbd6..fae23980b6 100644
--- a/drivers/gles3/storage/material_storage.cpp
+++ b/drivers/gles3/storage/material_storage.cpp
@@ -30,685 +30,2575 @@
#ifdef GLES3_ENABLED
-#include "material_storage.h"
+#include "core/config/project_settings.h"
+
#include "config.h"
+#include "material_storage.h"
#include "texture_storage.h"
#include "drivers/gles3/rasterizer_canvas_gles3.h"
using namespace GLES3;
-MaterialStorage *MaterialStorage::singleton = nullptr;
+///////////////////////////////////////////////////////////////////////////
+// UBI helper functions
+
+_FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, int p_array_size, const Variant &value, uint8_t *data, bool p_linear_color) {
+ switch (type) {
+ case ShaderLanguage::TYPE_BOOL: {
+ uint32_t *gui = (uint32_t *)data;
+
+ if (p_array_size > 0) {
+ const PackedInt32Array &ba = value;
+ int s = ba.size();
+ const int *r = ba.ptr();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = (r[i] != 0) ? 1 : 0;
+ } else {
+ gui[j] = 0;
+ }
+ gui[j + 1] = 0; // ignored
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ bool v = value;
+ gui[0] = v ? 1 : 0;
+ }
+ } break;
+ case ShaderLanguage::TYPE_BVEC2: {
+ uint32_t *gui = (uint32_t *)data;
+
+ if (p_array_size > 0) {
+ const PackedInt32Array &ba = value;
+ int s = ba.size();
+ const int *r = ba.ptr();
+ int count = 2 * p_array_size;
+
+ for (int i = 0, j = 0; i < count; i += 2, j += 4) {
+ if (i < s) {
+ gui[j] = r[i] ? 1 : 0;
+ gui[j + 1] = r[i + 1] ? 1 : 0;
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ }
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ int v = value;
+ gui[0] = v & 1 ? 1 : 0;
+ gui[1] = v & 2 ? 1 : 0;
+ }
+ } break;
+ case ShaderLanguage::TYPE_BVEC3: {
+ uint32_t *gui = (uint32_t *)data;
+
+ if (p_array_size > 0) {
+ const PackedInt32Array &ba = value;
+ int s = ba.size();
+ const int *r = ba.ptr();
+ int count = 3 * p_array_size;
+
+ for (int i = 0, j = 0; i < count; i += 3, j += 4) {
+ if (i < s) {
+ gui[j] = r[i] ? 1 : 0;
+ gui[j + 1] = r[i + 1] ? 1 : 0;
+ gui[j + 2] = r[i + 2] ? 1 : 0;
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+ }
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ int v = value;
+ gui[0] = (v & 1) ? 1 : 0;
+ gui[1] = (v & 2) ? 1 : 0;
+ gui[2] = (v & 4) ? 1 : 0;
+ }
+ } break;
+ case ShaderLanguage::TYPE_BVEC4: {
+ uint32_t *gui = (uint32_t *)data;
+
+ if (p_array_size > 0) {
+ const PackedInt32Array &ba = value;
+ int s = ba.size();
+ const int *r = ba.ptr();
+ int count = 4 * p_array_size;
+
+ for (int i = 0; i < count; i += 4) {
+ if (i < s) {
+ gui[i] = r[i] ? 1 : 0;
+ gui[i + 1] = r[i + 1] ? 1 : 0;
+ gui[i + 2] = r[i + 2] ? 1 : 0;
+ gui[i + 3] = r[i + 3] ? 1 : 0;
+ } else {
+ gui[i] = 0;
+ gui[i + 1] = 0;
+ gui[i + 2] = 0;
+ gui[i + 3] = 0;
+ }
+ }
+ } else {
+ int v = value;
+ gui[0] = (v & 1) ? 1 : 0;
+ gui[1] = (v & 2) ? 1 : 0;
+ gui[2] = (v & 4) ? 1 : 0;
+ gui[3] = (v & 8) ? 1 : 0;
+ }
+ } break;
+ case ShaderLanguage::TYPE_INT: {
+ int32_t *gui = (int32_t *)data;
+
+ if (p_array_size > 0) {
+ Vector<int> iv = value;
+ int s = iv.size();
+ const int *r = iv.ptr();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ } else {
+ gui[j] = 0;
+ }
+ gui[j + 1] = 0; // ignored
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ int v = value;
+ gui[0] = v;
+ }
+ } break;
+ case ShaderLanguage::TYPE_IVEC2: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ int32_t *gui = (int32_t *)data;
-MaterialStorage *MaterialStorage::get_singleton() {
- return singleton;
-}
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 2 * p_array_size;
-MaterialStorage::MaterialStorage() {
- singleton = this;
+ const int *r = iv.ptr();
+ for (int i = 0, j = 0; i < count; i += 2, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ gui[j + 1] = r[i + 1];
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ }
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_IVEC3: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ int32_t *gui = (int32_t *)data;
- shaders.copy.initialize();
- shaders.copy_version = shaders.copy.version_create(); //TODO
- shaders.copy.version_bind_shader(shaders.copy_version, CopyShaderGLES3::MODE_COPY_SECTION);
- //shaders.cubemap_filter.init();
- //bool ggx_hq = GLOBAL_GET("rendering/quality/reflections/high_quality_ggx");
- //shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, !ggx_hq);
-}
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 3 * p_array_size;
+
+ const int *r = iv.ptr();
+ for (int i = 0, j = 0; i < count; i += 3, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ gui[j + 1] = r[i + 1];
+ gui[j + 2] = r[i + 2];
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+ }
+ gui[j + 3] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_IVEC4: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ int32_t *gui = (int32_t *)data;
-MaterialStorage::~MaterialStorage() {
- shaders.copy.version_free(shaders.copy_version);
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 4 * p_array_size;
+
+ const int *r = iv.ptr();
+ for (int i = 0; i < count; i += 4) {
+ if (i < s) {
+ gui[i] = r[i];
+ gui[i + 1] = r[i + 1];
+ gui[i + 2] = r[i + 2];
+ gui[i + 3] = r[i + 3];
+ } else {
+ gui[i] = 0;
+ gui[i + 1] = 0;
+ gui[i + 2] = 0;
+ gui[i + 3] = 0;
+ }
+ }
+ } break;
+ case ShaderLanguage::TYPE_UINT: {
+ uint32_t *gui = (uint32_t *)data;
+
+ if (p_array_size > 0) {
+ Vector<int> iv = value;
+ int s = iv.size();
+ const int *r = iv.ptr();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ } else {
+ gui[j] = 0;
+ }
+ gui[j + 1] = 0; // ignored
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ int v = value;
+ gui[0] = v;
+ }
+ } break;
+ case ShaderLanguage::TYPE_UVEC2: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ uint32_t *gui = (uint32_t *)data;
- singleton = nullptr;
-}
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 2 * p_array_size;
-/* GLOBAL VARIABLE API */
+ const int *r = iv.ptr();
+ for (int i = 0, j = 0; i < count; i += 2, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ gui[j + 1] = r[i + 1];
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ }
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_UVEC3: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ uint32_t *gui = (uint32_t *)data;
-void MaterialStorage::global_variable_add(const StringName &p_name, RS::GlobalVariableType p_type, const Variant &p_value) {
-}
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 3 * p_array_size;
+
+ const int *r = iv.ptr();
+ for (int i = 0, j = 0; i < count; i += 3, j += 4) {
+ if (i < s) {
+ gui[j] = r[i];
+ gui[j + 1] = r[i + 1];
+ gui[j + 2] = r[i + 2];
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+ }
+ gui[j + 3] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_UVEC4: {
+ Vector<int> iv = value;
+ int s = iv.size();
+ uint32_t *gui = (uint32_t *)data;
-void MaterialStorage::global_variable_remove(const StringName &p_name) {
-}
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+ int count = 4 * p_array_size;
+
+ const int *r = iv.ptr();
+ for (int i = 0; i < count; i++) {
+ if (i < s) {
+ gui[i] = r[i];
+ gui[i + 1] = r[i + 1];
+ gui[i + 2] = r[i + 2];
+ gui[i + 3] = r[i + 3];
+ } else {
+ gui[i] = 0;
+ gui[i + 1] = 0;
+ gui[i + 2] = 0;
+ gui[i + 3] = 0;
+ }
+ }
+ } break;
+ case ShaderLanguage::TYPE_FLOAT: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedFloat32Array &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = a[i];
+ } else {
+ gui[j] = 0;
+ }
+ gui[j + 1] = 0; // ignored
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ float v = value;
+ gui[0] = v;
+ }
+ } break;
+ case ShaderLanguage::TYPE_VEC2: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedVector2Array &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = a[i].x;
+ gui[j + 1] = a[i].y;
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ }
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ Vector2 v = value;
+ gui[0] = v.x;
+ gui[1] = v.y;
+ }
+ } break;
+ case ShaderLanguage::TYPE_VEC3: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedVector3Array &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ gui[j] = a[i].x;
+ gui[j + 1] = a[i].y;
+ gui[j + 2] = a[i].z;
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+ }
+ gui[j + 3] = 0; // ignored
+ }
+ } else {
+ Vector3 v = value;
+ gui[0] = v.x;
+ gui[1] = v.y;
+ gui[2] = v.z;
+ }
+ } break;
+ case ShaderLanguage::TYPE_VEC4: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ if (value.get_type() == Variant::PACKED_COLOR_ARRAY) {
+ const PackedColorArray &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size; i++, j += 4) {
+ if (i < s) {
+ Color color = a[i];
+ if (p_linear_color) {
+ color = color.srgb_to_linear();
+ }
+ gui[j] = color.r;
+ gui[j + 1] = color.g;
+ gui[j + 2] = color.b;
+ gui[j + 3] = color.a;
+ } else {
+ gui[j] = 0;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+ gui[j + 3] = 0;
+ }
+ }
+ } else {
+ const PackedFloat32Array &a = value;
+ int s = a.size();
+ int count = 4 * p_array_size;
+
+ for (int i = 0; i < count; i += 4) {
+ if (i + 3 < s) {
+ gui[i] = a[i];
+ gui[i + 1] = a[i + 1];
+ gui[i + 2] = a[i + 2];
+ gui[i + 3] = a[i + 3];
+ } else {
+ gui[i] = 0;
+ gui[i + 1] = 0;
+ gui[i + 2] = 0;
+ gui[i + 3] = 0;
+ }
+ }
+ }
+ } else {
+ if (value.get_type() == Variant::COLOR) {
+ Color v = value;
+
+ if (p_linear_color) {
+ v = v.srgb_to_linear();
+ }
+
+ gui[0] = v.r;
+ gui[1] = v.g;
+ gui[2] = v.b;
+ gui[3] = v.a;
+ } else if (value.get_type() == Variant::RECT2) {
+ Rect2 v = value;
+
+ gui[0] = v.position.x;
+ gui[1] = v.position.y;
+ gui[2] = v.size.x;
+ gui[3] = v.size.y;
+ } else if (value.get_type() == Variant::QUATERNION) {
+ Quaternion v = value;
+
+ gui[0] = v.x;
+ gui[1] = v.y;
+ gui[2] = v.z;
+ gui[3] = v.w;
+ } else {
+ Plane v = value;
-Vector<StringName> MaterialStorage::global_variable_get_list() const {
- return Vector<StringName>();
+ gui[0] = v.normal.x;
+ gui[1] = v.normal.y;
+ gui[2] = v.normal.z;
+ gui[3] = v.d;
+ }
+ }
+ } break;
+ case ShaderLanguage::TYPE_MAT2: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedFloat32Array &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size * 4; i += 4, j += 8) {
+ if (i + 3 < s) {
+ gui[j] = a[i];
+ gui[j + 1] = a[i + 1];
+
+ gui[j + 4] = a[i + 2];
+ gui[j + 5] = a[i + 3];
+ } else {
+ gui[j] = 1;
+ gui[j + 1] = 0;
+
+ gui[j + 4] = 0;
+ gui[j + 5] = 1;
+ }
+ gui[j + 2] = 0; // ignored
+ gui[j + 3] = 0; // ignored
+ gui[j + 6] = 0; // ignored
+ gui[j + 7] = 0; // ignored
+ }
+ } else {
+ Transform2D v = value;
+
+ //in std140 members of mat2 are treated as vec4s
+ gui[0] = v.elements[0][0];
+ gui[1] = v.elements[0][1];
+ gui[2] = 0; // ignored
+ gui[3] = 0; // ignored
+
+ gui[4] = v.elements[1][0];
+ gui[5] = v.elements[1][1];
+ gui[6] = 0; // ignored
+ gui[7] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_MAT3: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedFloat32Array &a = value;
+ int s = a.size();
+
+ for (int i = 0, j = 0; i < p_array_size * 9; i += 9, j += 12) {
+ if (i + 8 < s) {
+ gui[j] = a[i];
+ gui[j + 1] = a[i + 1];
+ gui[j + 2] = a[i + 2];
+
+ gui[j + 4] = a[i + 3];
+ gui[j + 5] = a[i + 4];
+ gui[j + 6] = a[i + 5];
+
+ gui[j + 8] = a[i + 6];
+ gui[j + 9] = a[i + 7];
+ gui[j + 10] = a[i + 8];
+ } else {
+ gui[j] = 1;
+ gui[j + 1] = 0;
+ gui[j + 2] = 0;
+
+ gui[j + 4] = 0;
+ gui[j + 5] = 1;
+ gui[j + 6] = 0;
+
+ gui[j + 8] = 0;
+ gui[j + 9] = 0;
+ gui[j + 10] = 1;
+ }
+ gui[j + 3] = 0; // ignored
+ gui[j + 7] = 0; // ignored
+ gui[j + 11] = 0; // ignored
+ }
+ } else {
+ Basis v = value;
+ gui[0] = v.elements[0][0];
+ gui[1] = v.elements[1][0];
+ gui[2] = v.elements[2][0];
+ gui[3] = 0; // ignored
+
+ gui[4] = v.elements[0][1];
+ gui[5] = v.elements[1][1];
+ gui[6] = v.elements[2][1];
+ gui[7] = 0; // ignored
+
+ gui[8] = v.elements[0][2];
+ gui[9] = v.elements[1][2];
+ gui[10] = v.elements[2][2];
+ gui[11] = 0; // ignored
+ }
+ } break;
+ case ShaderLanguage::TYPE_MAT4: {
+ float *gui = (float *)data;
+
+ if (p_array_size > 0) {
+ const PackedFloat32Array &a = value;
+ int s = a.size();
+
+ for (int i = 0; i < p_array_size * 16; i += 16) {
+ if (i + 15 < s) {
+ gui[i] = a[i];
+ gui[i + 1] = a[i + 1];
+ gui[i + 2] = a[i + 2];
+ gui[i + 3] = a[i + 3];
+
+ gui[i + 4] = a[i + 4];
+ gui[i + 5] = a[i + 5];
+ gui[i + 6] = a[i + 6];
+ gui[i + 7] = a[i + 7];
+
+ gui[i + 8] = a[i + 8];
+ gui[i + 9] = a[i + 9];
+ gui[i + 10] = a[i + 10];
+ gui[i + 11] = a[i + 11];
+
+ gui[i + 12] = a[i + 12];
+ gui[i + 13] = a[i + 13];
+ gui[i + 14] = a[i + 14];
+ gui[i + 15] = a[i + 15];
+ } else {
+ gui[i] = 1;
+ gui[i + 1] = 0;
+ gui[i + 2] = 0;
+ gui[i + 3] = 0;
+
+ gui[i + 4] = 0;
+ gui[i + 5] = 1;
+ gui[i + 6] = 0;
+ gui[i + 7] = 0;
+
+ gui[i + 8] = 0;
+ gui[i + 9] = 0;
+ gui[i + 10] = 1;
+ gui[i + 11] = 0;
+
+ gui[i + 12] = 0;
+ gui[i + 13] = 0;
+ gui[i + 14] = 0;
+ gui[i + 15] = 1;
+ }
+ }
+ } else {
+ Transform3D v = value;
+ gui[0] = v.basis.elements[0][0];
+ gui[1] = v.basis.elements[1][0];
+ gui[2] = v.basis.elements[2][0];
+ gui[3] = 0;
+
+ gui[4] = v.basis.elements[0][1];
+ gui[5] = v.basis.elements[1][1];
+ gui[6] = v.basis.elements[2][1];
+ gui[7] = 0;
+
+ gui[8] = v.basis.elements[0][2];
+ gui[9] = v.basis.elements[1][2];
+ gui[10] = v.basis.elements[2][2];
+ gui[11] = 0;
+
+ gui[12] = v.origin.x;
+ gui[13] = v.origin.y;
+ gui[14] = v.origin.z;
+ gui[15] = 1;
+ }
+ } break;
+ default: {
+ }
+ }
}
-void MaterialStorage::global_variable_set(const StringName &p_name, const Variant &p_value) {
-}
+_FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value> &value, uint8_t *data) {
+ switch (type) {
+ case ShaderLanguage::TYPE_BOOL: {
+ uint32_t *gui = (uint32_t *)data;
+ *gui = value[0].boolean ? 1 : 0;
+ } break;
+ case ShaderLanguage::TYPE_BVEC2: {
+ uint32_t *gui = (uint32_t *)data;
+ gui[0] = value[0].boolean ? 1 : 0;
+ gui[1] = value[1].boolean ? 1 : 0;
-void MaterialStorage::global_variable_set_override(const StringName &p_name, const Variant &p_value) {
-}
+ } break;
+ case ShaderLanguage::TYPE_BVEC3: {
+ uint32_t *gui = (uint32_t *)data;
+ gui[0] = value[0].boolean ? 1 : 0;
+ gui[1] = value[1].boolean ? 1 : 0;
+ gui[2] = value[2].boolean ? 1 : 0;
-Variant MaterialStorage::global_variable_get(const StringName &p_name) const {
- return Variant();
-}
+ } break;
+ case ShaderLanguage::TYPE_BVEC4: {
+ uint32_t *gui = (uint32_t *)data;
+ gui[0] = value[0].boolean ? 1 : 0;
+ gui[1] = value[1].boolean ? 1 : 0;
+ gui[2] = value[2].boolean ? 1 : 0;
+ gui[3] = value[3].boolean ? 1 : 0;
-RS::GlobalVariableType MaterialStorage::global_variable_get_type(const StringName &p_name) const {
- return RS::GLOBAL_VAR_TYPE_MAX;
-}
+ } break;
+ case ShaderLanguage::TYPE_INT: {
+ int32_t *gui = (int32_t *)data;
+ gui[0] = value[0].sint;
-void MaterialStorage::global_variables_load_settings(bool p_load_textures) {
-}
+ } break;
+ case ShaderLanguage::TYPE_IVEC2: {
+ int32_t *gui = (int32_t *)data;
-void MaterialStorage::global_variables_clear() {
-}
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].sint;
+ }
-int32_t MaterialStorage::global_variables_instance_allocate(RID p_instance) {
- return 0;
-}
+ } break;
+ case ShaderLanguage::TYPE_IVEC3: {
+ int32_t *gui = (int32_t *)data;
-void MaterialStorage::global_variables_instance_free(RID p_instance) {
-}
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].sint;
+ }
-void MaterialStorage::global_variables_instance_update(RID p_instance, int p_index, const Variant &p_value) {
-}
+ } break;
+ case ShaderLanguage::TYPE_IVEC4: {
+ int32_t *gui = (int32_t *)data;
-/* SHADER API */
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].sint;
+ }
-void MaterialStorage::_shader_make_dirty(GLES3::Shader *p_shader) {
- if (p_shader->dirty_list.in_list()) {
- return;
- }
+ } break;
+ case ShaderLanguage::TYPE_UINT: {
+ uint32_t *gui = (uint32_t *)data;
+ gui[0] = value[0].uint;
- _shader_dirty_list.add(&p_shader->dirty_list);
-}
+ } break;
+ case ShaderLanguage::TYPE_UVEC2: {
+ int32_t *gui = (int32_t *)data;
-RID MaterialStorage::shader_allocate() {
- GLES3::Shader *shader = memnew(GLES3::Shader);
- shader->mode = RS::SHADER_CANVAS_ITEM;
- //shader->shader = &scene->state.scene_shader;
- RID rid = shader_owner.make_rid(shader);
- _shader_make_dirty(shader);
- shader->self = rid;
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].uint;
+ }
+ } break;
+ case ShaderLanguage::TYPE_UVEC3: {
+ int32_t *gui = (int32_t *)data;
+
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].uint;
+ }
+
+ } break;
+ case ShaderLanguage::TYPE_UVEC4: {
+ int32_t *gui = (int32_t *)data;
+
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].uint;
+ }
+ } break;
+ case ShaderLanguage::TYPE_FLOAT: {
+ float *gui = (float *)data;
+ gui[0] = value[0].real;
- return rid;
+ } break;
+ case ShaderLanguage::TYPE_VEC2: {
+ float *gui = (float *)data;
+
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].real;
+ }
+
+ } break;
+ case ShaderLanguage::TYPE_VEC3: {
+ float *gui = (float *)data;
+
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].real;
+ }
+
+ } break;
+ case ShaderLanguage::TYPE_VEC4: {
+ float *gui = (float *)data;
+
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].real;
+ }
+ } break;
+ case ShaderLanguage::TYPE_MAT2: {
+ float *gui = (float *)data;
+
+ //in std140 members of mat2 are treated as vec4s
+ gui[0] = value[0].real;
+ gui[1] = value[1].real;
+ gui[2] = 0;
+ gui[3] = 0;
+ gui[4] = value[2].real;
+ gui[5] = value[3].real;
+ gui[6] = 0;
+ gui[7] = 0;
+ } break;
+ case ShaderLanguage::TYPE_MAT3: {
+ float *gui = (float *)data;
+
+ gui[0] = value[0].real;
+ gui[1] = value[1].real;
+ gui[2] = value[2].real;
+ gui[3] = 0;
+ gui[4] = value[3].real;
+ gui[5] = value[4].real;
+ gui[6] = value[5].real;
+ gui[7] = 0;
+ gui[8] = value[6].real;
+ gui[9] = value[7].real;
+ gui[10] = value[8].real;
+ gui[11] = 0;
+ } break;
+ case ShaderLanguage::TYPE_MAT4: {
+ float *gui = (float *)data;
+
+ for (int i = 0; i < 16; i++) {
+ gui[i] = value[i].real;
+ }
+ } break;
+ default: {
+ }
+ }
}
-void MaterialStorage::shader_initialize(RID p_rid) {
- // noop
+_FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, int p_array_size, uint8_t *data) {
+ if (p_array_size <= 0) {
+ p_array_size = 1;
+ }
+
+ switch (type) {
+ case ShaderLanguage::TYPE_BOOL:
+ case ShaderLanguage::TYPE_INT:
+ case ShaderLanguage::TYPE_UINT:
+ case ShaderLanguage::TYPE_FLOAT: {
+ memset(data, 0, 4 * p_array_size);
+ } break;
+ case ShaderLanguage::TYPE_BVEC2:
+ case ShaderLanguage::TYPE_IVEC2:
+ case ShaderLanguage::TYPE_UVEC2:
+ case ShaderLanguage::TYPE_VEC2: {
+ memset(data, 0, 8 * p_array_size);
+ } break;
+ case ShaderLanguage::TYPE_BVEC3:
+ case ShaderLanguage::TYPE_IVEC3:
+ case ShaderLanguage::TYPE_UVEC3:
+ case ShaderLanguage::TYPE_VEC3:
+ case ShaderLanguage::TYPE_BVEC4:
+ case ShaderLanguage::TYPE_IVEC4:
+ case ShaderLanguage::TYPE_UVEC4:
+ case ShaderLanguage::TYPE_VEC4: {
+ memset(data, 0, 16 * p_array_size);
+ } break;
+ case ShaderLanguage::TYPE_MAT2: {
+ memset(data, 0, 32 * p_array_size);
+ } break;
+ case ShaderLanguage::TYPE_MAT3: {
+ memset(data, 0, 48 * p_array_size);
+ } break;
+ case ShaderLanguage::TYPE_MAT4: {
+ memset(data, 0, 64 * p_array_size);
+ } break;
+
+ default: {
+ }
+ }
}
-//RID MaterialStorage::shader_create() {
-// GLES3::Shader *shader = memnew(GLES3::Shader);
-// shader->mode = RS::SHADER_SPATIAL;
-// shader->shader = &scene->state.scene_shader;
-// RID rid = shader_owner.make_rid(shader);
-// _shader_make_dirty(shader);
-// shader->self = rid;
+///////////////////////////////////////////////////////////////////////////
+// MaterialData
-// return rid;
-//}
+void MaterialData::update_uniform_buffer(const Map<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const Map<StringName, Variant> &p_parameters, uint8_t *p_buffer, uint32_t p_buffer_size, bool p_use_linear_color) {
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ bool uses_global_buffer = false;
-void MaterialStorage::shader_free(RID p_rid) {
- GLES3::Shader *shader = shader_owner.get_or_null(p_rid);
+ for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : p_uniforms) {
+ if (E.value.order < 0) {
+ continue; // texture, does not go here
+ }
- if (shader->shader && shader->version.is_valid()) {
- shader->shader->version_free(shader->version);
+ if (E.value.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
+ continue; //instance uniforms don't appear in the buffer
+ }
+
+ if (E.value.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {
+ //this is a global variable, get the index to it
+ GlobalVariables::Variable *gv = material_storage->global_variables.variables.getptr(E.key);
+ uint32_t index = 0;
+ if (gv) {
+ index = gv->buffer_index;
+ } else {
+ WARN_PRINT("Shader uses global uniform '" + E.key + "', but it was removed at some point. Material will not display correctly.");
+ }
+
+ uint32_t offset = p_uniform_offsets[E.value.order];
+ uint32_t *intptr = (uint32_t *)&p_buffer[offset];
+ *intptr = index;
+ uses_global_buffer = true;
+ continue;
+ }
+
+ //regular uniform
+ uint32_t offset = p_uniform_offsets[E.value.order];
+#ifdef DEBUG_ENABLED
+ uint32_t size = 0U;
+ // The following code enforces a 16-byte alignment of uniform arrays.
+ if (E.value.array_size > 0) {
+ size = ShaderLanguage::get_datatype_size(E.value.type) * E.value.array_size;
+ int m = (16 * E.value.array_size);
+ if ((size % m) != 0U) {
+ size += m - (size % m);
+ }
+ } else {
+ size = ShaderLanguage::get_datatype_size(E.value.type);
+ }
+ ERR_CONTINUE(offset + size > p_buffer_size);
+#endif
+ uint8_t *data = &p_buffer[offset];
+ const Map<StringName, Variant>::Element *V = p_parameters.find(E.key);
+
+ if (V) {
+ //user provided
+ _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, V->get(), data, p_use_linear_color);
+
+ } else if (E.value.default_value.size()) {
+ //default value
+ _fill_std140_ubo_value(E.value.type, E.value.default_value, data);
+ //value=E.value.default_value;
+ } else {
+ //zero because it was not provided
+ if (E.value.type == ShaderLanguage::TYPE_VEC4 && E.value.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
+ //colors must be set as black, with alpha as 1.0
+ _fill_std140_variant_ubo_value(E.value.type, E.value.array_size, Color(0, 0, 0, 1), data, p_use_linear_color);
+ } else {
+ //else just zero it out
+ _fill_std140_ubo_empty(E.value.type, E.value.array_size, data);
+ }
+ }
}
- if (shader->dirty_list.in_list()) {
- _shader_dirty_list.remove(&shader->dirty_list);
+ if (uses_global_buffer != (global_buffer_E != nullptr)) {
+ if (uses_global_buffer) {
+ global_buffer_E = material_storage->global_variables.materials_using_buffer.push_back(self);
+ } else {
+ material_storage->global_variables.materials_using_buffer.erase(global_buffer_E);
+ global_buffer_E = nullptr;
+ }
}
+}
- while (shader->materials.first()) {
- GLES3::Material *m = shader->materials.first()->self();
+MaterialData::~MaterialData() {
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
- m->shader = nullptr;
- _material_make_dirty(m);
+ if (global_buffer_E) {
+ //unregister global buffers
+ material_storage->global_variables.materials_using_buffer.erase(global_buffer_E);
+ }
+
+ if (global_texture_E) {
+ //unregister global textures
- shader->materials.remove(shader->materials.first());
+ for (const KeyValue<StringName, uint64_t> &E : used_global_textures) {
+ GlobalVariables::Variable *v = material_storage->global_variables.variables.getptr(E.key);
+ if (v) {
+ v->texture_materials.erase(self);
+ }
+ }
+ //unregister material from those using global textures
+ material_storage->global_variables.materials_using_texture.erase(global_texture_E);
}
- shader_owner.free(p_rid);
- memdelete(shader);
+ if (uniform_buffer) {
+ glDeleteBuffers(1, &uniform_buffer);
+ }
}
-void MaterialStorage::shader_set_code(RID p_shader, const String &p_code) {
- GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
- ERR_FAIL_COND(!shader);
+void MaterialData::update_textures(const Map<StringName, Variant> &p_parameters, const Map<StringName, Map<int, RID>> &p_default_textures, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, RID *p_textures, bool p_use_linear_color) {
+ TextureStorage *texture_storage = TextureStorage::get_singleton();
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
- shader->code = p_code;
+#ifdef TOOLS_ENABLED
+ Texture *roughness_detect_texture = nullptr;
+ RS::TextureDetectRoughnessChannel roughness_channel = RS::TEXTURE_DETECT_ROUGHNESS_R;
+ Texture *normal_detect_texture = nullptr;
+#endif
- String mode_string = ShaderLanguage::get_shader_type(p_code);
- RS::ShaderMode mode;
+ bool uses_global_textures = false;
+ global_textures_pass++;
- if (mode_string == "canvas_item") {
- mode = RS::SHADER_CANVAS_ITEM;
- } else if (mode_string == "particles") {
- mode = RS::SHADER_PARTICLES;
- } else if (mode_string == "sky") {
- mode = RS::SHADER_SKY;
- } else if (mode_string == "spatial") {
- mode = RS::SHADER_SPATIAL;
- } else {
- mode = RS::SHADER_MAX;
- ERR_PRINT("shader type " + mode_string + " not supported in OpenGL renderer");
+ for (int i = 0, k = 0; i < p_texture_uniforms.size(); i++) {
+ const StringName &uniform_name = p_texture_uniforms[i].name;
+ int uniform_array_size = p_texture_uniforms[i].array_size;
+
+ Vector<RID> textures;
+
+ if (p_texture_uniforms[i].global) {
+ uses_global_textures = true;
+
+ GlobalVariables::Variable *v = material_storage->global_variables.variables.getptr(uniform_name);
+ if (v) {
+ if (v->buffer_index >= 0) {
+ WARN_PRINT("Shader uses global uniform texture '" + String(uniform_name) + "', but it changed type and is no longer a texture!.");
+
+ } else {
+ Map<StringName, uint64_t>::Element *E = used_global_textures.find(uniform_name);
+ if (!E) {
+ E = used_global_textures.insert(uniform_name, global_textures_pass);
+ v->texture_materials.insert(self);
+ } else {
+ E->get() = global_textures_pass;
+ }
+
+ textures.push_back(v->override.get_type() != Variant::NIL ? v->override : v->value);
+ }
+
+ } else {
+ WARN_PRINT("Shader uses global uniform texture '" + String(uniform_name) + "', but it was removed at some point. Material will not display correctly.");
+ }
+ } else {
+ const Map<StringName, Variant>::Element *V = p_parameters.find(uniform_name);
+ if (V) {
+ if (V->get().is_array()) {
+ Array array = (Array)V->get();
+ if (uniform_array_size > 0) {
+ for (int j = 0; j < array.size(); j++) {
+ textures.push_back(array[j]);
+ }
+ } else {
+ if (array.size() > 0) {
+ textures.push_back(array[0]);
+ }
+ }
+ } else {
+ textures.push_back(V->get());
+ }
+ }
+
+ if (uniform_array_size > 0) {
+ if (textures.size() < uniform_array_size) {
+ const Map<StringName, Map<int, RID>>::Element *W = p_default_textures.find(uniform_name);
+ for (int j = textures.size(); j < uniform_array_size; j++) {
+ if (W && W->get().has(j)) {
+ textures.push_back(W->get()[j]);
+ } else {
+ textures.push_back(RID());
+ }
+ }
+ }
+ } else if (textures.is_empty()) {
+ const Map<StringName, Map<int, RID>>::Element *W = p_default_textures.find(uniform_name);
+ if (W && W->get().has(0)) {
+ textures.push_back(W->get()[0]);
+ }
+ }
+ }
+
+ RID gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_WHITE);
+
+ if (textures.is_empty()) {
+ //check default usage
+ switch (p_texture_uniforms[i].type) {
+ case ShaderLanguage::TYPE_ISAMPLER2D:
+ case ShaderLanguage::TYPE_USAMPLER2D:
+ case ShaderLanguage::TYPE_SAMPLER2D: {
+ switch (p_texture_uniforms[i].hint) {
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK:
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_BLACK);
+ } break;
+ case ShaderLanguage::ShaderNode::Uniform::HINT_ANISOTROPY: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_ANISO);
+ } break;
+ case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_NORMAL);
+ } break;
+ case ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_NORMAL);
+ } break;
+ default: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_WHITE);
+ } break;
+ }
+ } break;
+
+ case ShaderLanguage::TYPE_SAMPLERCUBE: {
+ switch (p_texture_uniforms[i].hint) {
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK:
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_CUBEMAP_BLACK);
+ } break;
+ default: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_CUBEMAP_WHITE);
+ } break;
+ }
+ } break;
+ case ShaderLanguage::TYPE_SAMPLERCUBEARRAY: {
+ ERR_PRINT_ONCE("Type: SamplerCubeArray not supported in OpenGL renderer, please use another type.");
+ } break;
+
+ case ShaderLanguage::TYPE_ISAMPLER3D:
+ case ShaderLanguage::TYPE_USAMPLER3D:
+ case ShaderLanguage::TYPE_SAMPLER3D: {
+ switch (p_texture_uniforms[i].hint) {
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK:
+ case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_3D_BLACK);
+ } break;
+ default: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_3D_WHITE);
+ } break;
+ }
+ } break;
+
+ case ShaderLanguage::TYPE_ISAMPLER2DARRAY:
+ case ShaderLanguage::TYPE_USAMPLER2DARRAY:
+ case ShaderLanguage::TYPE_SAMPLER2DARRAY: {
+ gl_texture = texture_storage->texture_gl_get_default(DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE);
+ } break;
+
+ default: {
+ }
+ }
+#ifdef TOOLS_ENABLED
+ if (roughness_detect_texture && normal_detect_texture && !normal_detect_texture->path.is_empty()) {
+ roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel);
+ }
+#endif
+ if (uniform_array_size > 0) {
+ for (int j = 0; j < uniform_array_size; j++) {
+ p_textures[k++] = gl_texture;
+ }
+ } else {
+ p_textures[k++] = gl_texture;
+ }
+ } else {
+ //bool srgb = p_use_linear_color && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO);
+
+ for (int j = 0; j < textures.size(); j++) {
+ Texture *tex = TextureStorage::get_singleton()->get_texture(textures[j]);
+
+ if (tex) {
+ gl_texture = textures[j];
+#ifdef TOOLS_ENABLED
+ if (tex->detect_3d_callback && p_use_linear_color) {
+ tex->detect_3d_callback(tex->detect_3d_callback_ud);
+ }
+ if (tex->detect_normal_callback && (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL || p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL)) {
+ if (p_texture_uniforms[i].hint == ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_NORMAL) {
+ normal_detect_texture = tex;
+ }
+ tex->detect_normal_callback(tex->detect_normal_callback_ud);
+ }
+ if (tex->detect_roughness_callback && (p_texture_uniforms[i].hint >= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R || p_texture_uniforms[i].hint <= ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_GRAY)) {
+ //find the normal texture
+ roughness_detect_texture = tex;
+ roughness_channel = RS::TextureDetectRoughnessChannel(p_texture_uniforms[i].hint - ShaderLanguage::ShaderNode::Uniform::HINT_ROUGHNESS_R);
+ }
+#endif
+ }
+#ifdef TOOLS_ENABLED
+ if (roughness_detect_texture && normal_detect_texture && !normal_detect_texture->path.is_empty()) {
+ roughness_detect_texture->detect_roughness_callback(roughness_detect_texture->detect_roughness_callback_ud, normal_detect_texture->path, roughness_channel);
+ }
+#endif
+ p_textures[k++] = gl_texture;
+ }
+ }
+ }
+ {
+ //for textures no longer used, unregister them
+ List<Map<StringName, uint64_t>::Element *> to_delete;
+ for (Map<StringName, uint64_t>::Element *E = used_global_textures.front(); E; E = E->next()) {
+ if (E->get() != global_textures_pass) {
+ to_delete.push_back(E);
+
+ GlobalVariables::Variable *v = material_storage->global_variables.variables.getptr(E->key());
+ if (v) {
+ v->texture_materials.erase(self);
+ }
+ }
+ }
+
+ while (to_delete.front()) {
+ used_global_textures.erase(to_delete.front()->get());
+ to_delete.pop_front();
+ }
+ //handle registering/unregistering global textures
+ if (uses_global_textures != (global_texture_E != nullptr)) {
+ if (uses_global_textures) {
+ global_texture_E = material_storage->global_variables.materials_using_texture.push_back(self);
+ } else {
+ material_storage->global_variables.materials_using_texture.erase(global_texture_E);
+ global_texture_E = nullptr;
+ }
+ }
}
+}
- if (shader->version.is_valid() && mode != shader->mode) {
- shader->shader->version_free(shader->version);
- shader->version = RID();
+void MaterialData::update_parameters_internal(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty, const Map<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, const Map<StringName, Map<int, RID>> &p_default_texture_params, uint32_t p_ubo_size) {
+ if ((uint32_t)ubo_data.size() != p_ubo_size) {
+ p_uniform_dirty = true;
+ if (!uniform_buffer) {
+ glGenBuffers(1, &uniform_buffer);
+ }
+
+ ubo_data.resize(p_ubo_size);
+ if (ubo_data.size()) {
+ memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
+ }
}
- shader->mode = mode;
+ //check whether buffer changed
+ if (p_uniform_dirty && ubo_data.size()) {
+ update_uniform_buffer(p_uniforms, p_uniform_offsets, p_parameters, ubo_data.ptrw(), ubo_data.size(), true);
+ glBindBuffer(GL_UNIFORM_BUFFER, uniform_buffer);
+ glBufferData(GL_UNIFORM_BUFFER, ubo_data.size(), ubo_data.ptrw(), GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_UNIFORM_BUFFER, 0);
+ }
- // TODO handle all shader types
- if (mode == RS::SHADER_CANVAS_ITEM) {
- shader->shader = &RasterizerCanvasGLES3::get_singleton()->state.canvas_shader;
- } else if (mode == RS::SHADER_SPATIAL) {
- //shader->shader = &scene->state.scene_shader;
- } else if (mode == RS::SHADER_PARTICLES) {
- } else if (mode == RS::SHADER_SKY) {
- } else {
- return;
+ uint32_t tex_uniform_count = 0U;
+ for (int i = 0; i < p_texture_uniforms.size(); i++) {
+ tex_uniform_count += uint32_t(p_texture_uniforms[i].array_size > 0 ? p_texture_uniforms[i].array_size : 1);
}
- if (shader->version.is_null() && shader->shader) {
- shader->version = shader->shader->version_create();
+ if ((uint32_t)texture_cache.size() != tex_uniform_count || p_textures_dirty) {
+ texture_cache.resize(tex_uniform_count);
+ p_textures_dirty = true;
}
- _shader_make_dirty(shader);
+ if (p_textures_dirty && tex_uniform_count) {
+ update_textures(p_parameters, p_default_texture_params, p_texture_uniforms, texture_cache.ptrw(), true);
+ }
}
-String MaterialStorage::shader_get_code(RID p_shader) const {
- const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
- ERR_FAIL_COND_V(!shader, "");
+///////////////////////////////////////////////////////////////////////////
+// Material Storage
- return shader->code;
+MaterialStorage *MaterialStorage::singleton = nullptr;
+
+MaterialStorage *MaterialStorage::get_singleton() {
+ return singleton;
}
-void MaterialStorage::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
- GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
- ERR_FAIL_COND(!shader);
+MaterialStorage::MaterialStorage() {
+ singleton = this;
+
+ shader_data_request_func[RS::SHADER_SPATIAL] = nullptr;
+ shader_data_request_func[RS::SHADER_CANVAS_ITEM] = _create_canvas_shader_func;
+ shader_data_request_func[RS::SHADER_PARTICLES] = nullptr;
+ shader_data_request_func[RS::SHADER_SKY] = nullptr;
+ shader_data_request_func[RS::SHADER_FOG] = nullptr;
- if (shader->dirty_list.in_list()) {
- _update_shader(shader);
+ material_data_request_func[RS::SHADER_SPATIAL] = nullptr;
+ material_data_request_func[RS::SHADER_CANVAS_ITEM] = _create_canvas_material_func;
+ material_data_request_func[RS::SHADER_PARTICLES] = nullptr;
+ material_data_request_func[RS::SHADER_SKY] = nullptr;
+ material_data_request_func[RS::SHADER_FOG] = nullptr;
+
+ static_assert(sizeof(GlobalVariables::Value) == 16);
+
+ global_variables.buffer_size = MAX(4096, (int)GLOBAL_GET("rendering/limits/global_shader_variables/buffer_size"));
+ if (global_variables.buffer_size > uint32_t(Config::get_singleton()->max_uniform_buffer_size)) {
+ global_variables.buffer_size = uint32_t(Config::get_singleton()->max_uniform_buffer_size);
+ WARN_PRINT("Project setting: rendering/limits/global_shader_variables/buffer_size exceeds maximum uniform buffer size of: " + itos(Config::get_singleton()->max_uniform_buffer_size));
}
- Map<int, StringName> order;
+ global_variables.buffer_values = memnew_arr(GlobalVariables::Value, global_variables.buffer_size);
+ memset(global_variables.buffer_values, 0, sizeof(GlobalVariables::Value) * global_variables.buffer_size);
+ global_variables.buffer_usage = memnew_arr(GlobalVariables::ValueUsage, global_variables.buffer_size);
+ global_variables.buffer_dirty_regions = memnew_arr(bool, global_variables.buffer_size / GlobalVariables::BUFFER_DIRTY_REGION_SIZE);
+ memset(global_variables.buffer_dirty_regions, 0, sizeof(bool) * global_variables.buffer_size / GlobalVariables::BUFFER_DIRTY_REGION_SIZE);
+ glGenBuffers(1, &global_variables.buffer);
+ glBindBuffer(GL_UNIFORM_BUFFER, global_variables.buffer);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(GlobalVariables::Value) * global_variables.buffer_size, nullptr, GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_UNIFORM_BUFFER, 0);
- for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
- if (E->get().texture_order >= 0) {
- order[E->get().texture_order + 100000] = E->key();
- } else {
- order[E->get().order] = E->key();
- }
- }
-
- for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
- PropertyInfo pi;
- ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[E->get()];
-
- pi.name = E->get();
-
- switch (u.type) {
- case ShaderLanguage::TYPE_VOID: {
- pi.type = Variant::NIL;
- } break;
-
- case ShaderLanguage::TYPE_BOOL: {
- pi.type = Variant::BOOL;
- } break;
-
- // bool vectors
- case ShaderLanguage::TYPE_BVEC2: {
- pi.type = Variant::INT;
- pi.hint = PROPERTY_HINT_FLAGS;
- pi.hint_string = "x,y";
- } break;
- case ShaderLanguage::TYPE_BVEC3: {
- pi.type = Variant::INT;
- pi.hint = PROPERTY_HINT_FLAGS;
- pi.hint_string = "x,y,z";
- } break;
- case ShaderLanguage::TYPE_BVEC4: {
- pi.type = Variant::INT;
- pi.hint = PROPERTY_HINT_FLAGS;
- pi.hint_string = "x,y,z,w";
- } break;
-
- // int stuff
- case ShaderLanguage::TYPE_UINT:
- case ShaderLanguage::TYPE_INT: {
- pi.type = Variant::INT;
-
- if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
- pi.hint = PROPERTY_HINT_RANGE;
- pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
- }
- } break;
-
- case ShaderLanguage::TYPE_IVEC2:
- case ShaderLanguage::TYPE_UVEC2:
- case ShaderLanguage::TYPE_IVEC3:
- case ShaderLanguage::TYPE_UVEC3:
- case ShaderLanguage::TYPE_IVEC4:
- case ShaderLanguage::TYPE_UVEC4: {
- // not sure what this should be in godot 4
- // pi.type = Variant::POOL_INT_ARRAY;
- pi.type = Variant::PACKED_INT32_ARRAY;
- } break;
-
- case ShaderLanguage::TYPE_FLOAT: {
- pi.type = Variant::FLOAT;
- if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
- pi.hint = PROPERTY_HINT_RANGE;
- pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
- }
- } break;
-
- case ShaderLanguage::TYPE_VEC2: {
- pi.type = Variant::VECTOR2;
- } break;
- case ShaderLanguage::TYPE_VEC3: {
- pi.type = Variant::VECTOR3;
- } break;
-
- case ShaderLanguage::TYPE_VEC4: {
- if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
- pi.type = Variant::COLOR;
- } else {
- pi.type = Variant::QUATERNION;
- }
- } break;
-
- case ShaderLanguage::TYPE_MAT2: {
- pi.type = Variant::TRANSFORM2D;
- } break;
-
- case ShaderLanguage::TYPE_MAT3: {
- pi.type = Variant::BASIS;
- } break;
-
- case ShaderLanguage::TYPE_MAT4: {
- pi.type = Variant::TRANSFORM3D;
- } break;
-
- case ShaderLanguage::TYPE_SAMPLER2D:
- // case ShaderLanguage::TYPE_SAMPLEREXT:
- case ShaderLanguage::TYPE_ISAMPLER2D:
- case ShaderLanguage::TYPE_USAMPLER2D: {
- pi.type = Variant::OBJECT;
- pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string = "Texture";
- } break;
-
- case ShaderLanguage::TYPE_SAMPLERCUBE: {
- pi.type = Variant::OBJECT;
- pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string = "CubeMap";
- } break;
-
- case ShaderLanguage::TYPE_SAMPLER2DARRAY:
- case ShaderLanguage::TYPE_ISAMPLER2DARRAY:
- case ShaderLanguage::TYPE_USAMPLER2DARRAY:
- case ShaderLanguage::TYPE_SAMPLER3D:
- case ShaderLanguage::TYPE_ISAMPLER3D:
- case ShaderLanguage::TYPE_USAMPLER3D: {
- // Not implemented in OpenGL
- } break;
- // new for godot 4
- case ShaderLanguage::TYPE_SAMPLERCUBEARRAY:
- case ShaderLanguage::TYPE_STRUCT:
- case ShaderLanguage::TYPE_MAX: {
- } break;
+ {
+ // Setup CanvasItem compiler
+ ShaderCompiler::DefaultIdentifierActions actions;
+
+ actions.renames["VERTEX"] = "vertex";
+ actions.renames["LIGHT_VERTEX"] = "light_vertex";
+ actions.renames["SHADOW_VERTEX"] = "shadow_vertex";
+ actions.renames["UV"] = "uv";
+ actions.renames["POINT_SIZE"] = "gl_PointSize";
+
+ actions.renames["MODEL_MATRIX"] = "model_matrix";
+ actions.renames["CANVAS_MATRIX"] = "canvas_data.canvas_transform";
+ actions.renames["SCREEN_MATRIX"] = "canvas_data.screen_transform";
+ actions.renames["TIME"] = "canvas_data.time";
+ actions.renames["PI"] = _MKSTR(Math_PI);
+ actions.renames["TAU"] = _MKSTR(Math_TAU);
+ actions.renames["E"] = _MKSTR(Math_E);
+ actions.renames["AT_LIGHT_PASS"] = "false";
+ actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
+
+ actions.renames["COLOR"] = "color";
+ actions.renames["NORMAL"] = "normal";
+ actions.renames["NORMAL_MAP"] = "normal_map";
+ actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";
+ actions.renames["TEXTURE"] = "color_texture";
+ actions.renames["TEXTURE_PIXEL_SIZE"] = "draw_data.color_texture_pixel_size";
+ actions.renames["NORMAL_TEXTURE"] = "normal_texture";
+ actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";
+ actions.renames["SPECULAR_SHININESS"] = "specular_shininess";
+ actions.renames["SCREEN_UV"] = "screen_uv";
+ actions.renames["SCREEN_TEXTURE"] = "screen_texture";
+ actions.renames["SCREEN_PIXEL_SIZE"] = "canvas_data.screen_pixel_size";
+ actions.renames["FRAGCOORD"] = "gl_FragCoord";
+ actions.renames["POINT_COORD"] = "gl_PointCoord";
+ actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";
+ actions.renames["VERTEX_ID"] = "gl_VertexIndex";
+
+ actions.renames["LIGHT_POSITION"] = "light_position";
+ actions.renames["LIGHT_COLOR"] = "light_color";
+ actions.renames["LIGHT_ENERGY"] = "light_energy";
+ actions.renames["LIGHT"] = "light";
+ actions.renames["SHADOW_MODULATE"] = "shadow_modulate";
+
+ actions.renames["texture_sdf"] = "texture_sdf";
+ actions.renames["texture_sdf_normal"] = "texture_sdf_normal";
+ actions.renames["sdf_to_screen_uv"] = "sdf_to_screen_uv";
+ actions.renames["screen_uv_to_sdf"] = "screen_uv_to_sdf";
+
+ actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
+ actions.usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
+ actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
+ actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";
+ actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
+ actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
+ actions.usage_defines["LIGHT"] = "#define LIGHT_SHADER_CODE_USED\n";
+
+ actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
+ actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";
+ actions.render_mode_defines["light_only"] = "#define MODE_LIGHT_ONLY\n";
+
+ actions.base_texture_binding_index = 1;
+ actions.base_uniform_string = "";
+ actions.global_buffer_array_variable = "";
+
+ shaders.compiler_canvas.initialize(actions);
+ }
+
+ {
+ // Setup Scene compiler
+ /*
+ //shader compiler
+ ShaderCompiler::DefaultIdentifierActions actions;
+
+ actions.renames["MODEL_MATRIX"] = "model_matrix";
+ actions.renames["MODEL_NORMAL_MATRIX"] = "model_normal_matrix";
+ actions.renames["VIEW_MATRIX"] = "scene_data.view_matrix";
+ actions.renames["INV_VIEW_MATRIX"] = "scene_data.inv_view_matrix";
+ actions.renames["PROJECTION_MATRIX"] = "projection_matrix";
+ actions.renames["INV_PROJECTION_MATRIX"] = "inv_projection_matrix";
+ actions.renames["MODELVIEW_MATRIX"] = "modelview";
+ actions.renames["MODELVIEW_NORMAL_MATRIX"] = "modelview_normal";
+
+ actions.renames["VERTEX"] = "vertex";
+ actions.renames["NORMAL"] = "normal";
+ actions.renames["TANGENT"] = "tangent";
+ actions.renames["BINORMAL"] = "binormal";
+ actions.renames["POSITION"] = "position";
+ actions.renames["UV"] = "uv_interp";
+ actions.renames["UV2"] = "uv2_interp";
+ actions.renames["COLOR"] = "color_interp";
+ actions.renames["POINT_SIZE"] = "gl_PointSize";
+ actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";
+ actions.renames["VERTEX_ID"] = "gl_VertexIndex";
+
+ actions.renames["ALPHA_SCISSOR_THRESHOLD"] = "alpha_scissor_threshold";
+ actions.renames["ALPHA_HASH_SCALE"] = "alpha_hash_scale";
+ actions.renames["ALPHA_ANTIALIASING_EDGE"] = "alpha_antialiasing_edge";
+ actions.renames["ALPHA_TEXTURE_COORDINATE"] = "alpha_texture_coordinate";
+
+ //builtins
+
+ actions.renames["TIME"] = "scene_data.time";
+ actions.renames["PI"] = _MKSTR(Math_PI);
+ actions.renames["TAU"] = _MKSTR(Math_TAU);
+ actions.renames["E"] = _MKSTR(Math_E);
+ actions.renames["VIEWPORT_SIZE"] = "scene_data.viewport_size";
+
+ actions.renames["FRAGCOORD"] = "gl_FragCoord";
+ actions.renames["FRONT_FACING"] = "gl_FrontFacing";
+ actions.renames["NORMAL_MAP"] = "normal_map";
+ actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";
+ actions.renames["ALBEDO"] = "albedo";
+ actions.renames["ALPHA"] = "alpha";
+ actions.renames["METALLIC"] = "metallic";
+ actions.renames["SPECULAR"] = "specular";
+ actions.renames["ROUGHNESS"] = "roughness";
+ actions.renames["RIM"] = "rim";
+ actions.renames["RIM_TINT"] = "rim_tint";
+ actions.renames["CLEARCOAT"] = "clearcoat";
+ actions.renames["CLEARCOAT_ROUGHNESS"] = "clearcoat_roughness";
+ actions.renames["ANISOTROPY"] = "anisotropy";
+ actions.renames["ANISOTROPY_FLOW"] = "anisotropy_flow";
+ actions.renames["SSS_STRENGTH"] = "sss_strength";
+ actions.renames["SSS_TRANSMITTANCE_COLOR"] = "transmittance_color";
+ actions.renames["SSS_TRANSMITTANCE_DEPTH"] = "transmittance_depth";
+ actions.renames["SSS_TRANSMITTANCE_BOOST"] = "transmittance_boost";
+ actions.renames["BACKLIGHT"] = "backlight";
+ actions.renames["AO"] = "ao";
+ actions.renames["AO_LIGHT_AFFECT"] = "ao_light_affect";
+ actions.renames["EMISSION"] = "emission";
+ actions.renames["POINT_COORD"] = "gl_PointCoord";
+ actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
+ actions.renames["SCREEN_UV"] = "screen_uv";
+ actions.renames["SCREEN_TEXTURE"] = "color_buffer";
+ actions.renames["DEPTH_TEXTURE"] = "depth_buffer";
+ actions.renames["NORMAL_ROUGHNESS_TEXTURE"] = "normal_roughness_buffer";
+ actions.renames["DEPTH"] = "gl_FragDepth";
+ actions.renames["OUTPUT_IS_SRGB"] = "true";
+ actions.renames["FOG"] = "custom_fog";
+ actions.renames["RADIANCE"] = "custom_radiance";
+ actions.renames["IRRADIANCE"] = "custom_irradiance";
+ actions.renames["BONE_INDICES"] = "bone_attrib";
+ actions.renames["BONE_WEIGHTS"] = "weight_attrib";
+ actions.renames["CUSTOM0"] = "custom0_attrib";
+ actions.renames["CUSTOM1"] = "custom1_attrib";
+ actions.renames["CUSTOM2"] = "custom2_attrib";
+ actions.renames["CUSTOM3"] = "custom3_attrib";
+ actions.renames["OUTPUT_IS_SRGB"] = "SHADER_IS_SRGB";
+
+ actions.renames["VIEW_INDEX"] = "ViewIndex";
+ actions.renames["VIEW_MONO_LEFT"] = "0";
+ actions.renames["VIEW_RIGHT"] = "1";
+
+ //for light
+ actions.renames["VIEW"] = "view";
+ actions.renames["LIGHT_COLOR"] = "light_color";
+ actions.renames["LIGHT"] = "light";
+ actions.renames["ATTENUATION"] = "attenuation";
+ actions.renames["DIFFUSE_LIGHT"] = "diffuse_light";
+ actions.renames["SPECULAR_LIGHT"] = "specular_light";
+
+ actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
+ actions.usage_defines["TANGENT"] = "#define TANGENT_USED\n";
+ actions.usage_defines["BINORMAL"] = "@TANGENT";
+ actions.usage_defines["RIM"] = "#define LIGHT_RIM_USED\n";
+ actions.usage_defines["RIM_TINT"] = "@RIM";
+ actions.usage_defines["CLEARCOAT"] = "#define LIGHT_CLEARCOAT_USED\n";
+ actions.usage_defines["CLEARCOAT_ROUGHNESS"] = "@CLEARCOAT";
+ actions.usage_defines["ANISOTROPY"] = "#define LIGHT_ANISOTROPY_USED\n";
+ actions.usage_defines["ANISOTROPY_FLOW"] = "@ANISOTROPY";
+ actions.usage_defines["AO"] = "#define AO_USED\n";
+ actions.usage_defines["AO_LIGHT_AFFECT"] = "#define AO_USED\n";
+ actions.usage_defines["UV"] = "#define UV_USED\n";
+ actions.usage_defines["UV2"] = "#define UV2_USED\n";
+ actions.usage_defines["BONE_INDICES"] = "#define BONES_USED\n";
+ actions.usage_defines["BONE_WEIGHTS"] = "#define WEIGHTS_USED\n";
+ actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";
+ actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";
+ actions.usage_defines["CUSTOM2"] = "#define CUSTOM2_USED\n";
+ actions.usage_defines["CUSTOM3"] = "#define CUSTOM3_USED\n";
+ actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
+ actions.usage_defines["NORMAL_MAP_DEPTH"] = "@NORMAL_MAP";
+ actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
+ actions.usage_defines["INSTANCE_CUSTOM"] = "#define ENABLE_INSTANCE_CUSTOM\n";
+ actions.usage_defines["POSITION"] = "#define OVERRIDE_POSITION\n";
+
+ actions.usage_defines["ALPHA_SCISSOR_THRESHOLD"] = "#define ALPHA_SCISSOR_USED\n";
+ actions.usage_defines["ALPHA_HASH_SCALE"] = "#define ALPHA_HASH_USED\n";
+ actions.usage_defines["ALPHA_ANTIALIASING_EDGE"] = "#define ALPHA_ANTIALIASING_EDGE_USED\n";
+ actions.usage_defines["ALPHA_TEXTURE_COORDINATE"] = "@ALPHA_ANTIALIASING_EDGE";
+
+ actions.usage_defines["SSS_STRENGTH"] = "#define ENABLE_SSS\n";
+ actions.usage_defines["SSS_TRANSMITTANCE_DEPTH"] = "#define ENABLE_TRANSMITTANCE\n";
+ actions.usage_defines["BACKLIGHT"] = "#define LIGHT_BACKLIGHT_USED\n";
+ actions.usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
+ actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
+
+ actions.usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
+ actions.usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n";
+
+ actions.usage_defines["FOG"] = "#define CUSTOM_FOG_USED\n";
+ actions.usage_defines["RADIANCE"] = "#define CUSTOM_RADIANCE_USED\n";
+ actions.usage_defines["IRRADIANCE"] = "#define CUSTOM_IRRADIANCE_USED\n";
+
+ actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
+ actions.render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n";
+ actions.render_mode_defines["ensure_correct_normals"] = "#define ENSURE_CORRECT_NORMALS\n";
+ actions.render_mode_defines["cull_front"] = "#define DO_SIDE_CHECK\n";
+ actions.render_mode_defines["cull_disabled"] = "#define DO_SIDE_CHECK\n";
+ actions.render_mode_defines["particle_trails"] = "#define USE_PARTICLE_TRAILS\n";
+ actions.render_mode_defines["depth_draw_opaque"] = "#define USE_OPAQUE_PREPASS\n";
+
+ bool force_lambert = GLOBAL_GET("rendering/shading/overrides/force_lambert_over_burley");
+
+ if (!force_lambert) {
+ actions.render_mode_defines["diffuse_burley"] = "#define DIFFUSE_BURLEY\n";
}
- p_param_list->push_back(pi);
+ actions.render_mode_defines["diffuse_lambert_wrap"] = "#define DIFFUSE_LAMBERT_WRAP\n";
+ actions.render_mode_defines["diffuse_toon"] = "#define DIFFUSE_TOON\n";
+
+ actions.render_mode_defines["sss_mode_skin"] = "#define SSS_MODE_SKIN\n";
+
+ actions.render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_SCHLICK_GGX\n";
+
+ actions.custom_samplers["SCREEN_TEXTURE"] = "material_samplers[3]"; // linear filter with mipmaps
+ actions.custom_samplers["DEPTH_TEXTURE"] = "material_samplers[3]";
+ actions.custom_samplers["NORMAL_ROUGHNESS_TEXTURE"] = "material_samplers[1]"; // linear filter
+
+ actions.render_mode_defines["specular_toon"] = "#define SPECULAR_TOON\n";
+ actions.render_mode_defines["specular_disabled"] = "#define SPECULAR_DISABLED\n";
+ actions.render_mode_defines["shadows_disabled"] = "#define SHADOWS_DISABLED\n";
+ actions.render_mode_defines["ambient_light_disabled"] = "#define AMBIENT_LIGHT_DISABLED\n";
+ actions.render_mode_defines["shadow_to_opacity"] = "#define USE_SHADOW_TO_OPACITY\n";
+ actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";
+
+ actions.sampler_array_name = "material_samplers";
+ actions.base_texture_binding_index = 1;
+ actions.texture_layout_set = RenderForwardClustered::MATERIAL_UNIFORM_SET;
+ actions.base_uniform_string = "material.";
+ actions.base_varying_index = 10;
+
+ actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
+ actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
+ actions.global_buffer_array_variable = "global_variables.data";
+ actions.instance_uniform_index_variable = "instances.data[instance_index].instance_uniforms_ofs";
+
+ compiler.initialize(actions);
+ */
+ }
+
+ {
+ // Setup Particles compiler
+ /*
+ShaderCompiler::DefaultIdentifierActions actions;
+
+ actions.renames["COLOR"] = "PARTICLE.color";
+ actions.renames["VELOCITY"] = "PARTICLE.velocity";
+ //actions.renames["MASS"] = "mass"; ?
+ actions.renames["ACTIVE"] = "particle_active";
+ actions.renames["RESTART"] = "restart";
+ actions.renames["CUSTOM"] = "PARTICLE.custom";
+ for (int i = 0; i < ParticlesShader::MAX_USERDATAS; i++) {
+ String udname = "USERDATA" + itos(i + 1);
+ actions.renames[udname] = "PARTICLE.userdata" + itos(i + 1);
+ actions.usage_defines[udname] = "#define USERDATA" + itos(i + 1) + "_USED\n";
+ }
+ actions.renames["TRANSFORM"] = "PARTICLE.xform";
+ actions.renames["TIME"] = "frame_history.data[0].time";
+ actions.renames["PI"] = _MKSTR(Math_PI);
+ actions.renames["TAU"] = _MKSTR(Math_TAU);
+ actions.renames["E"] = _MKSTR(Math_E);
+ actions.renames["LIFETIME"] = "params.lifetime";
+ actions.renames["DELTA"] = "local_delta";
+ actions.renames["NUMBER"] = "particle_number";
+ actions.renames["INDEX"] = "index";
+ //actions.renames["GRAVITY"] = "current_gravity";
+ actions.renames["EMISSION_TRANSFORM"] = "FRAME.emission_transform";
+ actions.renames["RANDOM_SEED"] = "FRAME.random_seed";
+ actions.renames["FLAG_EMIT_POSITION"] = "EMISSION_FLAG_HAS_POSITION";
+ actions.renames["FLAG_EMIT_ROT_SCALE"] = "EMISSION_FLAG_HAS_ROTATION_SCALE";
+ actions.renames["FLAG_EMIT_VELOCITY"] = "EMISSION_FLAG_HAS_VELOCITY";
+ actions.renames["FLAG_EMIT_COLOR"] = "EMISSION_FLAG_HAS_COLOR";
+ actions.renames["FLAG_EMIT_CUSTOM"] = "EMISSION_FLAG_HAS_CUSTOM";
+ actions.renames["RESTART_POSITION"] = "restart_position";
+ actions.renames["RESTART_ROT_SCALE"] = "restart_rotation_scale";
+ actions.renames["RESTART_VELOCITY"] = "restart_velocity";
+ actions.renames["RESTART_COLOR"] = "restart_color";
+ actions.renames["RESTART_CUSTOM"] = "restart_custom";
+ actions.renames["emit_subparticle"] = "emit_subparticle";
+ actions.renames["COLLIDED"] = "collided";
+ actions.renames["COLLISION_NORMAL"] = "collision_normal";
+ actions.renames["COLLISION_DEPTH"] = "collision_depth";
+ actions.renames["ATTRACTOR_FORCE"] = "attractor_force";
+
+ actions.render_mode_defines["disable_force"] = "#define DISABLE_FORCE\n";
+ actions.render_mode_defines["disable_velocity"] = "#define DISABLE_VELOCITY\n";
+ actions.render_mode_defines["keep_data"] = "#define ENABLE_KEEP_DATA\n";
+ actions.render_mode_defines["collision_use_scale"] = "#define USE_COLLISON_SCALE\n";
+
+ actions.sampler_array_name = "material_samplers";
+ actions.base_texture_binding_index = 1;
+ actions.texture_layout_set = 3;
+ actions.base_uniform_string = "material.";
+ actions.base_varying_index = 10;
+
+ actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
+ actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
+ actions.global_buffer_array_variable = "global_variables.data";
+
+ particles_shader.compiler.initialize(actions);
+ */
}
+
+ {
+ // Setup Sky compiler
+ ShaderCompiler::DefaultIdentifierActions actions;
+
+ actions.renames["COLOR"] = "color";
+ actions.renames["ALPHA"] = "alpha";
+ actions.renames["EYEDIR"] = "cube_normal";
+ actions.renames["POSITION"] = "params.position_multiplier.xyz";
+ actions.renames["SKY_COORDS"] = "panorama_coords";
+ actions.renames["SCREEN_UV"] = "uv";
+ actions.renames["TIME"] = "params.time";
+ actions.renames["PI"] = _MKSTR(Math_PI);
+ actions.renames["TAU"] = _MKSTR(Math_TAU);
+ actions.renames["E"] = _MKSTR(Math_E);
+ actions.renames["HALF_RES_COLOR"] = "half_res_color";
+ actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
+ actions.renames["RADIANCE"] = "radiance";
+ actions.renames["FOG"] = "custom_fog";
+ actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
+ actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
+ actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
+ actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
+ actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
+ actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
+ actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
+ actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
+ actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
+ actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
+ actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
+ actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
+ actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
+ actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
+ actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
+ actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
+ actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
+ actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
+ actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
+ actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
+ actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
+ actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
+ actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
+ actions.custom_samplers["RADIANCE"] = "material_samplers[3]";
+ actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
+ actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
+ actions.render_mode_defines["disable_fog"] = "#define DISABLE_FOG\n";
+
+ actions.sampler_array_name = "material_samplers";
+ actions.base_texture_binding_index = 1;
+ actions.texture_layout_set = 1;
+ actions.base_uniform_string = "material.";
+ actions.base_varying_index = 10;
+
+ actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
+ actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
+ actions.global_buffer_array_variable = "global_variables";
+
+ shaders.compiler_sky.initialize(actions);
+ }
+
+ //shaders.copy.initialize();
+ //shaders.copy_version = shaders.copy.version_create(); //TODO
+ //shaders.copy.version_bind_shader(shaders.copy_version, CopyShaderGLES3::MODE_COPY_SECTION);
+ //shaders.cubemap_filter.init();
+ //bool ggx_hq = GLOBAL_GET("rendering/quality/reflections/high_quality_ggx");
+ //shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, !ggx_hq);
}
-void MaterialStorage::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture, int p_index) {
- GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
- ERR_FAIL_COND(!shader);
- ERR_FAIL_COND(p_texture.is_valid() && !TextureStorage::get_singleton()->owns_texture(p_texture));
+MaterialStorage::~MaterialStorage() {
+ //shaders.copy.version_free(shaders.copy_version);
- if (!p_texture.is_valid()) {
- if (shader->default_textures.has(p_name) && shader->default_textures[p_name].has(p_index)) {
- shader->default_textures[p_name].erase(p_index);
+ memdelete_arr(global_variables.buffer_values);
+ memdelete_arr(global_variables.buffer_usage);
+ memdelete_arr(global_variables.buffer_dirty_regions);
+ glDeleteBuffers(1, &global_variables.buffer);
+
+ singleton = nullptr;
+}
+
+/* GLOBAL VARIABLE API */
- if (shader->default_textures[p_name].is_empty()) {
- shader->default_textures.erase(p_name);
+int32_t MaterialStorage::_global_variable_allocate(uint32_t p_elements) {
+ int32_t idx = 0;
+ while (idx + p_elements <= global_variables.buffer_size) {
+ if (global_variables.buffer_usage[idx].elements == 0) {
+ bool valid = true;
+ for (uint32_t i = 1; i < p_elements; i++) {
+ if (global_variables.buffer_usage[idx + i].elements > 0) {
+ valid = false;
+ idx += i + global_variables.buffer_usage[idx + i].elements;
+ break;
+ }
}
+
+ if (!valid) {
+ continue; //if not valid, idx is in new position
+ }
+
+ return idx;
+ } else {
+ idx += global_variables.buffer_usage[idx].elements;
}
- } else {
- if (!shader->default_textures.has(p_name)) {
- shader->default_textures[p_name] = Map<int, RID>();
- }
- shader->default_textures[p_name][p_index] = p_texture;
}
- _shader_make_dirty(shader);
+ return -1;
}
-RID MaterialStorage::shader_get_default_texture_param(RID p_shader, const StringName &p_name, int p_index) const {
- const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
- ERR_FAIL_COND_V(!shader, RID());
+void MaterialStorage::_global_variable_store_in_buffer(int32_t p_index, RS::GlobalVariableType p_type, const Variant &p_value) {
+ switch (p_type) {
+ case RS::GLOBAL_VAR_TYPE_BOOL: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ bool b = p_value;
+ bv.x = b ? 1.0 : 0.0;
+ bv.y = 0.0;
+ bv.z = 0.0;
+ bv.w = 0.0;
- if (shader->default_textures.has(p_name) && shader->default_textures[p_name].has(p_index)) {
- return shader->default_textures[p_name][p_index];
- }
+ } break;
+ case RS::GLOBAL_VAR_TYPE_BVEC2: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ uint32_t bvec = p_value;
+ bv.x = (bvec & 1) ? 1.0 : 0.0;
+ bv.y = (bvec & 2) ? 1.0 : 0.0;
+ bv.z = 0.0;
+ bv.w = 0.0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_BVEC3: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ uint32_t bvec = p_value;
+ bv.x = (bvec & 1) ? 1.0 : 0.0;
+ bv.y = (bvec & 2) ? 1.0 : 0.0;
+ bv.z = (bvec & 4) ? 1.0 : 0.0;
+ bv.w = 0.0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_BVEC4: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ uint32_t bvec = p_value;
+ bv.x = (bvec & 1) ? 1.0 : 0.0;
+ bv.y = (bvec & 2) ? 1.0 : 0.0;
+ bv.z = (bvec & 4) ? 1.0 : 0.0;
+ bv.w = (bvec & 8) ? 1.0 : 0.0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_INT: {
+ GlobalVariables::ValueInt &bv = *(GlobalVariables::ValueInt *)&global_variables.buffer_values[p_index];
+ int32_t v = p_value;
+ bv.x = v;
+ bv.y = 0;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_IVEC2: {
+ GlobalVariables::ValueInt &bv = *(GlobalVariables::ValueInt *)&global_variables.buffer_values[p_index];
+ Vector2i v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_IVEC3: {
+ GlobalVariables::ValueInt &bv = *(GlobalVariables::ValueInt *)&global_variables.buffer_values[p_index];
+ Vector3i v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = v.z;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_IVEC4: {
+ GlobalVariables::ValueInt &bv = *(GlobalVariables::ValueInt *)&global_variables.buffer_values[p_index];
+ Vector<int32_t> v = p_value;
+ bv.x = v.size() >= 1 ? v[0] : 0;
+ bv.y = v.size() >= 2 ? v[1] : 0;
+ bv.z = v.size() >= 3 ? v[2] : 0;
+ bv.w = v.size() >= 4 ? v[3] : 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_RECT2I: {
+ GlobalVariables::ValueInt &bv = *(GlobalVariables::ValueInt *)&global_variables.buffer_values[p_index];
+ Rect2i v = p_value;
+ bv.x = v.position.x;
+ bv.y = v.position.y;
+ bv.z = v.size.x;
+ bv.w = v.size.y;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_UINT: {
+ GlobalVariables::ValueUInt &bv = *(GlobalVariables::ValueUInt *)&global_variables.buffer_values[p_index];
+ uint32_t v = p_value;
+ bv.x = v;
+ bv.y = 0;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_UVEC2: {
+ GlobalVariables::ValueUInt &bv = *(GlobalVariables::ValueUInt *)&global_variables.buffer_values[p_index];
+ Vector2i v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_UVEC3: {
+ GlobalVariables::ValueUInt &bv = *(GlobalVariables::ValueUInt *)&global_variables.buffer_values[p_index];
+ Vector3i v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = v.z;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_UVEC4: {
+ GlobalVariables::ValueUInt &bv = *(GlobalVariables::ValueUInt *)&global_variables.buffer_values[p_index];
+ Vector<int32_t> v = p_value;
+ bv.x = v.size() >= 1 ? v[0] : 0;
+ bv.y = v.size() >= 2 ? v[1] : 0;
+ bv.z = v.size() >= 3 ? v[2] : 0;
+ bv.w = v.size() >= 4 ? v[3] : 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_FLOAT: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ float v = p_value;
+ bv.x = v;
+ bv.y = 0;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_VEC2: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ Vector2 v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = 0;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_VEC3: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ Vector3 v = p_value;
+ bv.x = v.x;
+ bv.y = v.y;
+ bv.z = v.z;
+ bv.w = 0;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_VEC4: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ Plane v = p_value;
+ bv.x = v.normal.x;
+ bv.y = v.normal.y;
+ bv.z = v.normal.z;
+ bv.w = v.d;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_COLOR: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ Color v = p_value;
+ bv.x = v.r;
+ bv.y = v.g;
+ bv.z = v.b;
+ bv.w = v.a;
+
+ GlobalVariables::Value &bv_linear = global_variables.buffer_values[p_index + 1];
+ v = v.srgb_to_linear();
+ bv_linear.x = v.r;
+ bv_linear.y = v.g;
+ bv_linear.z = v.b;
+ bv_linear.w = v.a;
- return RID();
-}
+ } break;
+ case RS::GLOBAL_VAR_TYPE_RECT2: {
+ GlobalVariables::Value &bv = global_variables.buffer_values[p_index];
+ Rect2 v = p_value;
+ bv.x = v.position.x;
+ bv.y = v.position.y;
+ bv.z = v.size.x;
+ bv.w = v.size.y;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_MAT2: {
+ GlobalVariables::Value *bv = &global_variables.buffer_values[p_index];
+ Vector<float> m2 = p_value;
+ if (m2.size() < 4) {
+ m2.resize(4);
+ }
+ bv[0].x = m2[0];
+ bv[0].y = m2[1];
+ bv[0].z = 0;
+ bv[0].w = 0;
-void MaterialStorage::_update_shader(GLES3::Shader *p_shader) const {
- _shader_dirty_list.remove(&p_shader->dirty_list);
+ bv[1].x = m2[2];
+ bv[1].y = m2[3];
+ bv[1].z = 0;
+ bv[1].w = 0;
- p_shader->valid = false;
+ } break;
+ case RS::GLOBAL_VAR_TYPE_MAT3: {
+ GlobalVariables::Value *bv = &global_variables.buffer_values[p_index];
+ Basis v = p_value;
+ bv[0].x = v.elements[0][0];
+ bv[0].y = v.elements[1][0];
+ bv[0].z = v.elements[2][0];
+ bv[0].w = 0;
+
+ bv[1].x = v.elements[0][1];
+ bv[1].y = v.elements[1][1];
+ bv[1].z = v.elements[2][1];
+ bv[1].w = 0;
+
+ bv[2].x = v.elements[0][2];
+ bv[2].y = v.elements[1][2];
+ bv[2].z = v.elements[2][2];
+ bv[2].w = 0;
- p_shader->uniforms.clear();
+ } break;
+ case RS::GLOBAL_VAR_TYPE_MAT4: {
+ GlobalVariables::Value *bv = &global_variables.buffer_values[p_index];
- if (p_shader->code.is_empty()) {
- return; //just invalid, but no error
- }
+ Vector<float> m2 = p_value;
+ if (m2.size() < 16) {
+ m2.resize(16);
+ }
+
+ bv[0].x = m2[0];
+ bv[0].y = m2[1];
+ bv[0].z = m2[2];
+ bv[0].w = m2[3];
+
+ bv[1].x = m2[4];
+ bv[1].y = m2[5];
+ bv[1].z = m2[6];
+ bv[1].w = m2[7];
+
+ bv[2].x = m2[8];
+ bv[2].y = m2[9];
+ bv[2].z = m2[10];
+ bv[2].w = m2[11];
+
+ bv[3].x = m2[12];
+ bv[3].y = m2[13];
+ bv[3].z = m2[14];
+ bv[3].w = m2[15];
- ShaderCompiler::GeneratedCode gen_code;
- ShaderCompiler::IdentifierActions *actions = nullptr;
-
- switch (p_shader->mode) {
- case RS::SHADER_CANVAS_ITEM: {
- p_shader->canvas_item.light_mode = GLES3::Shader::CanvasItem::LIGHT_MODE_NORMAL;
- p_shader->canvas_item.blend_mode = GLES3::Shader::CanvasItem::BLEND_MODE_MIX;
-
- p_shader->canvas_item.uses_screen_texture = false;
- p_shader->canvas_item.uses_screen_uv = false;
- p_shader->canvas_item.uses_time = false;
- p_shader->canvas_item.uses_modulate = false;
- p_shader->canvas_item.uses_color = false;
- p_shader->canvas_item.uses_vertex = false;
-
- p_shader->canvas_item.uses_model_matrix = false;
- p_shader->canvas_item.uses_extra_matrix = false;
- p_shader->canvas_item.uses_projection_matrix = false;
- p_shader->canvas_item.uses_instance_custom = false;
-
- shaders.actions_canvas.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, GLES3::Shader::CanvasItem::BLEND_MODE_ADD);
- shaders.actions_canvas.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, GLES3::Shader::CanvasItem::BLEND_MODE_MIX);
- shaders.actions_canvas.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, GLES3::Shader::CanvasItem::BLEND_MODE_SUB);
- shaders.actions_canvas.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, GLES3::Shader::CanvasItem::BLEND_MODE_MUL);
- shaders.actions_canvas.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, GLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA);
-
- shaders.actions_canvas.render_mode_values["unshaded"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, GLES3::Shader::CanvasItem::LIGHT_MODE_UNSHADED);
- shaders.actions_canvas.render_mode_values["light_only"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, GLES3::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY);
-
- shaders.actions_canvas.usage_flag_pointers["SCREEN_UV"] = &p_shader->canvas_item.uses_screen_uv;
- shaders.actions_canvas.usage_flag_pointers["SCREEN_PIXEL_SIZE"] = &p_shader->canvas_item.uses_screen_uv;
- shaders.actions_canvas.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->canvas_item.uses_screen_texture;
- shaders.actions_canvas.usage_flag_pointers["TIME"] = &p_shader->canvas_item.uses_time;
- shaders.actions_canvas.usage_flag_pointers["MODULATE"] = &p_shader->canvas_item.uses_modulate;
- shaders.actions_canvas.usage_flag_pointers["COLOR"] = &p_shader->canvas_item.uses_color;
-
- shaders.actions_canvas.usage_flag_pointers["VERTEX"] = &p_shader->canvas_item.uses_vertex;
-
- shaders.actions_canvas.usage_flag_pointers["MODEL_MATRIX"] = &p_shader->canvas_item.uses_model_matrix;
- shaders.actions_canvas.usage_flag_pointers["EXTRA_MATRIX"] = &p_shader->canvas_item.uses_extra_matrix;
- shaders.actions_canvas.usage_flag_pointers["PROJECTION_MATRIX"] = &p_shader->canvas_item.uses_projection_matrix;
- shaders.actions_canvas.usage_flag_pointers["INSTANCE_CUSTOM"] = &p_shader->canvas_item.uses_instance_custom;
-
- actions = &shaders.actions_canvas;
- actions->uniforms = &p_shader->uniforms;
- } break;
-
- case RS::SHADER_SPATIAL: {
- // TODO remove once 3D is added back
- return;
- p_shader->spatial.blend_mode = GLES3::Shader::Spatial::BLEND_MODE_MIX;
- p_shader->spatial.depth_draw_mode = GLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE;
- p_shader->spatial.cull_mode = GLES3::Shader::Spatial::CULL_MODE_BACK;
- p_shader->spatial.uses_alpha = false;
- p_shader->spatial.uses_alpha_scissor = false;
- p_shader->spatial.uses_discard = false;
- p_shader->spatial.unshaded = false;
- p_shader->spatial.no_depth_test = false;
- p_shader->spatial.uses_sss = false;
- p_shader->spatial.uses_time = false;
- p_shader->spatial.uses_vertex_lighting = false;
- p_shader->spatial.uses_screen_texture = false;
- p_shader->spatial.uses_depth_texture = false;
- p_shader->spatial.uses_vertex = false;
- p_shader->spatial.uses_tangent = false;
- p_shader->spatial.uses_ensure_correct_normals = false;
- p_shader->spatial.writes_modelview_or_projection = false;
- p_shader->spatial.uses_world_coordinates = false;
-
- shaders.actions_scene.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->spatial.blend_mode, GLES3::Shader::Spatial::BLEND_MODE_ADD);
- shaders.actions_scene.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->spatial.blend_mode, GLES3::Shader::Spatial::BLEND_MODE_MIX);
- shaders.actions_scene.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->spatial.blend_mode, GLES3::Shader::Spatial::BLEND_MODE_SUB);
- shaders.actions_scene.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->spatial.blend_mode, GLES3::Shader::Spatial::BLEND_MODE_MUL);
-
- shaders.actions_scene.render_mode_values["depth_draw_opaque"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, GLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE);
- shaders.actions_scene.render_mode_values["depth_draw_always"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, GLES3::Shader::Spatial::DEPTH_DRAW_ALWAYS);
- shaders.actions_scene.render_mode_values["depth_draw_never"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, GLES3::Shader::Spatial::DEPTH_DRAW_NEVER);
- shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, GLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS);
-
- shaders.actions_scene.render_mode_values["cull_front"] = Pair<int *, int>(&p_shader->spatial.cull_mode, GLES3::Shader::Spatial::CULL_MODE_FRONT);
- shaders.actions_scene.render_mode_values["cull_back"] = Pair<int *, int>(&p_shader->spatial.cull_mode, GLES3::Shader::Spatial::CULL_MODE_BACK);
- shaders.actions_scene.render_mode_values["cull_disabled"] = Pair<int *, int>(&p_shader->spatial.cull_mode, GLES3::Shader::Spatial::CULL_MODE_DISABLED);
-
- shaders.actions_scene.render_mode_flags["unshaded"] = &p_shader->spatial.unshaded;
- shaders.actions_scene.render_mode_flags["depth_test_disable"] = &p_shader->spatial.no_depth_test;
-
- shaders.actions_scene.render_mode_flags["vertex_lighting"] = &p_shader->spatial.uses_vertex_lighting;
-
- shaders.actions_scene.render_mode_flags["world_vertex_coords"] = &p_shader->spatial.uses_world_coordinates;
-
- shaders.actions_scene.render_mode_flags["ensure_correct_normals"] = &p_shader->spatial.uses_ensure_correct_normals;
-
- shaders.actions_scene.usage_flag_pointers["ALPHA"] = &p_shader->spatial.uses_alpha;
- shaders.actions_scene.usage_flag_pointers["ALPHA_SCISSOR"] = &p_shader->spatial.uses_alpha_scissor;
-
- shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"] = &p_shader->spatial.uses_sss;
- shaders.actions_scene.usage_flag_pointers["DISCARD"] = &p_shader->spatial.uses_discard;
- shaders.actions_scene.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->spatial.uses_screen_texture;
- shaders.actions_scene.usage_flag_pointers["DEPTH_TEXTURE"] = &p_shader->spatial.uses_depth_texture;
- shaders.actions_scene.usage_flag_pointers["TIME"] = &p_shader->spatial.uses_time;
-
- // Use of any of these BUILTINS indicate the need for transformed tangents.
- // This is needed to know when to transform tangents in software skinning.
- shaders.actions_scene.usage_flag_pointers["TANGENT"] = &p_shader->spatial.uses_tangent;
- shaders.actions_scene.usage_flag_pointers["NORMALMAP"] = &p_shader->spatial.uses_tangent;
-
- shaders.actions_scene.write_flag_pointers["MODELVIEW_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection;
- shaders.actions_scene.write_flag_pointers["PROJECTION_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection;
- shaders.actions_scene.write_flag_pointers["VERTEX"] = &p_shader->spatial.uses_vertex;
-
- actions = &shaders.actions_scene;
- actions->uniforms = &p_shader->uniforms;
} break;
+ case RS::GLOBAL_VAR_TYPE_TRANSFORM_2D: {
+ GlobalVariables::Value *bv = &global_variables.buffer_values[p_index];
+ Transform2D v = p_value;
+ bv[0].x = v.elements[0][0];
+ bv[0].y = v.elements[0][1];
+ bv[0].z = 0;
+ bv[0].w = 0;
+
+ bv[1].x = v.elements[1][0];
+ bv[1].y = v.elements[1][1];
+ bv[1].z = 0;
+ bv[1].w = 0;
+
+ bv[2].x = v.elements[2][0];
+ bv[2].y = v.elements[2][1];
+ bv[2].z = 1;
+ bv[2].w = 0;
- default: {
- return;
} break;
- }
+ case RS::GLOBAL_VAR_TYPE_TRANSFORM: {
+ GlobalVariables::Value *bv = &global_variables.buffer_values[p_index];
+ Transform3D v = p_value;
+ bv[0].x = v.basis.elements[0][0];
+ bv[0].y = v.basis.elements[1][0];
+ bv[0].z = v.basis.elements[2][0];
+ bv[0].w = 0;
+
+ bv[1].x = v.basis.elements[0][1];
+ bv[1].y = v.basis.elements[1][1];
+ bv[1].z = v.basis.elements[2][1];
+ bv[1].w = 0;
+
+ bv[2].x = v.basis.elements[0][2];
+ bv[2].y = v.basis.elements[1][2];
+ bv[2].z = v.basis.elements[2][2];
+ bv[2].w = 0;
+
+ bv[3].x = v.origin.x;
+ bv[3].y = v.origin.y;
+ bv[3].z = v.origin.z;
+ bv[3].w = 1;
- Error err = shaders.compiler.compile(p_shader->mode, p_shader->code, actions, p_shader->path, gen_code);
- if (err != OK) {
- return;
+ } break;
+ default: {
+ ERR_FAIL();
+ }
}
+}
- Vector<StringName> texture_uniform_names;
- for (int i = 0; i < gen_code.texture_uniforms.size(); i++) {
- texture_uniform_names.push_back(gen_code.texture_uniforms[i].name);
+void MaterialStorage::_global_variable_mark_buffer_dirty(int32_t p_index, int32_t p_elements) {
+ int32_t prev_chunk = -1;
+
+ for (int32_t i = 0; i < p_elements; i++) {
+ int32_t chunk = (p_index + i) / GlobalVariables::BUFFER_DIRTY_REGION_SIZE;
+ if (chunk != prev_chunk) {
+ if (!global_variables.buffer_dirty_regions[chunk]) {
+ global_variables.buffer_dirty_regions[chunk] = true;
+ global_variables.buffer_dirty_region_count++;
+ }
+ }
+
+ prev_chunk = chunk;
}
+}
- p_shader->shader->version_set_code(p_shader->version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_names);
+void MaterialStorage::global_variable_add(const StringName &p_name, RS::GlobalVariableType p_type, const Variant &p_value) {
+ ERR_FAIL_COND(global_variables.variables.has(p_name));
+ GlobalVariables::Variable gv;
+ gv.type = p_type;
+ gv.value = p_value;
+ gv.buffer_index = -1;
+
+ if (p_type >= RS::GLOBAL_VAR_TYPE_SAMPLER2D) {
+ //is texture
+ global_variables.must_update_texture_materials = true; //normally there are none
+ } else {
+ gv.buffer_elements = 1;
+ if (p_type == RS::GLOBAL_VAR_TYPE_COLOR || p_type == RS::GLOBAL_VAR_TYPE_MAT2) {
+ //color needs to elements to store srgb and linear
+ gv.buffer_elements = 2;
+ }
+ if (p_type == RS::GLOBAL_VAR_TYPE_MAT3 || p_type == RS::GLOBAL_VAR_TYPE_TRANSFORM_2D) {
+ //color needs to elements to store srgb and linear
+ gv.buffer_elements = 3;
+ }
+ if (p_type == RS::GLOBAL_VAR_TYPE_MAT4 || p_type == RS::GLOBAL_VAR_TYPE_TRANSFORM) {
+ //color needs to elements to store srgb and linear
+ gv.buffer_elements = 4;
+ }
- p_shader->texture_uniforms = gen_code.texture_uniforms;
+ //is vector, allocate in buffer and update index
+ gv.buffer_index = _global_variable_allocate(gv.buffer_elements);
+ ERR_FAIL_COND_MSG(gv.buffer_index < 0, vformat("Failed allocating global variable '%s' out of buffer memory. Consider increasing it in the Project Settings.", String(p_name)));
+ global_variables.buffer_usage[gv.buffer_index].elements = gv.buffer_elements;
+ _global_variable_store_in_buffer(gv.buffer_index, gv.type, gv.value);
+ _global_variable_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
- p_shader->uses_vertex_time = gen_code.uses_vertex_time;
- p_shader->uses_fragment_time = gen_code.uses_fragment_time;
+ global_variables.must_update_buffer_materials = true; //normally there are none
+ }
+
+ global_variables.variables[p_name] = gv;
+}
+
+void MaterialStorage::global_variable_remove(const StringName &p_name) {
+ if (!global_variables.variables.has(p_name)) {
+ return;
+ }
+ GlobalVariables::Variable &gv = global_variables.variables[p_name];
- for (SelfList<GLES3::Material> *E = p_shader->materials.first(); E; E = E->next()) {
- _material_make_dirty(E->self());
+ if (gv.buffer_index >= 0) {
+ global_variables.buffer_usage[gv.buffer_index].elements = 0;
+ global_variables.must_update_buffer_materials = true;
+ } else {
+ global_variables.must_update_texture_materials = true;
}
- p_shader->valid = true;
+ global_variables.variables.erase(p_name);
}
-void MaterialStorage::update_dirty_shaders() {
- while (_shader_dirty_list.first()) {
- _update_shader(_shader_dirty_list.first()->self());
+Vector<StringName> MaterialStorage::global_variable_get_list() const {
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ ERR_FAIL_V_MSG(Vector<StringName>(), "This function should never be used outside the editor, it can severely damage performance.");
+ }
+
+ const StringName *K = nullptr;
+ Vector<StringName> names;
+ while ((K = global_variables.variables.next(K))) {
+ names.push_back(*K);
}
+ names.sort_custom<StringName::AlphCompare>();
+ return names;
}
-/* MATERIAL API */
+void MaterialStorage::global_variable_set(const StringName &p_name, const Variant &p_value) {
+ ERR_FAIL_COND(!global_variables.variables.has(p_name));
+ GlobalVariables::Variable &gv = global_variables.variables[p_name];
+ gv.value = p_value;
+ if (gv.override.get_type() == Variant::NIL) {
+ if (gv.buffer_index >= 0) {
+ //buffer
+ _global_variable_store_in_buffer(gv.buffer_index, gv.type, gv.value);
+ _global_variable_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
+ } else {
+ //texture
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ for (Set<RID>::Element *E = gv.texture_materials.front(); E; E = E->next()) {
+ Material *material = material_storage->get_material(E->get());
+ ERR_CONTINUE(!material);
+ material_storage->_material_queue_update(material, false, true);
+ }
+ }
+ }
+}
-void MaterialStorage::_material_make_dirty(GLES3::Material *p_material) const {
- if (p_material->dirty_list.in_list()) {
- return;
+void MaterialStorage::global_variable_set_override(const StringName &p_name, const Variant &p_value) {
+ if (!global_variables.variables.has(p_name)) {
+ return; //variable may not exist
}
- _material_dirty_list.add(&p_material->dirty_list);
+ ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT);
+
+ GlobalVariables::Variable &gv = global_variables.variables[p_name];
+
+ gv.override = p_value;
+
+ if (gv.buffer_index >= 0) {
+ //buffer
+ if (gv.override.get_type() == Variant::NIL) {
+ _global_variable_store_in_buffer(gv.buffer_index, gv.type, gv.value);
+ } else {
+ _global_variable_store_in_buffer(gv.buffer_index, gv.type, gv.override);
+ }
+
+ _global_variable_mark_buffer_dirty(gv.buffer_index, gv.buffer_elements);
+ } else {
+ //texture
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ for (Set<RID>::Element *E = gv.texture_materials.front(); E; E = E->next()) {
+ Material *material = material_storage->get_material(E->get());
+ ERR_CONTINUE(!material);
+ material_storage->_material_queue_update(material, false, true);
+ }
+ }
}
-void MaterialStorage::_update_material(GLES3::Material *p_material) {
- if (p_material->dirty_list.in_list()) {
- _material_dirty_list.remove(&p_material->dirty_list);
+Variant MaterialStorage::global_variable_get(const StringName &p_name) const {
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ ERR_FAIL_V_MSG(Variant(), "This function should never be used outside the editor, it can severely damage performance.");
}
- if (p_material->shader && p_material->shader->dirty_list.in_list()) {
- _update_shader(p_material->shader);
+ if (!global_variables.variables.has(p_name)) {
+ return Variant();
}
- if (p_material->shader && !p_material->shader->valid) {
- return;
+ return global_variables.variables[p_name].value;
+}
+
+RS::GlobalVariableType MaterialStorage::global_variable_get_type_internal(const StringName &p_name) const {
+ if (!global_variables.variables.has(p_name)) {
+ return RS::GLOBAL_VAR_TYPE_MAX;
}
- {
- if (p_material->shader && p_material->shader->mode == RS::SHADER_SPATIAL) {
- bool can_cast_shadow = false;
- bool is_animated = false;
+ return global_variables.variables[p_name].type;
+}
- if (p_material->shader->spatial.blend_mode == GLES3::Shader::Spatial::BLEND_MODE_MIX &&
+RS::GlobalVariableType MaterialStorage::global_variable_get_type(const StringName &p_name) const {
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ ERR_FAIL_V_MSG(RS::GLOBAL_VAR_TYPE_MAX, "This function should never be used outside the editor, it can severely damage performance.");
+ }
+
+ return global_variable_get_type_internal(p_name);
+}
- (!p_material->shader->spatial.uses_alpha || p_material->shader->spatial.depth_draw_mode == Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) {
- can_cast_shadow = true;
+void MaterialStorage::global_variables_load_settings(bool p_load_textures) {
+ List<PropertyInfo> settings;
+ ProjectSettings::get_singleton()->get_property_list(&settings);
+
+ for (const PropertyInfo &E : settings) {
+ if (E.name.begins_with("shader_globals/")) {
+ StringName name = E.name.get_slice("/", 1);
+ Dictionary d = ProjectSettings::get_singleton()->get(E.name);
+
+ ERR_CONTINUE(!d.has("type"));
+ ERR_CONTINUE(!d.has("value"));
+
+ String type = d["type"];
+
+ static const char *global_var_type_names[RS::GLOBAL_VAR_TYPE_MAX] = {
+ "bool",
+ "bvec2",
+ "bvec3",
+ "bvec4",
+ "int",
+ "ivec2",
+ "ivec3",
+ "ivec4",
+ "rect2i",
+ "uint",
+ "uvec2",
+ "uvec3",
+ "uvec4",
+ "float",
+ "vec2",
+ "vec3",
+ "vec4",
+ "color",
+ "rect2",
+ "mat2",
+ "mat3",
+ "mat4",
+ "transform_2d",
+ "transform",
+ "sampler2D",
+ "sampler2DArray",
+ "sampler3D",
+ "samplerCube",
+ };
+
+ RS::GlobalVariableType gvtype = RS::GLOBAL_VAR_TYPE_MAX;
+
+ for (int i = 0; i < RS::GLOBAL_VAR_TYPE_MAX; i++) {
+ if (global_var_type_names[i] == type) {
+ gvtype = RS::GlobalVariableType(i);
+ break;
+ }
}
- if (p_material->shader->spatial.uses_discard && p_material->shader->uses_fragment_time) {
- is_animated = true;
+ ERR_CONTINUE(gvtype == RS::GLOBAL_VAR_TYPE_MAX); //type invalid
+
+ Variant value = d["value"];
+
+ if (gvtype >= RS::GLOBAL_VAR_TYPE_SAMPLER2D) {
+ //textire
+ if (!p_load_textures) {
+ value = RID();
+ continue;
+ }
+
+ String path = value;
+ RES resource = ResourceLoader::load(path);
+ ERR_CONTINUE(resource.is_null());
+ value = resource;
}
- if (p_material->shader->spatial.uses_vertex && p_material->shader->uses_vertex_time) {
- is_animated = true;
+ if (global_variables.variables.has(name)) {
+ //has it, update it
+ global_variable_set(name, value);
+ } else {
+ global_variable_add(name, gvtype, value);
}
+ }
+ }
+}
- if (can_cast_shadow != p_material->can_cast_shadow_cache || is_animated != p_material->is_animated_cache) {
- p_material->can_cast_shadow_cache = can_cast_shadow;
- p_material->is_animated_cache = is_animated;
+void MaterialStorage::global_variables_clear() {
+ global_variables.variables.clear();
+}
- /*
- for (Map<Geometry *, int>::Element *E = p_material->geometry_owners.front(); E; E = E->next()) {
- E->key()->material_changed_notify();
- }
+GLuint MaterialStorage::global_variables_get_uniform_buffer() const {
+ return global_variables.buffer;
+}
- for (Map<InstanceBaseDependency *, int>::Element *E = p_material->instance_owners.front(); E; E = E->next()) {
- E->key()->base_changed(false, true);
+int32_t MaterialStorage::global_variables_instance_allocate(RID p_instance) {
+ ERR_FAIL_COND_V(global_variables.instance_buffer_pos.has(p_instance), -1);
+ int32_t pos = _global_variable_allocate(ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES);
+ global_variables.instance_buffer_pos[p_instance] = pos; //save anyway
+ ERR_FAIL_COND_V_MSG(pos < 0, -1, "Too many instances using shader instance variables. Increase buffer size in Project Settings.");
+ global_variables.buffer_usage[pos].elements = ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES;
+ return pos;
+}
+
+void MaterialStorage::global_variables_instance_free(RID p_instance) {
+ ERR_FAIL_COND(!global_variables.instance_buffer_pos.has(p_instance));
+ int32_t pos = global_variables.instance_buffer_pos[p_instance];
+ if (pos >= 0) {
+ global_variables.buffer_usage[pos].elements = 0;
+ }
+ global_variables.instance_buffer_pos.erase(p_instance);
+}
+
+void MaterialStorage::global_variables_instance_update(RID p_instance, int p_index, const Variant &p_value) {
+ if (!global_variables.instance_buffer_pos.has(p_instance)) {
+ return; //just not allocated, ignore
+ }
+ int32_t pos = global_variables.instance_buffer_pos[p_instance];
+
+ if (pos < 0) {
+ return; //again, not allocated, ignore
+ }
+ ERR_FAIL_INDEX(p_index, ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES);
+ ERR_FAIL_COND_MSG(p_value.get_type() > Variant::COLOR, "Unsupported variant type for instance parameter: " + Variant::get_type_name(p_value.get_type())); //anything greater not supported
+
+ ShaderLanguage::DataType datatype_from_value[Variant::COLOR + 1] = {
+ ShaderLanguage::TYPE_MAX, //nil
+ ShaderLanguage::TYPE_BOOL, //bool
+ ShaderLanguage::TYPE_INT, //int
+ ShaderLanguage::TYPE_FLOAT, //float
+ ShaderLanguage::TYPE_MAX, //string
+ ShaderLanguage::TYPE_VEC2, //vec2
+ ShaderLanguage::TYPE_IVEC2, //vec2i
+ ShaderLanguage::TYPE_VEC4, //rect2
+ ShaderLanguage::TYPE_IVEC4, //rect2i
+ ShaderLanguage::TYPE_VEC3, // vec3
+ ShaderLanguage::TYPE_IVEC3, //vec3i
+ ShaderLanguage::TYPE_MAX, //xform2d not supported here
+ ShaderLanguage::TYPE_VEC4, //plane
+ ShaderLanguage::TYPE_VEC4, //quat
+ ShaderLanguage::TYPE_MAX, //aabb not supported here
+ ShaderLanguage::TYPE_MAX, //basis not supported here
+ ShaderLanguage::TYPE_MAX, //xform not supported here
+ ShaderLanguage::TYPE_VEC4 //color
+ };
+
+ ShaderLanguage::DataType datatype = datatype_from_value[p_value.get_type()];
+
+ ERR_FAIL_COND_MSG(datatype == ShaderLanguage::TYPE_MAX, "Unsupported variant type for instance parameter: " + Variant::get_type_name(p_value.get_type())); //anything greater not supported
+
+ pos += p_index;
+
+ _fill_std140_variant_ubo_value(datatype, 0, p_value, (uint8_t *)&global_variables.buffer_values[pos], true); //instances always use linear color in this renderer
+ _global_variable_mark_buffer_dirty(pos, 1);
+}
+
+void MaterialStorage::_update_global_variables() {
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ if (global_variables.buffer_dirty_region_count > 0) {
+ uint32_t total_regions = global_variables.buffer_size / GlobalVariables::BUFFER_DIRTY_REGION_SIZE;
+ if (total_regions / global_variables.buffer_dirty_region_count <= 4) {
+ // 25% of regions dirty, just update all buffer
+ glBindBuffer(GL_UNIFORM_BUFFER, global_variables.buffer);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(GlobalVariables::Value) * global_variables.buffer_size, global_variables.buffer_values, GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_UNIFORM_BUFFER, 0);
+ memset(global_variables.buffer_dirty_regions, 0, sizeof(bool) * total_regions);
+ } else {
+ uint32_t region_byte_size = sizeof(GlobalVariables::Value) * GlobalVariables::BUFFER_DIRTY_REGION_SIZE;
+ glBindBuffer(GL_UNIFORM_BUFFER, global_variables.buffer);
+ for (uint32_t i = 0; i < total_regions; i++) {
+ if (global_variables.buffer_dirty_regions[i]) {
+ glBufferSubData(GL_UNIFORM_BUFFER, i * region_byte_size, region_byte_size, &global_variables.buffer_values[i * GlobalVariables::BUFFER_DIRTY_REGION_SIZE]);
+ global_variables.buffer_dirty_regions[i] = false;
}
- */
}
+ glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
+
+ global_variables.buffer_dirty_region_count = 0;
}
- // uniforms and other things will be set in the use_material method in ShaderGLES3
+ if (global_variables.must_update_buffer_materials) {
+ // only happens in the case of a buffer variable added or removed,
+ // so not often.
+ for (const RID &E : global_variables.materials_using_buffer) {
+ Material *material = material_storage->get_material(E);
+ ERR_CONTINUE(!material); //wtf
- if (p_material->shader && p_material->shader->texture_uniforms.size() > 0) {
- p_material->textures.resize(p_material->shader->texture_uniforms.size());
+ material_storage->_material_queue_update(material, true, false);
+ }
- for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = p_material->shader->uniforms.front(); E; E = E->next()) {
- if (E->get().texture_order < 0) {
- continue; // not a texture, does not go here
- }
+ global_variables.must_update_buffer_materials = false;
+ }
+
+ if (global_variables.must_update_texture_materials) {
+ // only happens in the case of a buffer variable added or removed,
+ // so not often.
+ for (const RID &E : global_variables.materials_using_texture) {
+ Material *material = material_storage->get_material(E);
+ ERR_CONTINUE(!material); //wtf
- RID texture;
+ material_storage->_material_queue_update(material, false, true);
+ }
- Map<StringName, Variant>::Element *V = p_material->params.find(E->key());
+ global_variables.must_update_texture_materials = false;
+ }
+}
- if (V) {
- texture = V->get();
+/* SHADER API */
+
+RID MaterialStorage::shader_allocate() {
+ return shader_owner.allocate_rid();
+}
+
+void MaterialStorage::shader_initialize(RID p_rid) {
+ Shader shader;
+ shader.data = nullptr;
+ shader.mode = RS::SHADER_MAX;
+
+ shader_owner.initialize_rid(p_rid, shader);
+}
+
+void MaterialStorage::shader_free(RID p_rid) {
+ GLES3::Shader *shader = shader_owner.get_or_null(p_rid);
+ ERR_FAIL_COND(!shader);
+
+ //make material unreference this
+ while (shader->owners.size()) {
+ material_set_shader(shader->owners.front()->get()->self, RID());
+ }
+
+ //clear data if exists
+ if (shader->data) {
+ memdelete(shader->data);
+ }
+ shader_owner.free(p_rid);
+}
+
+void MaterialStorage::shader_set_code(RID p_shader, const String &p_code) {
+ GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND(!shader);
+
+ shader->code = p_code;
+
+ String mode_string = ShaderLanguage::get_shader_type(p_code);
+
+ RS::ShaderMode new_mode;
+ if (mode_string == "canvas_item") {
+ new_mode = RS::SHADER_CANVAS_ITEM;
+ //} else if (mode_string == "particles") {
+ // new_mode = RS::SHADER_PARTICLES;
+ } else if (mode_string == "spatial") {
+ new_mode = RS::SHADER_SPATIAL;
+ } else if (mode_string == "sky") {
+ new_mode = RS::SHADER_SKY;
+ //} else if (mode_string == "fog") {
+ // new_mode = RS::SHADER_FOG;
+ } else {
+ new_mode = RS::SHADER_MAX;
+ ERR_PRINT("shader type " + mode_string + " not supported in OpenGL renderer");
+ }
+
+ if (new_mode != shader->mode) {
+ if (shader->data) {
+ memdelete(shader->data);
+ shader->data = nullptr;
+ }
+
+ for (Set<Material *>::Element *E = shader->owners.front(); E; E = E->next()) {
+ Material *material = E->get();
+ material->shader_mode = new_mode;
+ if (material->data) {
+ memdelete(material->data);
+ material->data = nullptr;
}
+ }
- if (!texture.is_valid()) {
- Map<StringName, Map<int, RID>>::Element *W = p_material->shader->default_textures.find(E->key());
+ shader->mode = new_mode;
- // TODO: make texture uniform array properly works with GLES3
- if (W && W->get().has(0)) {
- texture = W->get()[0];
+ if (new_mode < RS::SHADER_MAX && shader_data_request_func[new_mode]) {
+ shader->data = shader_data_request_func[new_mode]();
+ } else {
+ shader->mode = RS::SHADER_MAX; //invalid
+ }
+
+ for (Set<Material *>::Element *E = shader->owners.front(); E; E = E->next()) {
+ Material *material = E->get();
+ if (shader->data) {
+ material->data = material_data_request_func[new_mode](shader->data);
+ material->data->self = material->self;
+ material->data->set_next_pass(material->next_pass);
+ material->data->set_render_priority(material->priority);
+ }
+ material->shader_mode = new_mode;
+ }
+
+ if (shader->data) {
+ for (const KeyValue<StringName, Map<int, RID>> &E : shader->default_texture_parameter) {
+ for (const KeyValue<int, RID> &E2 : E.value) {
+ shader->data->set_default_texture_param(E.key, E2.value, E2.key);
}
}
+ }
+ }
+
+ if (shader->data) {
+ shader->data->set_code(p_code);
+ }
+
+ for (Set<Material *>::Element *E = shader->owners.front(); E; E = E->next()) {
+ Material *material = E->get();
+ material->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL);
+ _material_queue_update(material, true, true);
+ }
+}
+
+String MaterialStorage::shader_get_code(RID p_shader) const {
+ const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND_V(!shader, String());
+ return shader->code;
+}
+
+void MaterialStorage::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
+ GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND(!shader);
+ if (shader->data) {
+ return shader->data->get_param_list(p_param_list);
+ }
+}
- p_material->textures.write[E->get().texture_order] = Pair<StringName, RID>(E->key(), texture);
+void MaterialStorage::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture, int p_index) {
+ GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND(!shader);
+
+ if (p_texture.is_valid() && TextureStorage::get_singleton()->owns_texture(p_texture)) {
+ if (!shader->default_texture_parameter.has(p_name)) {
+ shader->default_texture_parameter[p_name] = Map<int, RID>();
}
+ shader->default_texture_parameter[p_name][p_index] = p_texture;
} else {
- p_material->textures.clear();
+ if (shader->default_texture_parameter.has(p_name) && shader->default_texture_parameter[p_name].has(p_index)) {
+ shader->default_texture_parameter[p_name].erase(p_index);
+
+ if (shader->default_texture_parameter[p_name].is_empty()) {
+ shader->default_texture_parameter.erase(p_name);
+ }
+ }
+ }
+ if (shader->data) {
+ shader->data->set_default_texture_param(p_name, p_texture, p_index);
+ }
+ for (Set<Material *>::Element *E = shader->owners.front(); E; E = E->next()) {
+ Material *material = E->get();
+ _material_queue_update(material, false, true);
}
}
-RID MaterialStorage::material_allocate() {
- GLES3::Material *material = memnew(GLES3::Material);
- return material_owner.make_rid(material);
+RID MaterialStorage::shader_get_default_texture_param(RID p_shader, const StringName &p_name, int p_index) const {
+ const GLES3::Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND_V(!shader, RID());
+ if (shader->default_texture_parameter.has(p_name) && shader->default_texture_parameter[p_name].has(p_index)) {
+ return shader->default_texture_parameter[p_name][p_index];
+ }
+
+ return RID();
}
-void MaterialStorage::material_initialize(RID p_rid) {
+Variant MaterialStorage::shader_get_param_default(RID p_shader, const StringName &p_param) const {
+ Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND_V(!shader, Variant());
+ if (shader->data) {
+ return shader->data->get_default_parameter(p_param);
+ }
+ return Variant();
}
-//RID MaterialStorage::material_create() {
-// Material *material = memnew(Material);
+RS::ShaderNativeSourceCode MaterialStorage::shader_get_native_source_code(RID p_shader) const {
+ Shader *shader = shader_owner.get_or_null(p_shader);
+ ERR_FAIL_COND_V(!shader, RS::ShaderNativeSourceCode());
+ if (shader->data) {
+ return shader->data->get_native_source_code();
+ }
+ return RS::ShaderNativeSourceCode();
+}
-// return material_owner.make_rid(material);
-//}
+/* MATERIAL API */
-void MaterialStorage::material_free(RID p_rid) {
- GLES3::Material *m = material_owner.get_or_null(p_rid);
+void MaterialStorage::_material_queue_update(Material *material, bool p_uniform, bool p_texture) {
+ material->uniform_dirty = material->uniform_dirty || p_uniform;
+ material->texture_dirty = material->texture_dirty || p_texture;
- if (m->shader) {
- m->shader->materials.remove(&m->list);
+ if (material->update_element.in_list()) {
+ return;
}
- /*
- for (Map<Geometry *, int>::Element *E = m->geometry_owners.front(); E; E = E->next()) {
- Geometry *g = E->key();
- g->material = RID();
- }
+ material_update_list.add(&material->update_element);
+}
- for (Map<InstanceBaseDependency *, int>::Element *E = m->instance_owners.front(); E; E = E->next()) {
- InstanceBaseDependency *ins = E->key();
+void MaterialStorage::_update_queued_materials() {
+ while (material_update_list.first()) {
+ Material *material = material_update_list.first()->self();
- if (ins->material_override == p_rid) {
- ins->material_override = RID();
+ if (material->data) {
+ material->data->update_parameters(material->params, material->uniform_dirty, material->texture_dirty);
}
+ material->texture_dirty = false;
+ material->uniform_dirty = false;
- for (int i = 0; i < ins->materials.size(); i++) {
- if (ins->materials[i] == p_rid) {
- ins->materials.write[i] = RID();
- }
- }
+ material_update_list.remove(&material->update_element);
}
-*/
+}
+
+RID MaterialStorage::material_allocate() {
+ return material_owner.allocate_rid();
+}
+
+void MaterialStorage::material_initialize(RID p_rid) {
+ material_owner.initialize_rid(p_rid);
+ Material *material = material_owner.get_or_null(p_rid);
+ material->self = p_rid;
+}
+
+void MaterialStorage::material_free(RID p_rid) {
+ Material *material = material_owner.get_or_null(p_rid);
+ ERR_FAIL_COND(!material);
+
+ material_set_shader(p_rid, RID()); //clean up shader
+ material->dependency.deleted_notify(p_rid);
material_owner.free(p_rid);
- memdelete(m);
}
void MaterialStorage::material_set_shader(RID p_material, RID p_shader) {
GLES3::Material *material = material_owner.get_or_null(p_material);
ERR_FAIL_COND(!material);
- GLES3::Shader *shader = get_shader(p_shader);
+ if (material->data) {
+ memdelete(material->data);
+ material->data = nullptr;
+ }
if (material->shader) {
- // if a shader is present, remove the old shader
- material->shader->materials.remove(&material->list);
+ material->shader->owners.erase(material);
+ material->shader = nullptr;
+ material->shader_mode = RS::SHADER_MAX;
}
+ if (p_shader.is_null()) {
+ material->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL);
+ material->shader_id = 0;
+ return;
+ }
+
+ Shader *shader = get_shader(p_shader);
+ ERR_FAIL_COND(!shader);
material->shader = shader;
+ material->shader_mode = shader->mode;
+ material->shader_id = p_shader.get_local_index();
+ shader->owners.insert(material);
- if (shader) {
- shader->materials.add(&material->list);
+ if (shader->mode == RS::SHADER_MAX) {
+ return;
}
- _material_make_dirty(material);
+ ERR_FAIL_COND(shader->data == nullptr);
+
+ material->data = material_data_request_func[shader->mode](shader->data);
+ material->data->self = p_material;
+ material->data->set_next_pass(material->next_pass);
+ material->data->set_render_priority(material->priority);
+ //updating happens later
+ material->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL);
+ _material_queue_update(material, true, true);
}
void MaterialStorage::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
@@ -718,28 +2608,42 @@ void MaterialStorage::material_set_param(RID p_material, const StringName &p_par
if (p_value.get_type() == Variant::NIL) {
material->params.erase(p_param);
} else {
+ ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT); //object not allowed
material->params[p_param] = p_value;
}
- _material_make_dirty(material);
+ if (material->shader && material->shader->data) { //shader is valid
+ bool is_texture = material->shader->data->is_param_texture(p_param);
+ _material_queue_update(material, !is_texture, is_texture);
+ } else {
+ _material_queue_update(material, true, true);
+ }
}
Variant MaterialStorage::material_get_param(RID p_material, const StringName &p_param) const {
const GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, RID());
-
+ ERR_FAIL_COND_V(!material, Variant());
if (material->params.has(p_param)) {
return material->params[p_param];
+ } else {
+ return Variant();
}
-
- return material_get_param_default(p_material, p_param);
}
void MaterialStorage::material_set_next_pass(RID p_material, RID p_next_material) {
GLES3::Material *material = material_owner.get_or_null(p_material);
ERR_FAIL_COND(!material);
+ if (material->next_pass == p_next_material) {
+ return;
+ }
+
material->next_pass = p_next_material;
+ if (material->data) {
+ material->data->set_next_pass(p_next_material);
+ }
+
+ material->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL);
}
void MaterialStorage::material_set_render_priority(RID p_material, int priority) {
@@ -748,167 +2652,300 @@ void MaterialStorage::material_set_render_priority(RID p_material, int priority)
GLES3::Material *material = material_owner.get_or_null(p_material);
ERR_FAIL_COND(!material);
-
- material->render_priority = priority;
+ material->priority = priority;
+ if (material->data) {
+ material->data->set_render_priority(priority);
+ }
}
bool MaterialStorage::material_is_animated(RID p_material) {
GLES3::Material *material = material_owner.get_or_null(p_material);
ERR_FAIL_COND_V(!material, false);
- if (material->dirty_list.in_list()) {
- _update_material(material);
- }
-
- bool animated = material->is_animated_cache;
- if (!animated && material->next_pass.is_valid()) {
- animated = material_is_animated(material->next_pass);
+ if (material->shader && material->shader->data) {
+ if (material->shader->data->is_animated()) {
+ return true;
+ } else if (material->next_pass.is_valid()) {
+ return material_is_animated(material->next_pass);
+ }
}
- return animated;
+ return false; //by default nothing is animated
}
bool MaterialStorage::material_casts_shadows(RID p_material) {
GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, false);
- if (material->dirty_list.in_list()) {
- _update_material(material);
- }
-
- bool casts_shadows = material->can_cast_shadow_cache;
-
- if (!casts_shadows && material->next_pass.is_valid()) {
- casts_shadows = material_casts_shadows(material->next_pass);
+ ERR_FAIL_COND_V(!material, true);
+ if (material->shader && material->shader->data) {
+ if (material->shader->data->casts_shadows()) {
+ return true;
+ } else if (material->next_pass.is_valid()) {
+ return material_casts_shadows(material->next_pass);
+ }
}
-
- return casts_shadows;
+ return true; //by default everything casts shadows
}
-Variant MaterialStorage::material_get_param_default(RID p_material, const StringName &p_param) const {
- const GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, Variant());
+void MaterialStorage::material_get_instance_shader_parameters(RID p_material, List<InstanceShaderParam> *r_parameters) {
+ GLES3::Material *material = material_owner.get_or_null(p_material);
+ ERR_FAIL_COND(!material);
+ if (material->shader && material->shader->data) {
+ material->shader->data->get_instance_param_list(r_parameters);
- if (material->shader) {
- if (material->shader->uniforms.has(p_param)) {
- ShaderLanguage::ShaderNode::Uniform uniform = material->shader->uniforms[p_param];
- Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
- return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
+ if (material->next_pass.is_valid()) {
+ material_get_instance_shader_parameters(material->next_pass, r_parameters);
}
}
- return Variant();
}
-void MaterialStorage::update_dirty_materials() {
- while (_material_dirty_list.first()) {
- GLES3::Material *material = _material_dirty_list.first()->self();
- _update_material(material);
+void MaterialStorage::material_update_dependency(RID p_material, RendererStorage::DependencyTracker *p_instance) {
+ Material *material = material_owner.get_or_null(p_material);
+ ERR_FAIL_COND(!material);
+ p_instance->update_dependency(&material->dependency);
+ if (material->next_pass.is_valid()) {
+ material_update_dependency(material->next_pass, p_instance);
}
}
-/* are these still used? */
-RID MaterialStorage::material_get_shader(RID p_material) const {
- const GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, RID());
+// Canvas Shader Data
+void CanvasShaderData::set_code(const String &p_code) {
+ // compile the shader
- if (material->shader) {
- return material->shader->self;
+ code = p_code;
+ valid = false;
+ ubo_size = 0;
+ uniforms.clear();
+ uses_screen_texture = false;
+ uses_sdf = false;
+ uses_time = false;
+
+ if (code.is_empty()) {
+ return; //just invalid, but no error
}
- return RID();
-}
+ ShaderCompiler::GeneratedCode gen_code;
-void MaterialStorage::material_set_line_width(RID p_material, float p_width) {
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND(!material);
+ int blend_mode = BLEND_MODE_MIX;
+ uses_screen_texture = false;
- material->line_width = p_width;
-}
+ ShaderCompiler::IdentifierActions actions;
+ actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
+ actions.entry_point_stages["fragment"] = ShaderCompiler::STAGE_FRAGMENT;
+ actions.entry_point_stages["light"] = ShaderCompiler::STAGE_FRAGMENT;
-bool MaterialStorage::material_uses_tangents(RID p_material) {
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, false);
+ actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_mode, BLEND_MODE_ADD);
+ actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MIX);
+ actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_mode, BLEND_MODE_SUB);
+ actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MUL);
+ actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_mode, BLEND_MODE_PMALPHA);
+ actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_mode, BLEND_MODE_DISABLED);
- if (!material->shader) {
- return false;
+ actions.usage_flag_pointers["SCREEN_TEXTURE"] = &uses_screen_texture;
+ actions.usage_flag_pointers["texture_sdf"] = &uses_sdf;
+ actions.usage_flag_pointers["TIME"] = &uses_time;
+
+ actions.uniforms = &uniforms;
+ Error err = MaterialStorage::get_singleton()->shaders.compiler_canvas.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
+ ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
+
+ if (version.is_null()) {
+ version = MaterialStorage::get_singleton()->shaders.canvas_shader.version_create();
}
- if (material->shader->dirty_list.in_list()) {
- _update_shader(material->shader);
+#if 0
+ print_line("**compiling shader:");
+ print_line("**defines:\n");
+ for (int i = 0; i < gen_code.defines.size(); i++) {
+ print_line(gen_code.defines[i]);
}
+ print_line("\n**uniforms:\n" + gen_code.uniforms);
+ print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
+ print_line("\n**vertex_code:\n" + gen_code.vertex);
+ print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
+ print_line("\n**fragment_code:\n" + gen_code.fragment);
+ print_line("\n**light_code:\n" + gen_code.light);
+#endif
- return material->shader->spatial.uses_tangent;
+ Vector<StringName> texture_uniform_names;
+ for (int i = 0; i < gen_code.texture_uniforms.size(); i++) {
+ texture_uniform_names.push_back(gen_code.texture_uniforms[i].name);
+ }
+
+ MaterialStorage::get_singleton()->shaders.canvas_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines, texture_uniform_names);
+ ERR_FAIL_COND(!MaterialStorage::get_singleton()->shaders.canvas_shader.version_is_valid(version));
+
+ ubo_size = gen_code.uniform_total_size;
+ ubo_offsets = gen_code.uniform_offsets;
+ texture_uniforms = gen_code.texture_uniforms;
+
+ valid = true;
}
-bool MaterialStorage::material_uses_ensure_correct_normals(RID p_material) {
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND_V(!material, false);
+void CanvasShaderData::set_default_texture_param(const StringName &p_name, RID p_texture, int p_index) {
+ if (!p_texture.is_valid()) {
+ if (default_texture_params.has(p_name) && default_texture_params[p_name].has(p_index)) {
+ default_texture_params[p_name].erase(p_index);
- if (!material->shader) {
- return false;
+ if (default_texture_params[p_name].is_empty()) {
+ default_texture_params.erase(p_name);
+ }
+ }
+ } else {
+ if (!default_texture_params.has(p_name)) {
+ default_texture_params[p_name] = Map<int, RID>();
+ }
+ default_texture_params[p_name][p_index] = p_texture;
}
+}
+
+void CanvasShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
+ Map<int, StringName> order;
- if (material->shader->dirty_list.in_list()) {
- _update_shader(material->shader);
+ for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
+ continue;
+ }
+ if (E.value.texture_order >= 0) {
+ order[E.value.texture_order + 100000] = E.key;
+ } else {
+ order[E.value.order] = E.key;
+ }
}
- return material->shader->spatial.uses_ensure_correct_normals;
+ for (const KeyValue<int, StringName> &E : order) {
+ PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E.value]);
+ pi.name = E.value;
+ p_param_list->push_back(pi);
+ }
}
-void MaterialStorage::material_add_instance_owner(RID p_material, RendererStorage::DependencyTracker *p_instance) {
- /*
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND(!material);
+void CanvasShaderData::get_instance_param_list(List<RendererMaterialStorage::InstanceShaderParam> *p_param_list) const {
+ for (const KeyValue<StringName, ShaderLanguage::ShaderNode::Uniform> &E : uniforms) {
+ if (E.value.scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
+ continue;
+ }
- Map<InstanceBaseDependency *, int>::Element *E = material->instance_owners.find(p_instance);
- if (E) {
- E->get()++;
- } else {
- material->instance_owners[p_instance] = 1;
+ RendererMaterialStorage::InstanceShaderParam p;
+ p.info = ShaderLanguage::uniform_to_property_info(E.value);
+ p.info.name = E.key; //supply name
+ p.index = E.value.instance_index;
+ p.default_value = ShaderLanguage::constant_value_to_variant(E.value.default_value, E.value.type, E.value.array_size, E.value.hint);
+ p_param_list->push_back(p);
}
-*/
}
-void MaterialStorage::material_remove_instance_owner(RID p_material, RendererStorage::DependencyTracker *p_instance) {
- /*
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND(!material);
+bool CanvasShaderData::is_param_texture(const StringName &p_param) const {
+ if (!uniforms.has(p_param)) {
+ return false;
+ }
- Map<InstanceBaseDependency *, int>::Element *E = material->instance_owners.find(p_instance);
- ERR_FAIL_COND(!E);
+ return uniforms[p_param].texture_order >= 0;
+}
- E->get()--;
+bool CanvasShaderData::is_animated() const {
+ return false;
+}
+
+bool CanvasShaderData::casts_shadows() const {
+ return false;
+}
- if (E->get() == 0) {
- material->instance_owners.erase(E);
+Variant CanvasShaderData::get_default_parameter(const StringName &p_parameter) const {
+ if (uniforms.has(p_parameter)) {
+ ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
+ Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
+ return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.array_size, uniform.hint);
}
-*/
+ return Variant();
}
-/*
-void MaterialStorage::_material_add_geometry(RID p_material, Geometry *p_geometry) {
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND(!material);
+RS::ShaderNativeSourceCode CanvasShaderData::get_native_source_code() const {
+ return MaterialStorage::get_singleton()->shaders.canvas_shader.version_get_native_source_code(version);
+}
- Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
+CanvasShaderData::CanvasShaderData() {
+ valid = false;
+ uses_screen_texture = false;
+ uses_sdf = false;
+}
- if (I) {
- I->get()++;
- } else {
- material->geometry_owners[p_geometry] = 1;
+CanvasShaderData::~CanvasShaderData() {
+ if (version.is_valid()) {
+ MaterialStorage::get_singleton()->shaders.canvas_shader.version_free(version);
}
}
-void MaterialStorage::_material_remove_geometry(RID p_material, Geometry *p_geometry) {
- GLES3::Material *material = material_owner.get_or_null(p_material);
- ERR_FAIL_COND(!material);
-
- Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
- ERR_FAIL_COND(!I);
+GLES3::ShaderData *GLES3::_create_canvas_shader_func() {
+ CanvasShaderData *shader_data = memnew(CanvasShaderData);
+ return shader_data;
+}
- I->get()--;
+void CanvasMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
+ return update_parameters_internal(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size);
+}
- if (I->get() == 0) {
- material->geometry_owners.erase(I);
+// Look up table to translate ShaderLanguage::DataType to GL_TEXTURE_*
+static const GLenum target_from_type[ShaderLanguage::TYPE_MAX] = {
+ GL_TEXTURE_2D, // TYPE_VOID,
+ GL_TEXTURE_2D, // TYPE_BOOL,
+ GL_TEXTURE_2D, // TYPE_BVEC2,
+ GL_TEXTURE_2D, // TYPE_BVEC3,
+ GL_TEXTURE_2D, // TYPE_BVEC4,
+ GL_TEXTURE_2D, // TYPE_INT,
+ GL_TEXTURE_2D, // TYPE_IVEC2,
+ GL_TEXTURE_2D, // TYPE_IVEC3,
+ GL_TEXTURE_2D, // TYPE_IVEC4,
+ GL_TEXTURE_2D, // TYPE_UINT,
+ GL_TEXTURE_2D, // TYPE_UVEC2,
+ GL_TEXTURE_2D, // TYPE_UVEC3,
+ GL_TEXTURE_2D, // TYPE_UVEC4,
+ GL_TEXTURE_2D, // TYPE_FLOAT,
+ GL_TEXTURE_2D, // TYPE_VEC2,
+ GL_TEXTURE_2D, // TYPE_VEC3,
+ GL_TEXTURE_2D, // TYPE_VEC4,
+ GL_TEXTURE_2D, // TYPE_MAT2,
+ GL_TEXTURE_2D, // TYPE_MAT3,
+ GL_TEXTURE_2D, // TYPE_MAT4,
+ GL_TEXTURE_2D, // TYPE_SAMPLER2D,
+ GL_TEXTURE_2D, // TYPE_ISAMPLER2D,
+ GL_TEXTURE_2D, // TYPE_USAMPLER2D,
+ GL_TEXTURE_2D_ARRAY, // TYPE_SAMPLER2DARRAY,
+ GL_TEXTURE_2D_ARRAY, // TYPE_ISAMPLER2DARRAY,
+ GL_TEXTURE_2D_ARRAY, // TYPE_USAMPLER2DARRAY,
+ GL_TEXTURE_3D, // TYPE_SAMPLER3D,
+ GL_TEXTURE_3D, // TYPE_ISAMPLER3D,
+ GL_TEXTURE_3D, // TYPE_USAMPLER3D,
+ GL_TEXTURE_CUBE_MAP, // TYPE_SAMPLERCUBE,
+ GL_TEXTURE_CUBE_MAP, // TYPE_SAMPLERCUBEARRAY,
+ GL_TEXTURE_2D, // TYPE_STRUCT
+};
+
+void CanvasMaterialData::bind_uniforms() {
+ // Bind Material Uniforms
+ glBindBufferBase(GL_UNIFORM_BUFFER, RasterizerCanvasGLES3::MATERIAL_UNIFORM_BUFFER_OBJECT, uniform_buffer);
+
+ RID *textures = texture_cache.ptrw();
+ ShaderCompiler::GeneratedCode::Texture *texture_uniforms = shader_data->texture_uniforms.ptrw();
+ for (int ti = 0; ti < texture_cache.size(); ti++) {
+ Texture *texture = TextureStorage::get_singleton()->get_texture(textures[ti]);
+ glActiveTexture(GL_TEXTURE1 + ti);
+ glBindTexture(target_from_type[texture_uniforms[ti].type], texture->tex_id);
+
+ // Set sampler state here as the same texture can be used in multiple places with different flags
+ // Need to convert sampler state from ShaderLanguage::Texture* to RS::CanvasItemTexture*
+ RS::CanvasItemTextureFilter filter = RS::CanvasItemTextureFilter((int(texture_uniforms[ti].filter) + 1) % RS::CANVAS_ITEM_TEXTURE_FILTER_MAX);
+ RS::CanvasItemTextureRepeat repeat = RS::CanvasItemTextureRepeat((int(texture_uniforms[ti].repeat) + 1) % RS::CANVAS_ITEM_TEXTURE_REPEAT_MIRROR);
+ texture->gl_set_filter(filter);
+ texture->gl_set_repeat(repeat);
}
}
-*/
+
+CanvasMaterialData::~CanvasMaterialData() {
+}
+
+GLES3::MaterialData *GLES3::_create_canvas_material_func(ShaderData *p_shader) {
+ CanvasMaterialData *material_data = memnew(CanvasMaterialData);
+ material_data->shader_data = static_cast<CanvasShaderData *>(p_shader);
+ //update will happen later anyway so do nothing.
+ return material_data;
+}
#endif // !GLES3_ENABLED
diff --git a/drivers/gles3/storage/material_storage.h b/drivers/gles3/storage/material_storage.h
index 450ee7191f..cc6cbdc152 100644
--- a/drivers/gles3/storage/material_storage.h
+++ b/drivers/gles3/storage/material_storage.h
@@ -44,193 +44,246 @@
#include "drivers/gles3/shaders/copy.glsl.gen.h"
+#include "../shaders/canvas.glsl.gen.h"
+#include "../shaders/sky.glsl.gen.h"
+
namespace GLES3 {
/* SHADER Structs */
struct Shaders {
- ShaderCompiler compiler;
+ CanvasShaderGLES3 canvas_shader;
+ SkyShaderGLES3 sky_shader;
+
+ ShaderCompiler compiler_canvas;
+ ShaderCompiler compiler_scene;
+ ShaderCompiler compiler_particles;
+ ShaderCompiler compiler_sky;
+};
+
+struct ShaderData {
+ virtual void set_code(const String &p_Code) = 0;
+ virtual void set_default_texture_param(const StringName &p_name, RID p_texture, int p_index) = 0;
+ virtual void get_param_list(List<PropertyInfo> *p_param_list) const = 0;
- CopyShaderGLES3 copy;
- RID copy_version;
- //CubemapFilterShaderGLES3 cubemap_filter;
+ virtual void get_instance_param_list(List<RendererMaterialStorage::InstanceShaderParam> *p_param_list) const = 0;
+ virtual bool is_param_texture(const StringName &p_param) const = 0;
+ virtual bool is_animated() const = 0;
+ virtual bool casts_shadows() const = 0;
+ virtual Variant get_default_parameter(const StringName &p_parameter) const = 0;
+ virtual RS::ShaderNativeSourceCode get_native_source_code() const { return RS::ShaderNativeSourceCode(); }
- ShaderCompiler::IdentifierActions actions_canvas;
- ShaderCompiler::IdentifierActions actions_scene;
- ShaderCompiler::IdentifierActions actions_particles;
+ virtual ~ShaderData() {}
};
+typedef ShaderData *(*ShaderDataRequestFunction)();
+
struct Material;
struct Shader {
- RID self;
-
- RS::ShaderMode mode;
- ShaderGLES3 *shader = nullptr;
+ ShaderData *data = nullptr;
String code;
- SelfList<Material>::List materials;
-
- Map<StringName, ShaderLanguage::ShaderNode::Uniform> uniforms;
+ RS::ShaderMode mode;
+ Map<StringName, Map<int, RID>> default_texture_parameter;
+ Set<Material *> owners;
+};
- RID version;
+/* Material structs */
- SelfList<Shader> dirty_list;
+struct MaterialData {
+ void update_uniform_buffer(const Map<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const Map<StringName, Variant> &p_parameters, uint8_t *p_buffer, uint32_t p_buffer_size, bool p_use_linear_color);
+ void update_textures(const Map<StringName, Variant> &p_parameters, const Map<StringName, Map<int, RID>> &p_default_textures, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, RID *p_textures, bool p_use_linear_color);
- Map<StringName, Map<int, RID>> default_textures;
+ virtual void set_render_priority(int p_priority) = 0;
+ virtual void set_next_pass(RID p_pass) = 0;
+ virtual void update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) = 0;
+ virtual void bind_uniforms() = 0;
+ virtual ~MaterialData();
- Vector<ShaderCompiler::GeneratedCode::Texture> texture_uniforms;
+ // Used internally by all Materials
+ void update_parameters_internal(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty, const Map<StringName, ShaderLanguage::ShaderNode::Uniform> &p_uniforms, const uint32_t *p_uniform_offsets, const Vector<ShaderCompiler::GeneratedCode::Texture> &p_texture_uniforms, const Map<StringName, Map<int, RID>> &p_default_texture_params, uint32_t p_ubo_size);
- bool valid;
+protected:
+ Vector<uint8_t> ubo_data;
+ GLuint uniform_buffer = GLuint(0);
+ Vector<RID> texture_cache;
- String path;
+private:
+ friend class MaterialStorage;
+ RID self;
+ List<RID>::Element *global_buffer_E = nullptr;
+ List<RID>::Element *global_texture_E = nullptr;
+ uint64_t global_textures_pass = 0;
+ Map<StringName, uint64_t> used_global_textures;
- uint32_t index;
- uint64_t last_pass;
-
- struct CanvasItem {
- enum BlendMode {
- BLEND_MODE_MIX,
- BLEND_MODE_ADD,
- BLEND_MODE_SUB,
- BLEND_MODE_MUL,
- BLEND_MODE_PMALPHA,
- };
-
- int blend_mode;
-
- enum LightMode {
- LIGHT_MODE_NORMAL,
- LIGHT_MODE_UNSHADED,
- LIGHT_MODE_LIGHT_ONLY
- };
-
- int light_mode;
-
- bool uses_screen_texture;
- bool uses_screen_uv;
- bool uses_time;
- bool uses_modulate;
- bool uses_color;
- bool uses_vertex;
-
- // all these should disable item joining if used in a custom shader
- bool uses_model_matrix;
- bool uses_extra_matrix;
- bool uses_projection_matrix;
- bool uses_instance_custom;
-
- } canvas_item;
-
- struct Spatial {
- enum BlendMode {
- BLEND_MODE_MIX,
- BLEND_MODE_ADD,
- BLEND_MODE_SUB,
- BLEND_MODE_MUL,
- };
-
- int blend_mode;
-
- enum DepthDrawMode {
- DEPTH_DRAW_OPAQUE,
- DEPTH_DRAW_ALWAYS,
- DEPTH_DRAW_NEVER,
- DEPTH_DRAW_ALPHA_PREPASS,
- };
-
- int depth_draw_mode;
-
- enum CullMode {
- CULL_MODE_FRONT,
- CULL_MODE_BACK,
- CULL_MODE_DISABLED,
- };
-
- int cull_mode;
-
- bool uses_alpha;
- bool uses_alpha_scissor;
- bool unshaded;
- bool no_depth_test;
- bool uses_vertex;
- bool uses_discard;
- bool uses_sss;
- bool uses_screen_texture;
- bool uses_depth_texture;
- bool uses_time;
- bool uses_tangent;
- bool uses_ensure_correct_normals;
- bool writes_modelview_or_projection;
- bool uses_vertex_lighting;
- bool uses_world_coordinates;
-
- } spatial;
-
- struct Particles {
- } particles;
-
- bool uses_vertex_time;
- bool uses_fragment_time;
-
- Shader() :
- dirty_list(this) {
- shader = nullptr;
- valid = false;
- version = RID();
- last_pass = 0;
- }
+ //internally by update_parameters_internal
};
-/* MATERIAL Structs */
+typedef MaterialData *(*MaterialDataRequestFunction)(ShaderData *);
struct Material {
RID self;
+ MaterialData *data = nullptr;
Shader *shader = nullptr;
+ //shortcut to shader data and type
+ RS::ShaderMode shader_mode = RS::SHADER_MAX;
+ uint32_t shader_id = 0;
+ bool uniform_dirty = false;
+ bool texture_dirty = false;
Map<StringName, Variant> params;
- SelfList<Material> list;
- SelfList<Material> dirty_list;
- Vector<Pair<StringName, RID>> textures;
- float line_width;
- int render_priority;
-
+ int32_t priority = 0;
RID next_pass;
+ SelfList<Material> update_element;
- uint32_t index;
- uint64_t last_pass;
+ RendererStorage::Dependency dependency;
- // Map<Geometry *, int> geometry_owners;
- // Map<InstanceBaseDependency *, int> instance_owners;
+ Material() :
+ update_element(this) {}
+};
- bool can_cast_shadow_cache;
- bool is_animated_cache;
+// CanvasItem Materials
- Material() :
- list(this),
- dirty_list(this) {
- can_cast_shadow_cache = false;
- is_animated_cache = false;
- shader = nullptr;
- line_width = 1.0;
- last_pass = 0;
- render_priority = 0;
- }
+struct CanvasShaderData : public ShaderData {
+ enum BlendMode { //used internally
+ BLEND_MODE_MIX,
+ BLEND_MODE_ADD,
+ BLEND_MODE_SUB,
+ BLEND_MODE_MUL,
+ BLEND_MODE_PMALPHA,
+ BLEND_MODE_DISABLED,
+ };
+
+ bool valid;
+ RID version;
+ //PipelineVariants pipeline_variants;
+ String path;
+
+ Map<StringName, ShaderLanguage::ShaderNode::Uniform> uniforms;
+ Vector<ShaderCompiler::GeneratedCode::Texture> texture_uniforms;
+
+ Vector<uint32_t> ubo_offsets;
+ uint32_t ubo_size;
+
+ String code;
+ Map<StringName, Map<int, RID>> default_texture_params;
+
+ bool uses_screen_texture = false;
+ bool uses_sdf = false;
+ bool uses_time = false;
+
+ virtual void set_code(const String &p_Code);
+ virtual void set_default_texture_param(const StringName &p_name, RID p_texture, int p_index);
+ virtual void get_param_list(List<PropertyInfo> *p_param_list) const;
+ virtual void get_instance_param_list(List<RendererMaterialStorage::InstanceShaderParam> *p_param_list) const;
+
+ virtual bool is_param_texture(const StringName &p_param) const;
+ virtual bool is_animated() const;
+ virtual bool casts_shadows() const;
+ virtual Variant get_default_parameter(const StringName &p_parameter) const;
+ virtual RS::ShaderNativeSourceCode get_native_source_code() const;
+
+ CanvasShaderData();
+ virtual ~CanvasShaderData();
+};
+
+ShaderData *_create_canvas_shader_func();
+
+struct CanvasMaterialData : public MaterialData {
+ CanvasShaderData *shader_data = nullptr;
+
+ virtual void set_render_priority(int p_priority) {}
+ virtual void set_next_pass(RID p_pass) {}
+ virtual void update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty);
+ virtual void bind_uniforms();
+ virtual ~CanvasMaterialData();
+};
+
+MaterialData *_create_canvas_material_func(ShaderData *p_shader);
+
+/* Global variable structs */
+struct GlobalVariables {
+ enum {
+ BUFFER_DIRTY_REGION_SIZE = 1024
+ };
+ struct Variable {
+ Set<RID> texture_materials; // materials using this
+
+ RS::GlobalVariableType type;
+ Variant value;
+ Variant override;
+ int32_t buffer_index; //for vectors
+ int32_t buffer_elements; //for vectors
+ };
+
+ HashMap<StringName, Variable> variables;
+
+ struct Value {
+ float x;
+ float y;
+ float z;
+ float w;
+ };
+
+ struct ValueInt {
+ int32_t x;
+ int32_t y;
+ int32_t z;
+ int32_t w;
+ };
+
+ struct ValueUInt {
+ uint32_t x;
+ uint32_t y;
+ uint32_t z;
+ uint32_t w;
+ };
+
+ struct ValueUsage {
+ uint32_t elements = 0;
+ };
+
+ List<RID> materials_using_buffer;
+ List<RID> materials_using_texture;
+
+ GLuint buffer = GLuint(0);
+ Value *buffer_values = nullptr;
+ ValueUsage *buffer_usage = nullptr;
+ bool *buffer_dirty_regions = nullptr;
+ uint32_t buffer_dirty_region_count = 0;
+
+ uint32_t buffer_size;
+
+ bool must_update_texture_materials = false;
+ bool must_update_buffer_materials = false;
+
+ HashMap<RID, int32_t> instance_buffer_pos;
};
class MaterialStorage : public RendererMaterialStorage {
private:
+ friend struct MaterialData;
static MaterialStorage *singleton;
- /* SHADER API */
+ /* GLOBAL VARIABLE API */
+
+ GlobalVariables global_variables;
+
+ int32_t _global_variable_allocate(uint32_t p_elements);
+ void _global_variable_store_in_buffer(int32_t p_index, RS::GlobalVariableType p_type, const Variant &p_value);
+ void _global_variable_mark_buffer_dirty(int32_t p_index, int32_t p_elements);
- mutable Shaders shaders;
+ /* SHADER API */
- mutable RID_PtrOwner<Shader> shader_owner;
- mutable SelfList<Shader>::List _shader_dirty_list;
+ ShaderDataRequestFunction shader_data_request_func[RS::SHADER_MAX];
+ mutable RID_Owner<Shader, true> shader_owner;
/* MATERIAL API */
+ MaterialDataRequestFunction material_data_request_func[RS::SHADER_MAX];
+ mutable RID_Owner<Material, true> material_owner;
+
+ SelfList<Material>::List material_update_list;
- mutable SelfList<Material>::List _material_dirty_list;
- mutable RID_PtrOwner<Material> material_owner;
+ //static void _material_uniform_set_erased(void *p_material);
public:
static MaterialStorage *get_singleton();
@@ -238,8 +291,12 @@ public:
MaterialStorage();
virtual ~MaterialStorage();
+ Shaders shaders;
+
/* GLOBAL VARIABLE API */
+ void _update_global_variables();
+
virtual void global_variable_add(const StringName &p_name, RS::GlobalVariableType p_type, const Variant &p_value) override;
virtual void global_variable_remove(const StringName &p_name) override;
virtual Vector<StringName> global_variable_get_list() const override;
@@ -248,6 +305,7 @@ public:
virtual void global_variable_set_override(const StringName &p_name, const Variant &p_value) override;
virtual Variant global_variable_get(const StringName &p_name) const override;
virtual RS::GlobalVariableType global_variable_get_type(const StringName &p_name) const override;
+ RS::GlobalVariableType global_variable_get_type_internal(const StringName &p_name) const;
virtual void global_variables_load_settings(bool p_load_textures = true) override;
virtual void global_variables_clear() override;
@@ -256,6 +314,8 @@ public:
virtual void global_variables_instance_free(RID p_instance) override;
virtual void global_variables_instance_update(RID p_instance, int p_index, const Variant &p_value) override;
+ GLuint global_variables_get_uniform_buffer() const;
+
/* SHADER API */
Shader *get_shader(RID p_rid) { return shader_owner.get_or_null(p_rid); };
@@ -267,68 +327,56 @@ public:
virtual void shader_initialize(RID p_rid) override;
virtual void shader_free(RID p_rid) override;
- //RID shader_create() override;
-
virtual void shader_set_code(RID p_shader, const String &p_code) override;
virtual String shader_get_code(RID p_shader) const override;
virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const override;
virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture, int p_index) override;
virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name, int p_index) const override;
+ virtual Variant shader_get_param_default(RID p_shader, const StringName &p_param) const override;
- virtual RS::ShaderNativeSourceCode shader_get_native_source_code(RID p_shader) const override { return RS::ShaderNativeSourceCode(); };
-
- void _update_shader(Shader *p_shader) const;
- void update_dirty_shaders();
-
- // new
- Variant shader_get_param_default(RID p_material, const StringName &p_param) const override { return Variant(); }
+ virtual RS::ShaderNativeSourceCode shader_get_native_source_code(RID p_shader) const override;
/* MATERIAL API */
Material *get_material(RID p_rid) { return material_owner.get_or_null(p_rid); };
bool owns_material(RID p_rid) { return material_owner.owns(p_rid); };
- void _material_make_dirty(Material *p_material) const;
+ void _material_queue_update(Material *material, bool p_uniform, bool p_texture);
+ void _update_queued_materials();
- // void _material_add_geometry(RID p_material, Geometry *p_geometry);
- // void _material_remove_geometry(RID p_material, Geometry *p_geometry);
-
- void _update_material(Material *p_material);
-
- // new
- virtual void material_get_instance_shader_parameters(RID p_material, List<InstanceShaderParam> *r_parameters) override {}
- virtual void material_update_dependency(RID p_material, RendererStorage::DependencyTracker *p_instance) override {}
-
- // old
virtual RID material_allocate() override;
virtual void material_initialize(RID p_rid) override;
-
virtual void material_free(RID p_rid) override;
- //RID material_create() override;
-
virtual void material_set_shader(RID p_material, RID p_shader) override;
- virtual RID material_get_shader(RID p_material) const;
virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) override;
virtual Variant material_get_param(RID p_material, const StringName &p_param) const override;
- virtual Variant material_get_param_default(RID p_material, const StringName &p_param) const;
- void material_set_line_width(RID p_material, float p_width);
virtual void material_set_next_pass(RID p_material, RID p_next_material) override;
+ virtual void material_set_render_priority(RID p_material, int priority) override;
virtual bool material_is_animated(RID p_material) override;
virtual bool material_casts_shadows(RID p_material) override;
- bool material_uses_tangents(RID p_material);
- bool material_uses_ensure_correct_normals(RID p_material);
- void material_add_instance_owner(RID p_material, RendererStorage::DependencyTracker *p_instance);
- void material_remove_instance_owner(RID p_material, RendererStorage::DependencyTracker *p_instance);
+ virtual void material_get_instance_shader_parameters(RID p_material, List<InstanceShaderParam> *r_parameters) override;
+
+ virtual void material_update_dependency(RID p_material, RendererStorage::DependencyTracker *p_instance) override;
- void material_set_render_priority(RID p_material, int priority) override;
+ _FORCE_INLINE_ uint32_t material_get_shader_id(RID p_material) {
+ Material *material = material_owner.get_or_null(p_material);
+ return material->shader_id;
+ }
- void update_dirty_materials();
+ _FORCE_INLINE_ MaterialData *material_get_data(RID p_material, RS::ShaderMode p_shader_mode) {
+ Material *material = material_owner.get_or_null(p_material);
+ if (!material || material->shader_mode != p_shader_mode) {
+ return nullptr;
+ } else {
+ return material->data;
+ }
+ }
};
} // namespace GLES3
diff --git a/drivers/gles3/storage/mesh_storage.cpp b/drivers/gles3/storage/mesh_storage.cpp
index c2a431aff1..934f746423 100644
--- a/drivers/gles3/storage/mesh_storage.cpp
+++ b/drivers/gles3/storage/mesh_storage.cpp
@@ -31,6 +31,7 @@
#ifdef GLES3_ENABLED
#include "mesh_storage.h"
+#include "material_storage.h"
using namespace GLES3;
@@ -51,34 +52,247 @@ MeshStorage::~MeshStorage() {
/* MESH API */
RID MeshStorage::mesh_allocate() {
- return RID();
+ return mesh_owner.allocate_rid();
}
void MeshStorage::mesh_initialize(RID p_rid) {
+ mesh_owner.initialize_rid(p_rid, Mesh());
}
void MeshStorage::mesh_free(RID p_rid) {
+ mesh_clear(p_rid);
+ mesh_set_shadow_mesh(p_rid, RID());
+ Mesh *mesh = mesh_owner.get_or_null(p_rid);
+ mesh->dependency.deleted_notify(p_rid);
+ if (mesh->instances.size()) {
+ ERR_PRINT("deleting mesh with active instances");
+ }
+ if (mesh->shadow_owners.size()) {
+ for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) {
+ Mesh *shadow_owner = E->get();
+ shadow_owner->shadow_mesh = RID();
+ shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+ }
+ }
+ mesh_owner.free(p_rid);
}
void MeshStorage::mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) {
+ ERR_FAIL_COND(p_blend_shape_count < 0);
+
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+
+ ERR_FAIL_COND(mesh->surface_count > 0); //surfaces already exist
+ WARN_PRINT_ONCE("blend shapes not supported by GLES3 renderer yet");
+ mesh->blend_shape_count = p_blend_shape_count;
}
bool MeshStorage::mesh_needs_instance(RID p_mesh, bool p_has_skeleton) {
- return false;
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, false);
+
+ return mesh->blend_shape_count > 0 || (mesh->has_bone_weights && p_has_skeleton);
}
void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+
+ ERR_FAIL_COND(mesh->surface_count == RS::MAX_MESH_SURFACES);
+
+#ifdef DEBUG_ENABLED
+ //do a validation, to catch errors first
+ {
+ uint32_t stride = 0;
+ uint32_t attrib_stride = 0;
+ uint32_t skin_stride = 0;
+
+ // TODO: I think this should be <=, but it is copied from RendererRD, will have to verify later
+ for (int i = 0; i < RS::ARRAY_WEIGHTS; i++) {
+ if ((p_surface.format & (1 << i))) {
+ switch (i) {
+ case RS::ARRAY_VERTEX: {
+ if (p_surface.format & RS::ARRAY_FLAG_USE_2D_VERTICES) {
+ stride += sizeof(float) * 2;
+ } else {
+ stride += sizeof(float) * 3;
+ }
+
+ } break;
+ case RS::ARRAY_NORMAL: {
+ stride += sizeof(int32_t);
+
+ } break;
+ case RS::ARRAY_TANGENT: {
+ stride += sizeof(int32_t);
+
+ } break;
+ case RS::ARRAY_COLOR: {
+ attrib_stride += sizeof(uint32_t);
+ } break;
+ case RS::ARRAY_TEX_UV: {
+ attrib_stride += sizeof(float) * 2;
+
+ } break;
+ case RS::ARRAY_TEX_UV2: {
+ attrib_stride += sizeof(float) * 2;
+
+ } break;
+ case RS::ARRAY_CUSTOM0:
+ case RS::ARRAY_CUSTOM1:
+ case RS::ARRAY_CUSTOM2:
+ case RS::ARRAY_CUSTOM3: {
+ int idx = i - RS::ARRAY_CUSTOM0;
+ uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
+ uint32_t fmt = (p_surface.format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK;
+ uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
+ attrib_stride += fmtsize[fmt];
+
+ } break;
+ case RS::ARRAY_WEIGHTS:
+ case RS::ARRAY_BONES: {
+ //uses a separate array
+ bool use_8 = p_surface.format & RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
+ skin_stride += sizeof(int16_t) * (use_8 ? 16 : 8);
+ } break;
+ }
+ }
+ }
+
+ int expected_size = stride * p_surface.vertex_count;
+ ERR_FAIL_COND_MSG(expected_size != p_surface.vertex_data.size(), "Size of vertex data provided (" + itos(p_surface.vertex_data.size()) + ") does not match expected (" + itos(expected_size) + ")");
+
+ int bs_expected_size = expected_size * mesh->blend_shape_count;
+
+ ERR_FAIL_COND_MSG(bs_expected_size != p_surface.blend_shape_data.size(), "Size of blend shape data provided (" + itos(p_surface.blend_shape_data.size()) + ") does not match expected (" + itos(bs_expected_size) + ")");
+
+ int expected_attrib_size = attrib_stride * p_surface.vertex_count;
+ ERR_FAIL_COND_MSG(expected_attrib_size != p_surface.attribute_data.size(), "Size of attribute data provided (" + itos(p_surface.attribute_data.size()) + ") does not match expected (" + itos(expected_attrib_size) + ")");
+
+ if ((p_surface.format & RS::ARRAY_FORMAT_WEIGHTS) && (p_surface.format & RS::ARRAY_FORMAT_BONES)) {
+ expected_size = skin_stride * p_surface.vertex_count;
+ ERR_FAIL_COND_MSG(expected_size != p_surface.skin_data.size(), "Size of skin data provided (" + itos(p_surface.skin_data.size()) + ") does not match expected (" + itos(expected_size) + ")");
+ }
+ }
+
+#endif
+
+ Mesh::Surface *s = memnew(Mesh::Surface);
+
+ s->format = p_surface.format;
+ s->primitive = p_surface.primitive;
+
+ glGenBuffers(1, &s->vertex_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, s->vertex_buffer);
+ glBufferData(GL_ARRAY_BUFFER, p_surface.vertex_data.size(), p_surface.vertex_data.ptr(), (s->format & RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
+ s->vertex_buffer_size = p_surface.vertex_data.size();
+
+ if (p_surface.attribute_data.size()) {
+ glGenBuffers(1, &s->attribute_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, s->attribute_buffer);
+ glBufferData(GL_ARRAY_BUFFER, p_surface.attribute_data.size(), p_surface.attribute_data.ptr(), (s->format & RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
+ }
+ if (p_surface.skin_data.size()) {
+ glGenBuffers(1, &s->skin_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, s->skin_buffer);
+ glBufferData(GL_ARRAY_BUFFER, p_surface.skin_data.size(), p_surface.skin_data.ptr(), (s->format & RS::ARRAY_FLAG_USE_DYNAMIC_UPDATE) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
+ s->skin_buffer_size = p_surface.skin_data.size();
+ }
+
+ s->vertex_count = p_surface.vertex_count;
+
+ if (p_surface.format & RS::ARRAY_FORMAT_BONES) {
+ mesh->has_bone_weights = true;
+ }
+
+ if (p_surface.index_count) {
+ bool is_index_16 = p_surface.vertex_count <= 65536;
+ glGenBuffers(1, &s->index_buffer);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_buffer);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, p_surface.index_data.size(), p_surface.index_data.ptr(), GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
+ s->index_count = p_surface.index_count;
+
+ if (p_surface.lods.size()) {
+ s->lods = memnew_arr(Mesh::Surface::LOD, p_surface.lods.size());
+ s->lod_count = p_surface.lods.size();
+
+ for (int i = 0; i < p_surface.lods.size(); i++) {
+ glGenBuffers(1, &s->lods[i].index_buffer);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->lods[i].index_buffer);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, p_surface.lods[i].index_data.size(), p_surface.lods[i].index_data.ptr(), GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
+ s->lods[i].edge_length = p_surface.lods[i].edge_length;
+ s->lods[i].index_count = p_surface.lods[i].index_data.size() / (is_index_16 ? 2 : 4);
+ }
+ }
+ }
+
+ s->aabb = p_surface.aabb;
+ s->bone_aabbs = p_surface.bone_aabbs; //only really useful for returning them.
+
+ if (mesh->blend_shape_count > 0) {
+ //s->blend_shape_buffer = RD::get_singleton()->storage_buffer_create(p_surface.blend_shape_data.size(), p_surface.blend_shape_data);
+ }
+
+ if (mesh->surface_count == 0) {
+ mesh->bone_aabbs = p_surface.bone_aabbs;
+ mesh->aabb = p_surface.aabb;
+ } else {
+ if (mesh->bone_aabbs.size() < p_surface.bone_aabbs.size()) {
+ // ArrayMesh::_surface_set_data only allocates bone_aabbs up to max_bone
+ // Each surface may affect different numbers of bones.
+ mesh->bone_aabbs.resize(p_surface.bone_aabbs.size());
+ }
+ for (int i = 0; i < p_surface.bone_aabbs.size(); i++) {
+ mesh->bone_aabbs.write[i].merge_with(p_surface.bone_aabbs[i]);
+ }
+ mesh->aabb.merge_with(p_surface.aabb);
+ }
+
+ s->material = p_surface.material;
+
+ mesh->surfaces = (Mesh::Surface **)memrealloc(mesh->surfaces, sizeof(Mesh::Surface *) * (mesh->surface_count + 1));
+ mesh->surfaces[mesh->surface_count] = s;
+ mesh->surface_count++;
+
+ for (MeshInstance *mi : mesh->instances) {
+ _mesh_instance_add_surface(mi, mesh, mesh->surface_count - 1);
+ }
+
+ mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+
+ for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) {
+ Mesh *shadow_owner = E->get();
+ shadow_owner->shadow_mesh = RID();
+ shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+ }
+
+ mesh->material_cache.clear();
}
int MeshStorage::mesh_get_blend_shape_count(RID p_mesh) const {
- return 0;
+ const Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
+ return mesh->blend_shape_count;
}
void MeshStorage::mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_INDEX((int)p_mode, 2);
+
+ mesh->blend_shape_mode = p_mode;
}
RS::BlendShapeMode MeshStorage::mesh_get_blend_shape_mode(RID p_mesh) const {
- return RS::BLEND_SHAPE_MODE_NORMALIZED;
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, RS::BLEND_SHAPE_MODE_NORMALIZED);
+ return mesh->blend_shape_mode;
}
void MeshStorage::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
@@ -91,10 +305,21 @@ void MeshStorage::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int
}
void MeshStorage::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count);
+ mesh->surfaces[p_surface]->material = p_material;
+
+ mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL);
+ mesh->material_cache.clear();
}
RID MeshStorage::mesh_surface_get_material(RID p_mesh, int p_surface) const {
- return RID();
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, RID());
+ ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_surface, mesh->surface_count, RID());
+
+ return mesh->surfaces[p_surface]->material;
}
RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const {
@@ -102,117 +327,1044 @@ RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const {
}
int MeshStorage::mesh_get_surface_count(RID p_mesh) const {
- return 1;
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, 0);
+ return mesh->surface_count;
}
void MeshStorage::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ mesh->custom_aabb = p_aabb;
}
AABB MeshStorage::mesh_get_custom_aabb(RID p_mesh) const {
- return AABB();
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, AABB());
+ return mesh->custom_aabb;
}
AABB MeshStorage::mesh_get_aabb(RID p_mesh, RID p_skeleton) {
- return AABB();
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, AABB());
+
+ if (mesh->custom_aabb != AABB()) {
+ return mesh->custom_aabb;
+ }
+
+ Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton);
+
+ if (!skeleton || skeleton->size == 0) {
+ return mesh->aabb;
+ }
+
+ // Calculate AABB based on Skeleton
+
+ AABB aabb;
+
+ for (uint32_t i = 0; i < mesh->surface_count; i++) {
+ AABB laabb;
+ if ((mesh->surfaces[i]->format & RS::ARRAY_FORMAT_BONES) && mesh->surfaces[i]->bone_aabbs.size()) {
+ int bs = mesh->surfaces[i]->bone_aabbs.size();
+ const AABB *skbones = mesh->surfaces[i]->bone_aabbs.ptr();
+
+ int sbs = skeleton->size;
+ ERR_CONTINUE(bs > sbs);
+ const float *baseptr = skeleton->data.ptr();
+
+ bool first = true;
+
+ if (skeleton->use_2d) {
+ for (int j = 0; j < bs; j++) {
+ if (skbones[0].size == Vector3()) {
+ continue; //bone is unused
+ }
+
+ const float *dataptr = baseptr + j * 8;
+
+ Transform3D mtx;
+
+ mtx.basis.elements[0].x = dataptr[0];
+ mtx.basis.elements[1].x = dataptr[1];
+ mtx.origin.x = dataptr[3];
+
+ mtx.basis.elements[0].y = dataptr[4];
+ mtx.basis.elements[1].y = dataptr[5];
+ mtx.origin.y = dataptr[7];
+
+ AABB baabb = mtx.xform(skbones[j]);
+
+ if (first) {
+ laabb = baabb;
+ first = false;
+ } else {
+ laabb.merge_with(baabb);
+ }
+ }
+ } else {
+ for (int j = 0; j < bs; j++) {
+ if (skbones[0].size == Vector3()) {
+ continue; //bone is unused
+ }
+
+ const float *dataptr = baseptr + j * 12;
+
+ Transform3D mtx;
+
+ mtx.basis.elements[0][0] = dataptr[0];
+ mtx.basis.elements[0][1] = dataptr[1];
+ mtx.basis.elements[0][2] = dataptr[2];
+ mtx.origin.x = dataptr[3];
+ mtx.basis.elements[1][0] = dataptr[4];
+ mtx.basis.elements[1][1] = dataptr[5];
+ mtx.basis.elements[1][2] = dataptr[6];
+ mtx.origin.y = dataptr[7];
+ mtx.basis.elements[2][0] = dataptr[8];
+ mtx.basis.elements[2][1] = dataptr[9];
+ mtx.basis.elements[2][2] = dataptr[10];
+ mtx.origin.z = dataptr[11];
+
+ AABB baabb = mtx.xform(skbones[j]);
+ if (first) {
+ laabb = baabb;
+ first = false;
+ } else {
+ laabb.merge_with(baabb);
+ }
+ }
+ }
+
+ if (laabb.size == Vector3()) {
+ laabb = mesh->surfaces[i]->aabb;
+ }
+ } else {
+ laabb = mesh->surfaces[i]->aabb;
+ }
+
+ if (i == 0) {
+ aabb = laabb;
+ } else {
+ aabb.merge_with(laabb);
+ }
+ }
+
+ return aabb;
}
void MeshStorage::mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+
+ Mesh *shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh);
+ if (shadow_mesh) {
+ shadow_mesh->shadow_owners.erase(mesh);
+ }
+ mesh->shadow_mesh = p_shadow_mesh;
+
+ shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh);
+
+ if (shadow_mesh) {
+ shadow_mesh->shadow_owners.insert(mesh);
+ }
+
+ mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
}
void MeshStorage::mesh_clear(RID p_mesh) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ for (uint32_t i = 0; i < mesh->surface_count; i++) {
+ Mesh::Surface &s = *mesh->surfaces[i];
+
+ if (s.vertex_buffer != 0) {
+ glDeleteBuffers(1, &s.vertex_buffer);
+ }
+
+ if (s.version_count != 0) {
+ for (uint32_t j = 0; j < s.version_count; j++) {
+ glDeleteVertexArrays(1, &s.versions[j].vertex_array);
+ }
+ }
+
+ if (s.attribute_buffer != 0) {
+ glDeleteBuffers(1, &s.attribute_buffer);
+ }
+
+ if (s.skin_buffer != 0) {
+ glDeleteBuffers(1, &s.skin_buffer);
+ }
+
+ if (s.index_buffer != 0) {
+ glDeleteBuffers(1, &s.index_buffer);
+ glDeleteVertexArrays(1, &s.index_array);
+ }
+ memdelete(mesh->surfaces[i]);
+ }
+ if (mesh->surfaces) {
+ memfree(mesh->surfaces);
+ }
+
+ mesh->surfaces = nullptr;
+ mesh->surface_count = 0;
+ mesh->material_cache.clear();
+ //clear instance data
+ for (MeshInstance *mi : mesh->instances) {
+ _mesh_instance_clear(mi);
+ }
+ mesh->has_bone_weights = false;
+ mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+
+ for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) {
+ Mesh *shadow_owner = E->get();
+ shadow_owner->shadow_mesh = RID();
+ shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+ }
+}
+
+void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis) {
+ Mesh::Surface::Attrib attribs[RS::ARRAY_MAX];
+
+ int attributes_stride = 0;
+ int vertex_stride = 0;
+ int skin_stride = 0;
+
+ for (int i = 0; i < RS::ARRAY_INDEX; i++) {
+ if (!(s->format & (1 << i))) {
+ attribs[i].enabled = false;
+ attribs[i].integer = false;
+ continue;
+ }
+
+ attribs[i].enabled = true;
+ attribs[i].integer = false;
+
+ switch (i) {
+ case RS::ARRAY_VERTEX: {
+ attribs[i].offset = vertex_stride;
+ if (s->format & RS::ARRAY_FLAG_USE_2D_VERTICES) {
+ attribs[i].size = 2;
+ } else {
+ attribs[i].size = 3;
+ }
+ attribs[i].type = GL_FLOAT;
+ vertex_stride += attribs[i].size * sizeof(float);
+ attribs[i].normalized = GL_FALSE;
+ } break;
+ case RS::ARRAY_NORMAL: {
+ attribs[i].offset = vertex_stride;
+ // Will need to change to accommodate octahedral compression
+ attribs[i].size = 1;
+ attribs[i].type = GL_UNSIGNED_INT_2_10_10_10_REV;
+ vertex_stride += sizeof(float);
+ attribs[i].normalized = GL_TRUE;
+ } break;
+ case RS::ARRAY_TANGENT: {
+ attribs[i].offset = vertex_stride;
+ attribs[i].size = 1;
+ attribs[i].type = GL_UNSIGNED_INT_2_10_10_10_REV;
+ vertex_stride += sizeof(float);
+ attribs[i].normalized = GL_TRUE;
+ } break;
+ case RS::ARRAY_COLOR: {
+ attribs[i].offset = attributes_stride;
+ attribs[i].size = 4;
+ attribs[i].type = GL_UNSIGNED_BYTE;
+ attributes_stride += 4;
+ attribs[i].normalized = GL_TRUE;
+ } break;
+ case RS::ARRAY_TEX_UV: {
+ attribs[i].offset = attributes_stride;
+ attribs[i].size = 2;
+ attribs[i].type = GL_FLOAT;
+ attributes_stride += 2 * sizeof(float);
+ attribs[i].normalized = GL_FALSE;
+ } break;
+ case RS::ARRAY_TEX_UV2: {
+ attribs[i].offset = attributes_stride;
+ attribs[i].size = 2;
+ attribs[i].type = GL_FLOAT;
+ attributes_stride += 2 * sizeof(float);
+ attribs[i].normalized = GL_FALSE;
+ } break;
+ case RS::ARRAY_CUSTOM0:
+ case RS::ARRAY_CUSTOM1:
+ case RS::ARRAY_CUSTOM2:
+ case RS::ARRAY_CUSTOM3: {
+ attribs[i].offset = attributes_stride;
+
+ int idx = i - RS::ARRAY_CUSTOM0;
+ uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
+ uint32_t fmt = (s->format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK;
+ uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
+ GLenum gl_type[RS::ARRAY_CUSTOM_MAX] = { GL_UNSIGNED_BYTE, GL_BYTE, GL_HALF_FLOAT, GL_HALF_FLOAT, GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_FLOAT };
+ GLboolean norm[RS::ARRAY_CUSTOM_MAX] = { GL_TRUE, GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE };
+ attribs[i].type = gl_type[fmt];
+ attributes_stride += fmtsize[fmt];
+ attribs[i].size = fmtsize[fmt] / sizeof(float);
+ attribs[i].normalized = norm[fmt];
+ } break;
+ case RS::ARRAY_BONES: {
+ attribs[i].offset = skin_stride;
+ attribs[i].size = 4;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ attributes_stride += 4 * sizeof(uint16_t);
+ attribs[i].normalized = GL_FALSE;
+ attribs[i].integer = true;
+ } break;
+ case RS::ARRAY_WEIGHTS: {
+ attribs[i].offset = skin_stride;
+ attribs[i].size = 4;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ attributes_stride += 4 * sizeof(uint16_t);
+ attribs[i].normalized = GL_TRUE;
+ } break;
+ }
+ }
+
+ glGenVertexArrays(1, &v.vertex_array);
+ glBindVertexArray(v.vertex_array);
+
+ for (int i = 0; i < RS::ARRAY_INDEX; i++) {
+ if (!attribs[i].enabled) {
+ continue;
+ }
+ if (i <= RS::ARRAY_TANGENT) {
+ if (mis) {
+ glBindBuffer(GL_ARRAY_BUFFER, mis->vertex_buffer);
+ } else {
+ glBindBuffer(GL_ARRAY_BUFFER, s->vertex_buffer);
+ }
+ } else if (i <= RS::ARRAY_CUSTOM3) {
+ glBindBuffer(GL_ARRAY_BUFFER, s->attribute_buffer);
+ } else {
+ glBindBuffer(GL_ARRAY_BUFFER, s->skin_buffer);
+ }
+
+ if (attribs[i].integer) {
+ glVertexAttribIPointer(i, attribs[i].size, attribs[i].type, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
+ } else {
+ glVertexAttribPointer(i, attribs[i].size, attribs[i].type, attribs[i].normalized, attribs[i].stride, CAST_INT_TO_UCHAR_PTR(attribs[i].offset));
+ }
+ glEnableVertexAttribArray(attribs[i].index);
+ }
+
+ // Do not bind index here as we want to switch between index buffers for LOD
+
+ glBindVertexArray(0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+ v.input_mask = p_input_mask;
}
/* MESH INSTANCE API */
RID MeshStorage::mesh_instance_create(RID p_base) {
- return RID();
+ Mesh *mesh = mesh_owner.get_or_null(p_base);
+ ERR_FAIL_COND_V(!mesh, RID());
+
+ RID rid = mesh_instance_owner.make_rid();
+ MeshInstance *mi = mesh_instance_owner.get_or_null(rid);
+
+ mi->mesh = mesh;
+
+ for (uint32_t i = 0; i < mesh->surface_count; i++) {
+ _mesh_instance_add_surface(mi, mesh, i);
+ }
+
+ mi->I = mesh->instances.push_back(mi);
+
+ mi->dirty = true;
+
+ return rid;
}
void MeshStorage::mesh_instance_free(RID p_rid) {
+ MeshInstance *mi = mesh_instance_owner.get_or_null(p_rid);
+ _mesh_instance_clear(mi);
+ mi->mesh->instances.erase(mi->I);
+ mi->I = nullptr;
+
+ mesh_instance_owner.free(p_rid);
}
void MeshStorage::mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) {
+ MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance);
+ if (mi->skeleton == p_skeleton) {
+ return;
+ }
+ mi->skeleton = p_skeleton;
+ mi->skeleton_version = 0;
+ mi->dirty = true;
}
void MeshStorage::mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) {
+ MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance);
+ ERR_FAIL_COND(!mi);
+ ERR_FAIL_INDEX(p_shape, (int)mi->blend_weights.size());
+ mi->blend_weights[p_shape] = p_weight;
+ mi->weights_dirty = true;
+}
+
+void MeshStorage::_mesh_instance_clear(MeshInstance *mi) {
+ for (uint32_t i = 0; i < mi->surfaces.size(); i++) {
+ if (mi->surfaces[i].version_count != 0) {
+ for (uint32_t j = 0; j < mi->surfaces[i].version_count; j++) {
+ glDeleteVertexArrays(1, &mi->surfaces[i].versions[j].vertex_array);
+ }
+ memfree(mi->surfaces[i].versions);
+ }
+ if (mi->surfaces[i].vertex_buffer != 0) {
+ glDeleteBuffers(1, &mi->surfaces[i].vertex_buffer);
+ }
+ }
+ mi->surfaces.clear();
+
+ if (mi->blend_weights_buffer != 0) {
+ glDeleteBuffers(1, &mi->blend_weights_buffer);
+ }
+ mi->blend_weights.clear();
+ mi->weights_dirty = false;
+ mi->skeleton_version = 0;
+}
+
+void MeshStorage::_mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface) {
+ if (mesh->blend_shape_count > 0 && mi->blend_weights_buffer == 0) {
+ mi->blend_weights.resize(mesh->blend_shape_count);
+ for (uint32_t i = 0; i < mi->blend_weights.size(); i++) {
+ mi->blend_weights[i] = 0;
+ }
+ // Todo allocate buffer for blend_weights and copy data to it
+ //mi->blend_weights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(float) * mi->blend_weights.size(), mi->blend_weights.to_byte_array());
+
+ mi->weights_dirty = true;
+ }
+
+ MeshInstance::Surface s;
+ if (mesh->blend_shape_count > 0 || (mesh->surfaces[p_surface]->format & RS::ARRAY_FORMAT_BONES)) {
+ //surface warrants transform
+ //s.vertex_buffer = RD::get_singleton()->vertex_buffer_create(mesh->surfaces[p_surface]->vertex_buffer_size, Vector<uint8_t>(), true);
+ }
+
+ mi->surfaces.push_back(s);
+ mi->dirty = true;
}
void MeshStorage::mesh_instance_check_for_update(RID p_mesh_instance) {
+ MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance);
+
+ bool needs_update = mi->dirty;
+
+ if (mi->weights_dirty && !mi->weight_update_list.in_list()) {
+ dirty_mesh_instance_weights.add(&mi->weight_update_list);
+ needs_update = true;
+ }
+
+ if (mi->array_update_list.in_list()) {
+ return;
+ }
+
+ if (!needs_update && mi->skeleton.is_valid()) {
+ Skeleton *sk = skeleton_owner.get_or_null(mi->skeleton);
+ if (sk && sk->version != mi->skeleton_version) {
+ needs_update = true;
+ }
+ }
+
+ if (needs_update) {
+ dirty_mesh_instance_arrays.add(&mi->array_update_list);
+ }
}
void MeshStorage::update_mesh_instances() {
+ while (dirty_mesh_instance_weights.first()) {
+ MeshInstance *mi = dirty_mesh_instance_weights.first()->self();
+
+ if (mi->blend_weights_buffer != 0) {
+ //RD::get_singleton()->buffer_update(mi->blend_weights_buffer, 0, mi->blend_weights.size() * sizeof(float), mi->blend_weights.ptr());
+ }
+ dirty_mesh_instance_weights.remove(&mi->weight_update_list);
+ mi->weights_dirty = false;
+ }
+ if (dirty_mesh_instance_arrays.first() == nullptr) {
+ return; //nothing to do
+ }
+
+ // Process skeletons and blend shapes using transform feedback
+ // TODO: Implement when working on skeletons and blend shapes
}
/* MULTIMESH API */
RID MeshStorage::multimesh_allocate() {
- return RID();
+ return multimesh_owner.allocate_rid();
}
void MeshStorage::multimesh_initialize(RID p_rid) {
+ multimesh_owner.initialize_rid(p_rid, MultiMesh());
}
void MeshStorage::multimesh_free(RID p_rid) {
+ _update_dirty_multimeshes();
+ multimesh_allocate_data(p_rid, 0, RS::MULTIMESH_TRANSFORM_2D);
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_rid);
+ multimesh->dependency.deleted_notify(p_rid);
+ multimesh_owner.free(p_rid);
}
void MeshStorage::multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors, bool p_use_custom_data) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+
+ if (multimesh->instances == p_instances && multimesh->xform_format == p_transform_format && multimesh->uses_colors == p_use_colors && multimesh->uses_custom_data == p_use_custom_data) {
+ return;
+ }
+
+ if (multimesh->buffer) {
+ glDeleteBuffers(1, &multimesh->buffer);
+ multimesh->buffer = 0;
+ }
+
+ if (multimesh->data_cache_dirty_regions) {
+ memdelete_arr(multimesh->data_cache_dirty_regions);
+ multimesh->data_cache_dirty_regions = nullptr;
+ multimesh->data_cache_used_dirty_regions = 0;
+ }
+
+ multimesh->instances = p_instances;
+ multimesh->xform_format = p_transform_format;
+ multimesh->uses_colors = p_use_colors;
+ multimesh->color_offset_cache = p_transform_format == RS::MULTIMESH_TRANSFORM_2D ? 8 : 12;
+ multimesh->uses_custom_data = p_use_custom_data;
+ multimesh->custom_data_offset_cache = multimesh->color_offset_cache + (p_use_colors ? 4 : 0);
+ multimesh->stride_cache = multimesh->custom_data_offset_cache + (p_use_custom_data ? 4 : 0);
+ multimesh->buffer_set = false;
+
+ //print_line("allocate, elements: " + itos(p_instances) + " 2D: " + itos(p_transform_format == RS::MULTIMESH_TRANSFORM_2D) + " colors " + itos(multimesh->uses_colors) + " data " + itos(multimesh->uses_custom_data) + " stride " + itos(multimesh->stride_cache) + " total size " + itos(multimesh->stride_cache * multimesh->instances));
+ multimesh->data_cache = Vector<float>();
+ multimesh->aabb = AABB();
+ multimesh->aabb_dirty = false;
+ multimesh->visible_instances = MIN(multimesh->visible_instances, multimesh->instances);
+
+ if (multimesh->instances) {
+ glGenBuffers(1, &multimesh->buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ glBufferData(GL_ARRAY_BUFFER, multimesh->instances * multimesh->stride_cache * sizeof(float), nullptr, GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ }
+
+ multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MULTIMESH);
}
int MeshStorage::multimesh_get_instance_count(RID p_multimesh) const {
- return 0;
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, 0);
+ return multimesh->instances;
}
void MeshStorage::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ if (multimesh->mesh == p_mesh) {
+ return;
+ }
+ multimesh->mesh = p_mesh;
+
+ if (multimesh->instances == 0) {
+ return;
+ }
+
+ if (multimesh->data_cache.size()) {
+ //we have a data cache, just mark it dirty
+ _multimesh_mark_all_dirty(multimesh, false, true);
+ } else if (multimesh->instances) {
+ //need to re-create AABB unfortunately, calling this has a penalty
+ if (multimesh->buffer_set) {
+ // TODO add a function to RasterizerStorage to get data from a buffer
+ //Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer);
+ //const uint8_t *r = buffer.ptr();
+ //const float *data = (const float *)r;
+ //_multimesh_re_create_aabb(multimesh, data, multimesh->instances);
+ }
+ }
+
+ multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH);
+}
+
+#define MULTIMESH_DIRTY_REGION_SIZE 512
+
+void MeshStorage::_multimesh_make_local(MultiMesh *multimesh) const {
+ if (multimesh->data_cache.size() > 0) {
+ return; //already local
+ }
+ ERR_FAIL_COND(multimesh->data_cache.size() > 0);
+ // this means that the user wants to load/save individual elements,
+ // for this, the data must reside on CPU, so just copy it there.
+ multimesh->data_cache.resize(multimesh->instances * multimesh->stride_cache);
+ {
+ float *w = multimesh->data_cache.ptrw();
+
+ if (multimesh->buffer_set) {
+ //Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer);
+ {
+ // const uint8_t *r = buffer.ptr();
+ // memcpy(w, r, buffer.size());
+ }
+ } else {
+ memset(w, 0, (size_t)multimesh->instances * multimesh->stride_cache * sizeof(float));
+ }
+ }
+ uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+ multimesh->data_cache_dirty_regions = memnew_arr(bool, data_cache_dirty_region_count);
+ for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) {
+ multimesh->data_cache_dirty_regions[i] = false;
+ }
+ multimesh->data_cache_used_dirty_regions = 0;
+}
+
+void MeshStorage::_multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb) {
+ uint32_t region_index = p_index / MULTIMESH_DIRTY_REGION_SIZE;
+#ifdef DEBUG_ENABLED
+ uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+ ERR_FAIL_UNSIGNED_INDEX(region_index, data_cache_dirty_region_count); //bug
+#endif
+ if (!multimesh->data_cache_dirty_regions[region_index]) {
+ multimesh->data_cache_dirty_regions[region_index] = true;
+ multimesh->data_cache_used_dirty_regions++;
+ }
+
+ if (p_aabb) {
+ multimesh->aabb_dirty = true;
+ }
+
+ if (!multimesh->dirty) {
+ multimesh->dirty_list = multimesh_dirty_list;
+ multimesh_dirty_list = multimesh;
+ multimesh->dirty = true;
+ }
+}
+
+void MeshStorage::_multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb) {
+ if (p_data) {
+ uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+
+ for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) {
+ if (!multimesh->data_cache_dirty_regions[i]) {
+ multimesh->data_cache_dirty_regions[i] = true;
+ multimesh->data_cache_used_dirty_regions++;
+ }
+ }
+ }
+
+ if (p_aabb) {
+ multimesh->aabb_dirty = true;
+ }
+
+ if (!multimesh->dirty) {
+ multimesh->dirty_list = multimesh_dirty_list;
+ multimesh_dirty_list = multimesh;
+ multimesh->dirty = true;
+ }
+}
+
+void MeshStorage::_multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances) {
+ ERR_FAIL_COND(multimesh->mesh.is_null());
+ AABB aabb;
+ AABB mesh_aabb = mesh_get_aabb(multimesh->mesh);
+ for (int i = 0; i < p_instances; i++) {
+ const float *data = p_data + multimesh->stride_cache * i;
+ Transform3D t;
+
+ if (multimesh->xform_format == RS::MULTIMESH_TRANSFORM_3D) {
+ t.basis.elements[0][0] = data[0];
+ t.basis.elements[0][1] = data[1];
+ t.basis.elements[0][2] = data[2];
+ t.origin.x = data[3];
+ t.basis.elements[1][0] = data[4];
+ t.basis.elements[1][1] = data[5];
+ t.basis.elements[1][2] = data[6];
+ t.origin.y = data[7];
+ t.basis.elements[2][0] = data[8];
+ t.basis.elements[2][1] = data[9];
+ t.basis.elements[2][2] = data[10];
+ t.origin.z = data[11];
+
+ } else {
+ t.basis.elements[0].x = data[0];
+ t.basis.elements[1].x = data[1];
+ t.origin.x = data[3];
+
+ t.basis.elements[0].y = data[4];
+ t.basis.elements[1].y = data[5];
+ t.origin.y = data[7];
+ }
+
+ if (i == 0) {
+ aabb = t.xform(mesh_aabb);
+ } else {
+ aabb.merge_with(t.xform(mesh_aabb));
+ }
+ }
+
+ multimesh->aabb = aabb;
}
void MeshStorage::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_INDEX(p_index, multimesh->instances);
+ ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D);
+
+ _multimesh_make_local(multimesh);
+
+ {
+ float *w = multimesh->data_cache.ptrw();
+
+ float *dataptr = w + p_index * multimesh->stride_cache;
+
+ dataptr[0] = p_transform.basis.elements[0][0];
+ dataptr[1] = p_transform.basis.elements[0][1];
+ dataptr[2] = p_transform.basis.elements[0][2];
+ dataptr[3] = p_transform.origin.x;
+ dataptr[4] = p_transform.basis.elements[1][0];
+ dataptr[5] = p_transform.basis.elements[1][1];
+ dataptr[6] = p_transform.basis.elements[1][2];
+ dataptr[7] = p_transform.origin.y;
+ dataptr[8] = p_transform.basis.elements[2][0];
+ dataptr[9] = p_transform.basis.elements[2][1];
+ dataptr[10] = p_transform.basis.elements[2][2];
+ dataptr[11] = p_transform.origin.z;
+ }
+
+ _multimesh_mark_dirty(multimesh, p_index, true);
}
void MeshStorage::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_INDEX(p_index, multimesh->instances);
+ ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D);
+
+ _multimesh_make_local(multimesh);
+
+ {
+ float *w = multimesh->data_cache.ptrw();
+
+ float *dataptr = w + p_index * multimesh->stride_cache;
+
+ dataptr[0] = p_transform.elements[0][0];
+ dataptr[1] = p_transform.elements[1][0];
+ dataptr[2] = 0;
+ dataptr[3] = p_transform.elements[2][0];
+ dataptr[4] = p_transform.elements[0][1];
+ dataptr[5] = p_transform.elements[1][1];
+ dataptr[6] = 0;
+ dataptr[7] = p_transform.elements[2][1];
+ }
+
+ _multimesh_mark_dirty(multimesh, p_index, true);
}
void MeshStorage::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_INDEX(p_index, multimesh->instances);
+ ERR_FAIL_COND(!multimesh->uses_colors);
+
+ _multimesh_make_local(multimesh);
+
+ {
+ float *w = multimesh->data_cache.ptrw();
+
+ float *dataptr = w + p_index * multimesh->stride_cache + multimesh->color_offset_cache;
+
+ dataptr[0] = p_color.r;
+ dataptr[1] = p_color.g;
+ dataptr[2] = p_color.b;
+ dataptr[3] = p_color.a;
+ }
+
+ _multimesh_mark_dirty(multimesh, p_index, false);
}
void MeshStorage::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_INDEX(p_index, multimesh->instances);
+ ERR_FAIL_COND(!multimesh->uses_custom_data);
+
+ _multimesh_make_local(multimesh);
+
+ {
+ float *w = multimesh->data_cache.ptrw();
+
+ float *dataptr = w + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache;
+
+ dataptr[0] = p_color.r;
+ dataptr[1] = p_color.g;
+ dataptr[2] = p_color.b;
+ dataptr[3] = p_color.a;
+ }
+
+ _multimesh_mark_dirty(multimesh, p_index, false);
}
RID MeshStorage::multimesh_get_mesh(RID p_multimesh) const {
- return RID();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, RID());
+
+ return multimesh->mesh;
}
AABB MeshStorage::multimesh_get_aabb(RID p_multimesh) const {
- return AABB();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, AABB());
+ if (multimesh->aabb_dirty) {
+ const_cast<MeshStorage *>(this)->_update_dirty_multimeshes();
+ }
+ return multimesh->aabb;
}
Transform3D MeshStorage::multimesh_instance_get_transform(RID p_multimesh, int p_index) const {
- return Transform3D();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, Transform3D());
+ ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform3D());
+ ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D, Transform3D());
+
+ _multimesh_make_local(multimesh);
+
+ Transform3D t;
+ {
+ const float *r = multimesh->data_cache.ptr();
+
+ const float *dataptr = r + p_index * multimesh->stride_cache;
+
+ t.basis.elements[0][0] = dataptr[0];
+ t.basis.elements[0][1] = dataptr[1];
+ t.basis.elements[0][2] = dataptr[2];
+ t.origin.x = dataptr[3];
+ t.basis.elements[1][0] = dataptr[4];
+ t.basis.elements[1][1] = dataptr[5];
+ t.basis.elements[1][2] = dataptr[6];
+ t.origin.y = dataptr[7];
+ t.basis.elements[2][0] = dataptr[8];
+ t.basis.elements[2][1] = dataptr[9];
+ t.basis.elements[2][2] = dataptr[10];
+ t.origin.z = dataptr[11];
+ }
+
+ return t;
}
Transform2D MeshStorage::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const {
- return Transform2D();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, Transform2D());
+ ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform2D());
+ ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D, Transform2D());
+
+ _multimesh_make_local(multimesh);
+
+ Transform2D t;
+ {
+ const float *r = multimesh->data_cache.ptr();
+
+ const float *dataptr = r + p_index * multimesh->stride_cache;
+
+ t.elements[0][0] = dataptr[0];
+ t.elements[1][0] = dataptr[1];
+ t.elements[2][0] = dataptr[3];
+ t.elements[0][1] = dataptr[4];
+ t.elements[1][1] = dataptr[5];
+ t.elements[2][1] = dataptr[7];
+ }
+
+ return t;
}
Color MeshStorage::multimesh_instance_get_color(RID p_multimesh, int p_index) const {
- return Color();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, Color());
+ ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color());
+ ERR_FAIL_COND_V(!multimesh->uses_colors, Color());
+
+ _multimesh_make_local(multimesh);
+
+ Color c;
+ {
+ const float *r = multimesh->data_cache.ptr();
+
+ const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->color_offset_cache;
+
+ c.r = dataptr[0];
+ c.g = dataptr[1];
+ c.b = dataptr[2];
+ c.a = dataptr[3];
+ }
+
+ return c;
}
Color MeshStorage::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const {
- return Color();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, Color());
+ ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color());
+ ERR_FAIL_COND_V(!multimesh->uses_custom_data, Color());
+
+ _multimesh_make_local(multimesh);
+
+ Color c;
+ {
+ const float *r = multimesh->data_cache.ptr();
+
+ const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache;
+
+ c.r = dataptr[0];
+ c.g = dataptr[1];
+ c.b = dataptr[2];
+ c.a = dataptr[3];
+ }
+
+ return c;
}
void MeshStorage::multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_COND(p_buffer.size() != (multimesh->instances * (int)multimesh->stride_cache));
+
+ {
+ const float *r = p_buffer.ptr();
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ glBufferData(GL_ARRAY_BUFFER, p_buffer.size() * sizeof(float), r, GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ multimesh->buffer_set = true;
+ }
+
+ if (multimesh->data_cache.size()) {
+ //if we have a data cache, just update it
+ multimesh->data_cache = p_buffer;
+ {
+ //clear dirty since nothing will be dirty anymore
+ uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+ for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) {
+ multimesh->data_cache_dirty_regions[i] = false;
+ }
+ multimesh->data_cache_used_dirty_regions = 0;
+ }
+
+ _multimesh_mark_all_dirty(multimesh, false, true); //update AABB
+ } else if (multimesh->mesh.is_valid()) {
+ //if we have a mesh set, we need to re-generate the AABB from the new data
+ const float *data = p_buffer.ptr();
+
+ _multimesh_re_create_aabb(multimesh, data, multimesh->instances);
+ multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_AABB);
+ }
}
Vector<float> MeshStorage::multimesh_get_buffer(RID p_multimesh) const {
- return Vector<float>();
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, Vector<float>());
+ if (multimesh->buffer == 0) {
+ return Vector<float>();
+ } else if (multimesh->data_cache.size()) {
+ return multimesh->data_cache;
+ } else {
+ //get from memory
+
+ //Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer);
+ Vector<float> ret;
+ ret.resize(multimesh->instances * multimesh->stride_cache);
+ //{
+ // float *w = ret.ptrw();
+ // const uint8_t *r = buffer.ptr();
+ // memcpy(w, r, buffer.size());
+ //}
+
+ return ret;
+ }
}
void MeshStorage::multimesh_set_visible_instances(RID p_multimesh, int p_visible) {
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND(!multimesh);
+ ERR_FAIL_COND(p_visible < -1 || p_visible > multimesh->instances);
+ if (multimesh->visible_instances == p_visible) {
+ return;
+ }
+
+ if (multimesh->data_cache.size()) {
+ //there is a data cache..
+ _multimesh_mark_all_dirty(multimesh, false, true);
+ }
+
+ multimesh->visible_instances = p_visible;
+
+ multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES);
}
int MeshStorage::multimesh_get_visible_instances(RID p_multimesh) const {
- return 0;
+ MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
+ ERR_FAIL_COND_V(!multimesh, 0);
+ return multimesh->visible_instances;
+}
+
+void MeshStorage::_update_dirty_multimeshes() {
+ while (multimesh_dirty_list) {
+ MultiMesh *multimesh = multimesh_dirty_list;
+
+ if (multimesh->data_cache.size()) { //may have been cleared, so only process if it exists
+ const float *data = multimesh->data_cache.ptr();
+
+ uint32_t visible_instances = multimesh->visible_instances >= 0 ? multimesh->visible_instances : multimesh->instances;
+
+ if (multimesh->data_cache_used_dirty_regions) {
+ uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+ uint32_t visible_region_count = visible_instances == 0 ? 0 : (visible_instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1;
+
+ GLint region_size = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * sizeof(float);
+
+ if (multimesh->data_cache_used_dirty_regions > 32 || multimesh->data_cache_used_dirty_regions > visible_region_count / 2) {
+ // If there too many dirty regions, or represent the majority of regions, just copy all, else transfer cost piles up too much
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ glBufferData(GL_ARRAY_BUFFER, MIN(visible_region_count * region_size, multimesh->instances * (uint32_t)multimesh->stride_cache * (uint32_t)sizeof(float)), data, GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ } else {
+ // Not that many regions? update them all
+ // TODO: profile the performance cost on low end
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ for (uint32_t i = 0; i < visible_region_count; i++) {
+ if (multimesh->data_cache_dirty_regions[i]) {
+ GLint offset = i * region_size;
+ GLint size = multimesh->stride_cache * (uint32_t)multimesh->instances * (uint32_t)sizeof(float);
+ uint32_t region_start_index = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * i;
+ glBufferSubData(GL_ARRAY_BUFFER, offset, MIN(region_size, size - offset), &data[region_start_index]);
+ }
+ }
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ }
+
+ for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) {
+ multimesh->data_cache_dirty_regions[i] = false;
+ }
+
+ multimesh->data_cache_used_dirty_regions = 0;
+ }
+
+ if (multimesh->aabb_dirty) {
+ //aabb is dirty..
+ _multimesh_re_create_aabb(multimesh, data, visible_instances);
+ multimesh->aabb_dirty = false;
+ multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_AABB);
+ }
+ }
+
+ multimesh_dirty_list = multimesh->dirty_list;
+
+ multimesh->dirty_list = nullptr;
+ multimesh->dirty = false;
+ }
+
+ multimesh_dirty_list = nullptr;
}
/* SKELETON API */
diff --git a/drivers/gles3/storage/mesh_storage.h b/drivers/gles3/storage/mesh_storage.h
index 3f44908049..f51ec6edbe 100644
--- a/drivers/gles3/storage/mesh_storage.h
+++ b/drivers/gles3/storage/mesh_storage.h
@@ -38,12 +38,202 @@
#include "core/templates/self_list.h"
#include "servers/rendering/storage/mesh_storage.h"
+#include "platform_config.h"
+#ifndef OPENGL_INCLUDE_H
+#include <GLES3/gl3.h>
+#else
+#include OPENGL_INCLUDE_H
+#endif
+
namespace GLES3 {
+struct MeshInstance;
+
+struct Mesh {
+ struct Surface {
+ struct Attrib {
+ bool enabled;
+ bool integer;
+ GLuint index;
+ GLint size;
+ GLenum type;
+ GLboolean normalized;
+ GLsizei stride;
+ uint32_t offset;
+ };
+ RS::PrimitiveType primitive = RS::PRIMITIVE_POINTS;
+ uint32_t format = 0;
+
+ GLuint vertex_buffer = 0;
+ GLuint attribute_buffer = 0;
+ GLuint skin_buffer = 0;
+ uint32_t vertex_count = 0;
+ uint32_t vertex_buffer_size = 0;
+ uint32_t skin_buffer_size = 0;
+
+ // Cache vertex arrays so they can be created
+ struct Version {
+ uint32_t input_mask = 0;
+ GLuint vertex_array;
+
+ Attrib attribs[RS::ARRAY_MAX];
+ };
+
+ SpinLock version_lock; //needed to access versions
+ Version *versions = nullptr; //allocated on demand
+ uint32_t version_count = 0;
+
+ GLuint index_buffer = 0;
+ GLuint index_array = 0;
+ uint32_t index_count = 0;
+
+ struct LOD {
+ float edge_length = 0.0;
+ uint32_t index_count = 0;
+ GLuint index_buffer;
+ };
+
+ LOD *lods = nullptr;
+ uint32_t lod_count = 0;
+
+ AABB aabb;
+
+ Vector<AABB> bone_aabbs;
+
+ GLuint blend_shape_buffer = 0;
+
+ RID material;
+ };
+
+ uint32_t blend_shape_count = 0;
+ RS::BlendShapeMode blend_shape_mode = RS::BLEND_SHAPE_MODE_NORMALIZED;
+
+ Surface **surfaces = nullptr;
+ uint32_t surface_count = 0;
+
+ Vector<AABB> bone_aabbs;
+
+ bool has_bone_weights = false;
+
+ AABB aabb;
+ AABB custom_aabb;
+
+ Vector<RID> material_cache;
+
+ List<MeshInstance *> instances;
+
+ RID shadow_mesh;
+ Set<Mesh *> shadow_owners;
+
+ RendererStorage::Dependency dependency;
+};
+
+/* Mesh Instance */
+
+struct MeshInstance {
+ Mesh *mesh = nullptr;
+ RID skeleton;
+ struct Surface {
+ GLuint vertex_buffer = 0;
+
+ Mesh::Surface::Version *versions = nullptr; //allocated on demand
+ uint32_t version_count = 0;
+ };
+ LocalVector<Surface> surfaces;
+ LocalVector<float> blend_weights;
+
+ GLuint blend_weights_buffer = 0;
+ List<MeshInstance *>::Element *I = nullptr; //used to erase itself
+ uint64_t skeleton_version = 0;
+ bool dirty = false;
+ bool weights_dirty = false;
+ SelfList<MeshInstance> weight_update_list;
+ SelfList<MeshInstance> array_update_list;
+ MeshInstance() :
+ weight_update_list(this), array_update_list(this) {}
+};
+
+/* MultiMesh */
+
+struct MultiMesh {
+ RID mesh;
+ int instances = 0;
+ RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D;
+ bool uses_colors = false;
+ bool uses_custom_data = false;
+ int visible_instances = -1;
+ AABB aabb;
+ bool aabb_dirty = false;
+ bool buffer_set = false;
+ uint32_t stride_cache = 0;
+ uint32_t color_offset_cache = 0;
+ uint32_t custom_data_offset_cache = 0;
+
+ Vector<float> data_cache; //used if individual setting is used
+ bool *data_cache_dirty_regions = nullptr;
+ uint32_t data_cache_used_dirty_regions = 0;
+
+ GLuint buffer;
+
+ bool dirty = false;
+ MultiMesh *dirty_list = nullptr;
+
+ RendererStorage::Dependency dependency;
+};
+
+struct Skeleton {
+ bool use_2d = false;
+ int size = 0;
+ Vector<float> data;
+ GLuint buffer = 0;
+
+ bool dirty = false;
+ Skeleton *dirty_list = nullptr;
+ Transform2D base_transform_2d;
+
+ uint64_t version = 1;
+
+ RendererStorage::Dependency dependency;
+};
+
class MeshStorage : public RendererMeshStorage {
private:
static MeshStorage *singleton;
+ /* Mesh */
+
+ mutable RID_Owner<Mesh, true> mesh_owner;
+
+ void _mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis = nullptr);
+
+ /* Mesh Instance API */
+
+ mutable RID_Owner<MeshInstance> mesh_instance_owner;
+
+ void _mesh_instance_clear(MeshInstance *mi);
+ void _mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface);
+ SelfList<MeshInstance>::List dirty_mesh_instance_weights;
+ SelfList<MeshInstance>::List dirty_mesh_instance_arrays;
+
+ /* MultiMesh */
+
+ mutable RID_Owner<MultiMesh, true> multimesh_owner;
+
+ MultiMesh *multimesh_dirty_list = nullptr;
+
+ _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const;
+ _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb);
+ _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb);
+ _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances);
+
+ /* Skeleton */
+
+ mutable RID_Owner<Skeleton, true> skeleton_owner;
+
+ Skeleton *skeleton_dirty_list = nullptr;
+
+ _FORCE_INLINE_ void _skeleton_make_dirty(Skeleton *skeleton);
+
public:
static MeshStorage *get_singleton();
@@ -52,6 +242,9 @@ public:
/* MESH API */
+ Mesh *get_mesh(RID p_rid) { return mesh_owner.get_or_null(p_rid); };
+ bool owns_mesh(RID p_rid) { return mesh_owner.owns(p_rid); };
+
virtual RID mesh_allocate() override;
virtual void mesh_initialize(RID p_rid) override;
virtual void mesh_free(RID p_rid) override;
@@ -83,6 +276,116 @@ public:
virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override;
virtual void mesh_clear(RID p_mesh) override;
+ _FORCE_INLINE_ const RID *mesh_get_surface_count_and_materials(RID p_mesh, uint32_t &r_surface_count) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, nullptr);
+ r_surface_count = mesh->surface_count;
+ if (r_surface_count == 0) {
+ return nullptr;
+ }
+ if (mesh->material_cache.is_empty()) {
+ mesh->material_cache.resize(mesh->surface_count);
+ for (uint32_t i = 0; i < r_surface_count; i++) {
+ mesh->material_cache.write[i] = mesh->surfaces[i]->material;
+ }
+ }
+
+ return mesh->material_cache.ptr();
+ }
+
+ _FORCE_INLINE_ void *mesh_get_surface(RID p_mesh, uint32_t p_surface_index) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, nullptr);
+ ERR_FAIL_UNSIGNED_INDEX_V(p_surface_index, mesh->surface_count, nullptr);
+
+ return mesh->surfaces[p_surface_index];
+ }
+
+ _FORCE_INLINE_ RID mesh_get_shadow_mesh(RID p_mesh) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND_V(!mesh, RID());
+
+ return mesh->shadow_mesh;
+ }
+
+ _FORCE_INLINE_ RS::PrimitiveType mesh_surface_get_primitive(void *p_surface) {
+ Mesh::Surface *surface = reinterpret_cast<Mesh::Surface *>(p_surface);
+ return surface->primitive;
+ }
+
+ _FORCE_INLINE_ bool mesh_surface_has_lod(void *p_surface) const {
+ Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
+ return s->lod_count > 0;
+ }
+
+ _FORCE_INLINE_ uint32_t mesh_surface_get_vertices_drawn_count(void *p_surface) const {
+ Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
+ return s->index_count ? s->index_count : s->vertex_count;
+ }
+
+ _FORCE_INLINE_ uint32_t mesh_surface_get_lod(void *p_surface, float p_model_scale, float p_distance_threshold, float p_mesh_lod_threshold, uint32_t *r_index_count = nullptr) const {
+ Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
+
+ int32_t current_lod = -1;
+ if (r_index_count) {
+ *r_index_count = s->index_count;
+ }
+ for (uint32_t i = 0; i < s->lod_count; i++) {
+ float screen_size = s->lods[i].edge_length * p_model_scale / p_distance_threshold;
+ if (screen_size > p_mesh_lod_threshold) {
+ break;
+ }
+ current_lod = i;
+ }
+ if (current_lod == -1) {
+ return 0;
+ } else {
+ if (r_index_count) {
+ *r_index_count = s->lods[current_lod].index_count;
+ }
+ return current_lod + 1;
+ }
+ }
+
+ _FORCE_INLINE_ GLuint mesh_surface_get_index_buffer(void *p_surface, uint32_t p_lod) const {
+ Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
+
+ if (p_lod == 0) {
+ return s->index_buffer;
+ } else {
+ return s->lods[p_lod - 1].index_buffer;
+ }
+ }
+
+ // Use this to cache Vertex Array Objects so they are only generated once
+ _FORCE_INLINE_ void mesh_surface_get_vertex_arrays_and_format(void *p_surface, uint32_t p_input_mask, GLuint &r_vertex_array_gl) {
+ Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface);
+
+ s->version_lock.lock();
+
+ //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way
+
+ for (uint32_t i = 0; i < s->version_count; i++) {
+ if (s->versions[i].input_mask != p_input_mask) {
+ continue;
+ }
+ //we have this version, hooray
+ r_vertex_array_gl = s->versions[i].vertex_array;
+ s->version_lock.unlock();
+ return;
+ }
+
+ uint32_t version = s->version_count;
+ s->version_count++;
+ s->versions = (Mesh::Surface::Version *)memrealloc(s->versions, sizeof(Mesh::Surface::Version) * s->version_count);
+
+ _mesh_surface_generate_version_for_input_mask(s->versions[version], s, p_input_mask);
+
+ r_vertex_array_gl = s->versions[version].vertex_array;
+
+ s->version_lock.unlock();
+ }
+
/* MESH INSTANCE API */
virtual RID mesh_instance_create(RID p_base) override;
@@ -92,45 +395,41 @@ public:
virtual void mesh_instance_check_for_update(RID p_mesh_instance) override;
virtual void update_mesh_instances() override;
- /* MULTIMESH API */
+ _FORCE_INLINE_ void mesh_instance_surface_get_vertex_arrays_and_format(RID p_mesh_instance, uint32_t p_surface_index, uint32_t p_input_mask, GLuint &r_vertex_array_gl) {
+ MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance);
+ ERR_FAIL_COND(!mi);
+ Mesh *mesh = mi->mesh;
+ ERR_FAIL_UNSIGNED_INDEX(p_surface_index, mesh->surface_count);
- struct MultiMesh {
- RID mesh;
- int instances = 0;
- RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D;
- bool uses_colors = false;
- bool uses_custom_data = false;
- int visible_instances = -1;
- AABB aabb;
- bool aabb_dirty = false;
- bool buffer_set = false;
- uint32_t stride_cache = 0;
- uint32_t color_offset_cache = 0;
- uint32_t custom_data_offset_cache = 0;
+ MeshInstance::Surface *mis = &mi->surfaces[p_surface_index];
+ Mesh::Surface *s = mesh->surfaces[p_surface_index];
- Vector<float> data_cache; //used if individual setting is used
- bool *data_cache_dirty_regions = nullptr;
- uint32_t data_cache_used_dirty_regions = 0;
+ s->version_lock.lock();
- RID buffer; //storage buffer
- RID uniform_set_3d;
- RID uniform_set_2d;
+ //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way
- bool dirty = false;
- MultiMesh *dirty_list = nullptr;
+ for (uint32_t i = 0; i < mis->version_count; i++) {
+ if (mis->versions[i].input_mask != p_input_mask) {
+ continue;
+ }
+ //we have this version, hooray
+ r_vertex_array_gl = mis->versions[i].vertex_array;
+ s->version_lock.unlock();
+ return;
+ }
- RendererStorage::Dependency dependency;
- };
+ uint32_t version = mis->version_count;
+ mis->version_count++;
+ mis->versions = (Mesh::Surface::Version *)memrealloc(mis->versions, sizeof(Mesh::Surface::Version) * mis->version_count);
- mutable RID_Owner<MultiMesh, true> multimesh_owner;
+ _mesh_surface_generate_version_for_input_mask(mis->versions[version], s, p_input_mask, mis);
- MultiMesh *multimesh_dirty_list = nullptr;
+ r_vertex_array_gl = mis->versions[version].vertex_array;
- _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const;
- _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb);
- _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb);
- _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances);
- void _update_dirty_multimeshes();
+ s->version_lock.unlock();
+ }
+
+ /* MULTIMESH API */
virtual RID multimesh_allocate() override;
virtual void multimesh_initialize(RID p_rid) override;
@@ -157,6 +456,8 @@ public:
virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override;
virtual int multimesh_get_visible_instances(RID p_multimesh) const override;
+ void _update_dirty_multimeshes();
+
_FORCE_INLINE_ RS::MultimeshTransformFormat multimesh_get_transform_format(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh);
return multimesh->xform_format;
diff --git a/drivers/gles3/storage/texture_storage.cpp b/drivers/gles3/storage/texture_storage.cpp
index 2a63c7ccad..6f2dc391d8 100644
--- a/drivers/gles3/storage/texture_storage.cpp
+++ b/drivers/gles3/storage/texture_storage.cpp
@@ -41,87 +41,152 @@ TextureStorage *TextureStorage::get_singleton() {
return singleton;
}
+static const GLenum _cube_side_enum[6] = {
+ GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
+ GL_TEXTURE_CUBE_MAP_POSITIVE_X,
+ GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
+ GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
+ GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
+ GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
+};
+
TextureStorage::TextureStorage() {
singleton = this;
system_fbo = 0;
- frame.count = 0;
- frame.delta = 0;
frame.current_rt = nullptr;
- frame.clear_request = false;
- Config *config = Config::get_singleton();
+ { //create default textures
+ { // White Textures
- //determine formats for depth textures (or renderbuffers)
- if (config->support_depth_texture) {
- // Will use texture for depth
- // have to manually see if we can create a valid framebuffer texture using UNSIGNED_INT,
- // as there is no extension to test for this.
- GLuint fbo;
- glGenFramebuffers(1, &fbo);
- glBindFramebuffer(GL_FRAMEBUFFER, fbo);
- GLuint depth;
- glGenTextures(1, &depth);
- glBindTexture(GL_TEXTURE_2D, depth);
- glTexImage2D(GL_TEXTURE_2D, 0, config->depth_internalformat, 32, 32, 0, GL_DEPTH_COMPONENT, config->depth_type, nullptr);
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(1, 1, 1, 1));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ default_gl_textures[DEFAULT_GL_TEXTURE_WHITE] = texture_allocate();
+ texture_2d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_WHITE], image);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
+ Vector<Ref<Image>> images;
+ images.push_back(image);
- GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+ default_gl_textures[DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE] = texture_allocate();
+ texture_2d_layered_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE], images, RS::TEXTURE_LAYERED_2D_ARRAY);
- glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
- glDeleteFramebuffers(1, &fbo);
- glBindTexture(GL_TEXTURE_2D, 0);
- glDeleteTextures(1, &depth);
+ for (int i = 0; i < 3; i++) {
+ images.push_back(image);
+ }
- if (status != GL_FRAMEBUFFER_COMPLETE) {
- // If it fails, test to see if it supports a framebuffer texture using UNSIGNED_SHORT
- // This is needed because many OSX devices don't support either UNSIGNED_INT or UNSIGNED_SHORT
-#ifdef GLES_OVER_GL
- config->depth_internalformat = GL_DEPTH_COMPONENT16;
-#else
- // OES_depth_texture extension only specifies GL_DEPTH_COMPONENT.
- config->depth_internalformat = GL_DEPTH_COMPONENT;
-#endif
- config->depth_type = GL_UNSIGNED_SHORT;
+ default_gl_textures[DEFAULT_GL_TEXTURE_3D_WHITE] = texture_allocate();
+ texture_3d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_3D_WHITE], image->get_format(), 4, 4, 4, false, images);
- glGenFramebuffers(1, &fbo);
- glBindFramebuffer(GL_FRAMEBUFFER, fbo);
+ for (int i = 0; i < 2; i++) {
+ images.push_back(image);
+ }
- glGenTextures(1, &depth);
- glBindTexture(GL_TEXTURE_2D, depth);
- glTexImage2D(GL_TEXTURE_2D, 0, config->depth_internalformat, 32, 32, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, nullptr);
+ default_gl_textures[DEFAULT_GL_TEXTURE_CUBEMAP_WHITE] = texture_allocate();
+ texture_2d_layered_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_CUBEMAP_WHITE], images, RS::TEXTURE_LAYERED_CUBEMAP);
+ }
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ { // black
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(0, 0, 0, 1));
+
+ default_gl_textures[DEFAULT_GL_TEXTURE_BLACK] = texture_allocate();
+ texture_2d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_BLACK], image);
+
+ Vector<Ref<Image>> images;
+
+ for (int i = 0; i < 4; i++) {
+ images.push_back(image);
+ }
+
+ default_gl_textures[DEFAULT_GL_TEXTURE_3D_BLACK] = texture_allocate();
+ texture_3d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_3D_BLACK], image->get_format(), 4, 4, 4, false, images);
+
+ for (int i = 0; i < 2; i++) {
+ images.push_back(image);
+ }
+ default_gl_textures[DEFAULT_GL_TEXTURE_CUBEMAP_BLACK] = texture_allocate();
+ texture_2d_layered_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_CUBEMAP_BLACK], images, RS::TEXTURE_LAYERED_CUBEMAP);
+ }
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
+ {
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(0.5, 0.5, 1, 1));
+
+ default_gl_textures[DEFAULT_GL_TEXTURE_NORMAL] = texture_allocate();
+ texture_2d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_NORMAL], image);
+ }
+
+ {
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(1.0, 0.5, 1, 1));
+
+ default_gl_textures[DEFAULT_GL_TEXTURE_ANISO] = texture_allocate();
+ texture_2d_initialize(default_gl_textures[DEFAULT_GL_TEXTURE_ANISO], image);
+ }
+
+ {
+ unsigned char pixel_data[4 * 4 * 4];
+ for (int i = 0; i < 16; i++) {
+ pixel_data[i * 4 + 0] = 0;
+ pixel_data[i * 4 + 1] = 0;
+ pixel_data[i * 4 + 2] = 0;
+ pixel_data[i * 4 + 3] = 0;
+ }
- status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- if (status != GL_FRAMEBUFFER_COMPLETE) {
- //if it fails again depth textures aren't supported, use rgba shadows and renderbuffer for depth
- config->support_depth_texture = false;
- config->use_rgba_3d_shadows = true;
+ default_gl_textures[DEFAULT_GL_TEXTURE_2D_UINT] = texture_allocate();
+ Texture texture;
+ texture.width = 4;
+ texture.height = 4;
+ texture.format = Image::FORMAT_RGBA8;
+ texture.type = Texture::TYPE_2D;
+ texture.target = GL_TEXTURE_2D;
+ texture.active = true;
+ glGenTextures(1, &texture.tex_id);
+ texture_owner.initialize_rid(default_gl_textures[DEFAULT_GL_TEXTURE_2D_UINT], texture);
+
+ glBindTexture(GL_TEXTURE_2D, texture.tex_id);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8UI, 4, 4, 0, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, pixel_data);
+ texture.gl_set_filter(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST);
+ }
+ {
+ uint16_t pixel_data[4 * 4];
+ for (int i = 0; i < 16; i++) {
+ pixel_data[i] = Math::make_half_float(1.0f);
}
- glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
- glDeleteFramebuffers(1, &fbo);
- glBindTexture(GL_TEXTURE_2D, 0);
- glDeleteTextures(1, &depth);
+ default_gl_textures[DEFAULT_GL_TEXTURE_DEPTH] = texture_allocate();
+ Texture texture;
+ texture.width = 4;
+ texture.height = 4;
+ texture.format = Image::FORMAT_RGBA8;
+ texture.type = Texture::TYPE_2D;
+ texture.target = GL_TEXTURE_2D;
+ texture.active = true;
+ glGenTextures(1, &texture.tex_id);
+ texture_owner.initialize_rid(default_gl_textures[DEFAULT_GL_TEXTURE_DEPTH], texture);
+
+ glBindTexture(GL_TEXTURE_2D, texture.tex_id);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 4, 4, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, pixel_data);
+ texture.gl_set_filter(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST);
}
}
}
TextureStorage::~TextureStorage() {
singleton = nullptr;
+ for (int i = 0; i < DEFAULT_GL_TEXTURE_MAX; i++) {
+ texture_free(default_gl_textures[i]);
+ }
}
void TextureStorage::set_main_thread_id(Thread::ID p_id) {
@@ -189,15 +254,6 @@ void TextureStorage::canvas_texture_set_texture_repeat(RID p_canvas_texture, RS:
/* Texture API */
-static const GLenum _cube_side_enum[6] = {
- GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
- GL_TEXTURE_CUBE_MAP_POSITIVE_X,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
-};
-
Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, Image::Format p_format, uint32_t p_flags, Image::Format &r_real_format, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool p_force_decompress) const {
Config *config = Config::get_singleton();
r_gl_format = 0;
@@ -547,251 +603,152 @@ Ref<Image> TextureStorage::_get_gl_image_and_format(const Ref<Image> &p_image, I
return p_image;
}
-void TextureStorage::_texture_set_state_from_flags(Texture *p_tex) {
- // Config *config = Config::get_singleton();
-
- if ((p_tex->flags & TEXTURE_FLAG_MIPMAPS) && !p_tex->ignore_mipmaps) {
- if (p_tex->flags & TEXTURE_FLAG_FILTER) {
- // these do not exactly correspond ...
- p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS);
- //texture->glTexParam_MinFilter(texture->target, config->use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
- } else {
- p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS);
- //texture->glTexParam_MinFilter(texture->target, config->use_fast_texture_filter ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR);
- }
- } else {
- if (p_tex->flags & TEXTURE_FLAG_FILTER) {
- p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR);
- //texture->glTexParam_MinFilter(texture->target, GL_LINEAR);
- } else {
- p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST);
- //texture->glTexParam_MinFilter(texture->target, GL_NEAREST);
- }
- }
-
- if (((p_tex->flags & TEXTURE_FLAG_REPEAT) || (p_tex->flags & TEXTURE_FLAG_MIRRORED_REPEAT)) && p_tex->target != GL_TEXTURE_CUBE_MAP) {
- if (p_tex->flags & TEXTURE_FLAG_MIRRORED_REPEAT) {
- p_tex->GLSetRepeat(p_tex->target, RS::CANVAS_ITEM_TEXTURE_REPEAT_MIRROR);
- } else {
- p_tex->GLSetRepeat(p_tex->target, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
- }
- } else {
- p_tex->GLSetRepeat(p_tex->target, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
- }
+RID TextureStorage::texture_allocate() {
+ return texture_owner.allocate_rid();
}
-void TextureStorage::_texture_allocate_internal(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, RenderingDevice::TextureType p_type, uint32_t p_flags) {
- // GLenum format;
- // GLenum internal_format;
- // GLenum type;
+void TextureStorage::texture_free(RID p_texture) {
+ Texture *t = texture_owner.get_or_null(p_texture);
+ ERR_FAIL_COND(!t);
+ ERR_FAIL_COND(t->is_render_target);
- // bool compressed = false;
-
- // Config *config = Config::get_singleton();
-
- if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) {
- p_flags &= ~TEXTURE_FLAG_MIPMAPS; // no mipies for video
+ if (t->canvas_texture) {
+ memdelete(t->canvas_texture);
}
- Texture *texture = texture_owner.get_or_null(p_texture);
- ERR_FAIL_COND(!texture);
- texture->width = p_width;
- texture->height = p_height;
- texture->format = p_format;
- texture->flags = p_flags;
- texture->stored_cube_sides = 0;
- texture->type = p_type;
-
- switch (p_type) {
- case RenderingDevice::TEXTURE_TYPE_2D: {
- texture->target = GL_TEXTURE_2D;
- texture->images.resize(1);
- } break;
- // case RenderingDevice::TEXTURE_TYPE_EXTERNAL: {
- //#ifdef ANDROID_ENABLED
- // texture->target = _GL_TEXTURE_EXTERNAL_OES;
- //#else
- // texture->target = GL_TEXTURE_2D;
- //#endif
- // texture->images.resize(0);
- // } break;
- case RenderingDevice::TEXTURE_TYPE_CUBE: {
- texture->target = GL_TEXTURE_CUBE_MAP;
- texture->images.resize(6);
- } break;
- case RenderingDevice::TEXTURE_TYPE_2D_ARRAY:
- case RenderingDevice::TEXTURE_TYPE_3D: {
- texture->target = GL_TEXTURE_3D;
- ERR_PRINT("3D textures and Texture Arrays are not supported in OpenGL. Please switch to the Vulkan backend.");
- return;
- } break;
- default: {
- ERR_PRINT("Unknown texture type!");
- return;
- }
+ if (t->tex_id != 0) {
+ glDeleteTextures(1, &t->tex_id);
+ t->tex_id = 0;
}
-#if 0
- // if (p_type != RS::TEXTURE_TYPE_EXTERNAL) {
- if (p_type == RenderingDevice::TEXTURE_TYPE_2D) {
- texture->alloc_width = texture->width;
- texture->alloc_height = texture->height;
- texture->resize_to_po2 = false;
- if (!config->support_npot_repeat_mipmap) {
- int po2_width = next_power_of_2(p_width);
- int po2_height = next_power_of_2(p_height);
-
- bool is_po2 = p_width == po2_width && p_height == po2_height;
-
- if (!is_po2 && (p_flags & TEXTURE_FLAG_REPEAT || p_flags & TEXTURE_FLAG_MIPMAPS)) {
- if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) {
- //not supported
- ERR_PRINT("Streaming texture for non power of 2 or has mipmaps on this hardware: " + texture->path + "'. Mipmaps and repeat disabled.");
- texture->flags &= ~(TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS);
- } else {
- texture->alloc_height = po2_height;
- texture->alloc_width = po2_width;
- texture->resize_to_po2 = true;
- }
- }
+ if (t->is_proxy && t->proxy_to.is_valid()) {
+ Texture *proxy_to = texture_owner.get_or_null(t->proxy_to);
+ if (proxy_to) {
+ proxy_to->proxies.erase(p_texture);
}
-
- GLenum format;
- GLenum internal_format;
- GLenum type;
- bool compressed = false;
-
- Image::Format real_format;
- _get_gl_image_and_format(Ref<Image>(),
- texture->format,
- texture->flags,
- real_format,
- format,
- internal_format,
- type,
- compressed,
- texture->resize_to_po2);
-
- texture->gl_format_cache = format;
- texture->gl_type_cache = type;
- texture->gl_internal_format_cache = internal_format;
- texture->data_size = 0;
- texture->mipmaps = 1;
-
- texture->compressed = compressed;
}
-#endif
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(texture->target, texture->tex_id);
-
- // if (p_type == RS::TEXTURE_TYPE_EXTERNAL) {
- // glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- // glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- // glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- // glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- // } else if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) {
- // //prealloc if video
- // glTexImage2D(texture->target, 0, internal_format, texture->alloc_width, texture->alloc_height, 0, format, type, NULL);
- // }
-
- texture->active = true;
-}
-
-RID TextureStorage::texture_create() {
- ERR_FAIL_COND_V(!_is_main_thread(), RID());
-
- Texture *texture = memnew(Texture);
- ERR_FAIL_COND_V(!texture, RID());
- glGenTextures(1, &texture->tex_id);
- texture->active = false;
- texture->total_data_size = 0;
-
- return texture_owner.make_rid(texture);
-}
-RID TextureStorage::texture_allocate() {
- RID id = texture_create();
- ERR_FAIL_COND_V(id == RID(), id);
- return id;
-}
-
-void TextureStorage::texture_free(RID p_rid) {
- Texture *t = texture_owner.get_or_null(p_rid);
+ //decal_atlas_remove_texture(p_texture);
- // can't free a render target texture
- ERR_FAIL_COND(t->render_target);
- if (t->canvas_texture) {
- memdelete(t->canvas_texture);
+ for (int i = 0; i < t->proxies.size(); i++) {
+ Texture *p = texture_owner.get_or_null(t->proxies[i]);
+ ERR_CONTINUE(!p);
+ p->proxy_to = RID();
+ p->tex_id = 0;
}
- // info.texture_mem -= t->total_data_size; // TODO make this work again!!
- texture_owner.free(p_rid);
- memdelete(t);
+ texture_owner.free(p_texture);
}
void TextureStorage::texture_2d_initialize(RID p_texture, const Ref<Image> &p_image) {
- Texture *tex = texture_owner.get_or_null(p_texture);
- ERR_FAIL_COND(!tex);
-
- int w = p_image->get_width();
- int h = p_image->get_height();
-
- _texture_allocate_internal(p_texture, w, h, 1, p_image->get_format(), RenderingDevice::TEXTURE_TYPE_2D, 0);
+ Texture texture;
+ texture.width = p_image->get_width();
+ texture.height = p_image->get_height();
+ texture.format = p_image->get_format();
+ texture.type = Texture::TYPE_2D;
+ texture.target = GL_TEXTURE_2D;
+ texture.image_cache_2d = p_image; //TODO, remove this once texture_2d_get is implemented
+ texture.active = true;
+ glGenTextures(1, &texture.tex_id);
+ texture_owner.initialize_rid(p_texture, texture);
texture_set_data(p_texture, p_image);
}
void TextureStorage::texture_2d_layered_initialize(RID p_texture, const Vector<Ref<Image>> &p_layers, RS::TextureLayeredType p_layered_type) {
+ texture_owner.initialize_rid(p_texture, Texture());
}
void TextureStorage::texture_3d_initialize(RID p_texture, Image::Format, int p_width, int p_height, int p_depth, bool p_mipmaps, const Vector<Ref<Image>> &p_data) {
+ texture_owner.initialize_rid(p_texture, Texture());
}
+// Called internally when texture_proxy_create(p_base) is called.
+// Note: p_base is the root and p_texture is the proxy.
void TextureStorage::texture_proxy_initialize(RID p_texture, RID p_base) {
- texture_set_proxy(p_texture, p_base);
+ Texture *texture = texture_owner.get_or_null(p_base);
+ ERR_FAIL_COND(!texture);
+ Texture proxy_tex;
+ proxy_tex.copy_from(*texture);
+ proxy_tex.proxy_to = p_base;
+ proxy_tex.is_render_target = false;
+ proxy_tex.is_proxy = true;
+ proxy_tex.proxies.clear();
+ texture->proxies.push_back(p_texture);
+ texture_owner.initialize_rid(p_texture, proxy_tex);
}
-//RID TextureStorage::texture_2d_create(const Ref<Image> &p_image) {
-// RID id = texture_create();
-// ERR_FAIL_COND_V(id == RID(), id);
-
-// int w = p_image->get_width();
-// int h = p_image->get_height();
-
-// texture_allocate(id, w, h, 1, p_image->get_format(), RenderingDevice::TEXTURE_TYPE_2D, 0);
-
-// texture_set_data(id, p_image);
-
-// return id;
-//}
-
-//RID TextureStorage::texture_2d_layered_create(const Vector<Ref<Image>> &p_layers, RS::TextureLayeredType p_layered_type) {
-// return RID();
-//}
-
-//void TextureStorage::texture_2d_update_immediate(RID p_texture, const Ref<Image> &p_image, int p_layer) {
-// // only 1 layer so far
-// texture_set_data(p_texture, p_image);
-//}
-
void TextureStorage::texture_2d_update(RID p_texture, const Ref<Image> &p_image, int p_layer) {
// only 1 layer so far
texture_set_data(p_texture, p_image);
+#ifdef TOOLS_ENABLED
+ Texture *tex = texture_owner.get_or_null(p_texture);
+
+ tex->image_cache_2d.unref();
+#endif
+}
+
+void TextureStorage::texture_proxy_update(RID p_texture, RID p_proxy_to) {
}
void TextureStorage::texture_2d_placeholder_initialize(RID p_texture) {
+ //this could be better optimized to reuse an existing image , done this way
+ //for now to get it working
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(1, 0, 1, 1));
+
+ texture_2d_initialize(p_texture, image);
}
void TextureStorage::texture_2d_layered_placeholder_initialize(RID p_texture, RenderingServer::TextureLayeredType p_layered_type) {
+ //this could be better optimized to reuse an existing image , done this way
+ //for now to get it working
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(1, 0, 1, 1));
+
+ Vector<Ref<Image>> images;
+ if (p_layered_type == RS::TEXTURE_LAYERED_2D_ARRAY) {
+ images.push_back(image);
+ } else {
+ //cube
+ for (int i = 0; i < 6; i++) {
+ images.push_back(image);
+ }
+ }
+
+ texture_2d_layered_initialize(p_texture, images, p_layered_type);
}
void TextureStorage::texture_3d_placeholder_initialize(RID p_texture) {
+ //this could be better optimized to reuse an existing image , done this way
+ //for now to get it working
+ Ref<Image> image;
+ image.instantiate();
+ image->create(4, 4, false, Image::FORMAT_RGBA8);
+ image->fill(Color(1, 0, 1, 1));
+
+ Vector<Ref<Image>> images;
+ //cube
+ for (int i = 0; i < 4; i++) {
+ images.push_back(image);
+ }
+
+ texture_3d_initialize(p_texture, Image::FORMAT_RGBA8, 4, 4, 4, false, images);
}
Ref<Image> TextureStorage::texture_2d_get(RID p_texture) const {
Texture *tex = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND_V(!tex, Ref<Image>());
+#ifdef TOOLS_ENABLED
+ if (tex->image_cache_2d.is_valid() && !tex->is_render_target) {
+ return tex->image_cache_2d;
+ }
+#endif
+
/*
#ifdef TOOLS_ENABLED
if (tex->image_cache_2d.is_valid()) {
@@ -814,39 +771,70 @@ Ref<Image> TextureStorage::texture_2d_get(RID p_texture) const {
}
#endif
*/
- ERR_FAIL_COND_V(!tex->images.size(), Ref<Image>());
- return tex->images[0];
+ /*
+ #ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint() && !tex->is_render_target) {
+ tex->image_cache_2d = image;
+ }
+ #endif
+ */
// return image;
- // return Ref<Image>();
+ return Ref<Image>();
}
void TextureStorage::texture_replace(RID p_texture, RID p_by_texture) {
Texture *tex_to = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND(!tex_to);
+ ERR_FAIL_COND(tex_to->is_proxy); //can't replace proxy
Texture *tex_from = texture_owner.get_or_null(p_by_texture);
ERR_FAIL_COND(!tex_from);
+ ERR_FAIL_COND(tex_from->is_proxy); //can't replace proxy
+
+ if (tex_to == tex_from) {
+ return;
+ }
+
+ if (tex_to->canvas_texture) {
+ memdelete(tex_to->canvas_texture);
+ tex_to->canvas_texture = nullptr;
+ }
+
+ if (tex_to->tex_id) {
+ glDeleteTextures(1, &tex_to->tex_id);
+ tex_to->tex_id = 0;
+ }
+
+ Vector<RID> proxies_to_update = tex_to->proxies;
+ Vector<RID> proxies_to_redirect = tex_from->proxies;
- tex_to->destroy();
tex_to->copy_from(*tex_from);
- // copy image data and upload to GL
- tex_to->images.resize(tex_from->images.size());
+ tex_to->proxies = proxies_to_update; //restore proxies, so they can be updated
- for (int n = 0; n < tex_from->images.size(); n++) {
- texture_set_data(p_texture, tex_from->images[n], n);
+ if (tex_to->canvas_texture) {
+ tex_to->canvas_texture->diffuse = p_texture; //update
}
- texture_free(p_by_texture);
+ for (int i = 0; i < proxies_to_update.size(); i++) {
+ texture_proxy_update(proxies_to_update[i], p_texture);
+ }
+ for (int i = 0; i < proxies_to_redirect.size(); i++) {
+ texture_proxy_update(proxies_to_redirect[i], p_texture);
+ }
+ //delete last, so proxies can be updated
+ texture_owner.free(p_by_texture);
+
+ //decal_atlas_mark_dirty_on_texture(p_texture);
}
void TextureStorage::texture_set_size_override(RID p_texture, int p_width, int p_height) {
Texture *texture = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND(!texture);
- ERR_FAIL_COND(texture->render_target);
+ ERR_FAIL_COND(texture->is_render_target);
ERR_FAIL_COND(p_width <= 0 || p_width > 16384);
ERR_FAIL_COND(p_height <= 0 || p_height > 16384);
@@ -873,8 +861,8 @@ void TextureStorage::texture_set_detect_3d_callback(RID p_texture, RS::TextureDe
Texture *texture = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND(!texture);
- texture->detect_3d = p_callback;
- texture->detect_3d_ud = p_userdata;
+ texture->detect_3d_callback = p_callback;
+ texture->detect_3d_callback_ud = p_userdata;
}
void TextureStorage::texture_set_detect_srgb_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata) {
@@ -889,8 +877,16 @@ void TextureStorage::texture_set_detect_normal_callback(RID p_texture, RS::Textu
Texture *texture = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND(!texture);
- texture->detect_normal = p_callback;
- texture->detect_normal_ud = p_userdata;
+ texture->detect_normal_callback = p_callback;
+ texture->detect_normal_callback_ud = p_userdata;
+}
+
+void TextureStorage::texture_set_detect_roughness_callback(RID p_texture, RS::TextureDetectRoughnessCallback p_callback, void *p_userdata) {
+ Texture *texture = texture_owner.get_or_null(p_texture);
+ ERR_FAIL_COND(!texture);
+
+ texture->detect_roughness_callback = p_callback;
+ texture->detect_roughness_callback_ud = p_userdata;
}
void TextureStorage::texture_debug_usage(List<RS::TextureInfo> *r_info) {
@@ -923,55 +919,24 @@ void TextureStorage::texture_set_force_redraw_if_visible(RID p_texture, bool p_e
Size2 TextureStorage::texture_size_with_proxy(RID p_texture) {
const Texture *texture = texture_owner.get_or_null(p_texture);
ERR_FAIL_COND_V(!texture, Size2());
- if (texture->proxy) {
- return Size2(texture->proxy->width, texture->proxy->height);
+ if (texture->is_proxy) {
+ const Texture *proxy = texture_owner.get_or_null(texture->proxy_to);
+ return Size2(proxy->width, proxy->height);
} else {
return Size2(texture->width, texture->height);
}
}
-// example use in 3.2
-// VS::get_singleton()->texture_set_proxy(default_texture->proxy, texture_rid);
-
-// p_proxy is the source (pre-existing) texture?
-// and p_texture is the one that is being made into a proxy?
-//This naming is confusing. Comments!!!
-
-// The naming of the parameters seemed to be reversed?
-// The p_proxy is the source texture
-// and p_texture is actually the proxy????
-
-void TextureStorage::texture_set_proxy(RID p_texture, RID p_proxy) {
- Texture *texture = texture_owner.get_or_null(p_texture);
- ERR_FAIL_COND(!texture);
-
- if (texture->proxy) {
- texture->proxy->proxy_owners.erase(texture);
- texture->proxy = nullptr;
- }
-
- if (p_proxy.is_valid()) {
- Texture *proxy = texture_owner.get_or_null(p_proxy);
- ERR_FAIL_COND(!proxy);
- ERR_FAIL_COND(proxy == texture);
- proxy->proxy_owners.insert(texture);
- texture->proxy = proxy;
- }
-}
-
void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image, int p_layer) {
- Config *config = Config::get_singleton();
Texture *texture = texture_owner.get_or_null(p_texture);
- ERR_FAIL_COND(!_is_main_thread());
-
ERR_FAIL_COND(!texture);
if (texture->target == GL_TEXTURE_3D) {
// Target is set to a 3D texture or array texture, exit early to avoid spamming errors
return;
}
ERR_FAIL_COND(!texture->active);
- ERR_FAIL_COND(texture->render_target);
+ ERR_FAIL_COND(texture->is_render_target);
ERR_FAIL_COND(p_image.is_null());
ERR_FAIL_COND(texture->format != p_image->get_format());
@@ -985,14 +950,10 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
GLenum internal_format;
bool compressed = false;
- if (config->keep_original_textures && !(texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING)) {
- texture->images.write[p_layer] = p_image;
- }
-
// print_line("texture_set_data width " + itos (p_image->get_width()) + " height " + itos(p_image->get_height()));
Image::Format real_format;
- Ref<Image> img = _get_gl_image_and_format(p_image, p_image->get_format(), texture->flags, real_format, format, internal_format, type, compressed, texture->resize_to_po2);
+ Ref<Image> img = _get_gl_image_and_format(p_image, p_image->get_format(), 0, real_format, format, internal_format, type, compressed, texture->resize_to_po2);
if (texture->resize_to_po2) {
if (p_image->is_compressed()) {
@@ -1005,29 +966,16 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
img->resize_to_po2(false);
}
- if (config->shrink_textures_x2 && (p_image->has_mipmaps() || !p_image->is_compressed()) && !(texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING)) {
- texture->alloc_height = MAX(1, texture->alloc_height / 2);
- texture->alloc_width = MAX(1, texture->alloc_width / 2);
-
- if (texture->alloc_width == img->get_width() / 2 && texture->alloc_height == img->get_height() / 2) {
- img->shrink_x2();
- } else if (img->get_format() <= Image::FORMAT_RGBA8) {
- img->resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR);
- }
- }
-
GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_layer] : GL_TEXTURE_2D;
- texture->data_size = img->get_data().size();
Vector<uint8_t> read = img->get_data();
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
- texture->ignore_mipmaps = compressed && !img->has_mipmaps();
-
- // set filtering and repeat state
- _texture_set_state_from_flags(texture);
+ // set filtering and repeat state to default
+ texture->gl_set_filter(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST);
+ texture->gl_set_repeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
//set swizle for older format compatibility
#ifdef GLES_OVER_GL
@@ -1055,7 +1003,7 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
}
#endif
- int mipmaps = ((texture->flags & TEXTURE_FLAG_MIPMAPS) && img->has_mipmaps()) ? img->get_mipmap_count() + 1 : 1;
+ int mipmaps = img->has_mipmaps() ? img->get_mipmap_count() + 1 : 1;
int w = img->get_width();
int h = img->get_height();
@@ -1075,11 +1023,7 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
glCompressedTexImage2D(blit_target, i, internal_format, bw, bh, 0, size, &read[ofs]);
} else {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- if (texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING) {
- glTexSubImage2D(blit_target, i, 0, 0, w, h, format, type, &read[ofs]);
- } else {
- glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
- }
+ glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
}
tsize += size;
@@ -1096,17 +1040,16 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
texture->stored_cube_sides |= (1 << p_layer);
- if ((texture->flags & TEXTURE_FLAG_MIPMAPS) && mipmaps == 1 && !texture->ignore_mipmaps && (texture->type != RenderingDevice::TEXTURE_TYPE_CUBE || texture->stored_cube_sides == (1 << 6) - 1)) {
- //generate mipmaps if they were requested and the image does not contain them
- glGenerateMipmap(texture->target);
- }
+ //if ((texture->flags & TEXTURE_FLAG_MIPMAPS) && mipmaps == 1 && !texture->ignore_mipmaps && (texture->type != RenderingDevice::TEXTURE_TYPE_CUBE || texture->stored_cube_sides == (1 << 6) - 1)) {
+ //generate mipmaps if they were requested and the image does not contain them
+ // glGenerateMipmap(texture->target);
+ //}
texture->mipmaps = mipmaps;
}
void TextureStorage::texture_set_data_partial(RID p_texture, const Ref<Image> &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_layer) {
- // TODO
- ERR_PRINT("Not implemented (ask Karroffel to do it :p)");
+ ERR_PRINT("Not implemented yet, sorry :(");
}
/*
@@ -1117,9 +1060,6 @@ Ref<Image> TextureStorage::texture_get_data(RID p_texture, int p_layer) const {
ERR_FAIL_COND_V(!texture->active, Ref<Image>());
ERR_FAIL_COND_V(texture->data_size == 0 && !texture->render_target, Ref<Image>());
- if (texture->type == RS::TEXTURE_TYPE_CUBEMAP && p_layer < 6 && p_layer >= 0 && !texture->images[p_layer].is_null()) {
- return texture->images[p_layer];
- }
#ifdef GLES_OVER_GL
@@ -1234,35 +1174,6 @@ Ref<Image> TextureStorage::texture_get_data(RID p_texture, int p_layer) const {
}
*/
-void TextureStorage::texture_set_flags(RID p_texture, uint32_t p_flags) {
- Texture *texture = texture_owner.get_or_null(p_texture);
- ERR_FAIL_COND(!texture);
-
- bool had_mipmaps = texture->flags & TEXTURE_FLAG_MIPMAPS;
-
- texture->flags = p_flags;
-
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(texture->target, texture->tex_id);
-
- // set filtering and repeat state
- _texture_set_state_from_flags(texture);
-
- if ((texture->flags & TEXTURE_FLAG_MIPMAPS) && !texture->ignore_mipmaps) {
- if (!had_mipmaps && texture->mipmaps == 1) {
- glGenerateMipmap(texture->target);
- }
- }
-}
-
-uint32_t TextureStorage::texture_get_flags(RID p_texture) const {
- Texture *texture = texture_owner.get_or_null(p_texture);
-
- ERR_FAIL_COND_V(!texture, 0);
-
- return texture->flags;
-}
-
Image::Format TextureStorage::texture_get_format(RID p_texture) const {
Texture *texture = texture_owner.get_or_null(p_texture);
@@ -1271,14 +1182,6 @@ Image::Format TextureStorage::texture_get_format(RID p_texture) const {
return texture->format;
}
-RenderingDevice::TextureType TextureStorage::texture_get_type(RID p_texture) const {
- Texture *texture = texture_owner.get_or_null(p_texture);
-
- ERR_FAIL_COND_V(!texture, RenderingDevice::TEXTURE_TYPE_2D);
-
- return texture->type;
-}
-
uint32_t TextureStorage::texture_get_texid(RID p_texture) const {
Texture *texture = texture_owner.get_or_null(p_texture);
@@ -1320,18 +1223,10 @@ void TextureStorage::texture_bind(RID p_texture, uint32_t p_texture_no) {
glBindTexture(texture->target, texture->tex_id);
}
-void TextureStorage::texture_set_shrink_all_x2_on_set_data(bool p_enable) {
- Config::get_singleton()->shrink_textures_x2 = p_enable;
-}
-
RID TextureStorage::texture_create_radiance_cubemap(RID p_source, int p_resolution) const {
return RID();
}
-void TextureStorage::textures_keep_original(bool p_enable) {
- Config::get_singleton()->keep_original_textures = p_enable;
-}
-
/* DECAL API */
RID TextureStorage::decal_allocate() {
@@ -1382,32 +1277,29 @@ void TextureStorage::_set_current_render_target(RID p_render_target) {
if (rt) {
if (rt->allocate_is_dirty) {
rt->allocate_is_dirty = false;
- _render_target_allocate(rt);
+ //_clear_render_target(rt);
+ //_update_render_target(rt);
}
frame.current_rt = rt;
ERR_FAIL_COND(!rt);
- frame.clear_request = false;
- glViewport(0, 0, rt->width, rt->height);
+ glViewport(rt->position.x, rt->position.y, rt->size.x, rt->size.y);
- _dims.rt_width = rt->width;
- _dims.rt_height = rt->height;
- _dims.win_width = rt->width;
- _dims.win_height = rt->height;
+ _dims.rt_width = rt->size.x;
+ _dims.rt_height = rt->size.y;
+ _dims.win_width = rt->size.x;
+ _dims.win_height = rt->size.y;
} else {
frame.current_rt = nullptr;
- frame.clear_request = false;
glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
}
}
-void TextureStorage::_render_target_allocate(RenderTarget *rt) {
- Config *config = Config::get_singleton();
-
+void TextureStorage::_update_render_target(RenderTarget *rt) {
// do not allocate a render target with no size
- if (rt->width <= 0 || rt->height <= 0) {
+ if (rt->size.x <= 0 || rt->size.y <= 0) {
return;
}
@@ -1417,31 +1309,13 @@ void TextureStorage::_render_target_allocate(RenderTarget *rt) {
return;
}
- GLuint color_internal_format;
- GLuint color_format;
- GLuint color_type = GL_UNSIGNED_BYTE;
- Image::Format image_format;
-
- if (rt->flags[TextureStorage::RENDER_TARGET_TRANSPARENT]) {
-#ifdef GLES_OVER_GL
- color_internal_format = GL_RGBA8;
-#else
- color_internal_format = GL_RGBA;
-#endif
- color_format = GL_RGBA;
- image_format = Image::FORMAT_RGBA8;
- } else {
-#ifdef GLES_OVER_GL
- color_internal_format = GL_RGB8;
-#else
- color_internal_format = GL_RGB;
-#endif
- color_format = GL_RGB;
- image_format = Image::FORMAT_RGB8;
- }
+ rt->color_internal_format = rt->flags[RENDER_TARGET_TRANSPARENT] ? GL_RGBA8 : GL_RGB10_A2;
+ rt->color_format = GL_RGBA;
+ rt->image_format = Image::FORMAT_RGBA8;
- rt->used_dof_blur_near = false;
- rt->mip_maps_allocated = false;
+ glDisable(GL_SCISSOR_TEST);
+ glColorMask(1, 1, 1, 1);
+ glDepthMask(GL_FALSE);
{
/* Front FBO */
@@ -1457,180 +1331,52 @@ void TextureStorage::_render_target_allocate(RenderTarget *rt) {
glGenTextures(1, &rt->color);
glBindTexture(GL_TEXTURE_2D, rt->color);
- glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, nullptr);
+ glTexImage2D(GL_TEXTURE_2D, 0, rt->color_internal_format, rt->size.x, rt->size.y, 0, rt->color_format, rt->color_type, nullptr);
- if (texture->flags & TEXTURE_FLAG_FILTER) {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- } else {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- }
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
- // depth
-
- if (config->support_depth_texture) {
- glGenTextures(1, &rt->depth);
- glBindTexture(GL_TEXTURE_2D, rt->depth);
- glTexImage2D(GL_TEXTURE_2D, 0, config->depth_internalformat, rt->width, rt->height, 0, GL_DEPTH_COMPONENT, config->depth_type, nullptr);
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0);
- } else {
- glGenRenderbuffers(1, &rt->depth);
- glBindRenderbuffer(GL_RENDERBUFFER, rt->depth);
-
- glRenderbufferStorage(GL_RENDERBUFFER, config->depth_buffer_internalformat, rt->width, rt->height);
-
- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth);
- }
-
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
glDeleteFramebuffers(1, &rt->fbo);
- if (config->support_depth_texture) {
- glDeleteTextures(1, &rt->depth);
- } else {
- glDeleteRenderbuffers(1, &rt->depth);
- }
-
glDeleteTextures(1, &rt->color);
rt->fbo = 0;
- rt->width = 0;
- rt->height = 0;
+ rt->size.x = 0;
+ rt->size.y = 0;
rt->color = 0;
- rt->depth = 0;
texture->tex_id = 0;
texture->active = false;
- WARN_PRINT("Could not create framebuffer!!");
+ WARN_PRINT("Could not create render target, status: " + get_framebuffer_error(status));
return;
}
- texture->format = image_format;
- texture->gl_format_cache = color_format;
+ texture->format = rt->image_format;
+ texture->gl_format_cache = rt->color_format;
texture->gl_type_cache = GL_UNSIGNED_BYTE;
- texture->gl_internal_format_cache = color_internal_format;
+ texture->gl_internal_format_cache = rt->color_internal_format;
texture->tex_id = rt->color;
- texture->width = rt->width;
- texture->alloc_width = rt->width;
- texture->height = rt->height;
- texture->alloc_height = rt->height;
+ texture->width = rt->size.x;
+ texture->alloc_width = rt->size.x;
+ texture->height = rt->size.y;
+ texture->alloc_height = rt->size.y;
texture->active = true;
-
- texture_set_flags(rt->texture, texture->flags);
- }
-
- /* BACK FBO */
- /* For MSAA */
-
-#ifndef JAVASCRIPT_ENABLED
- if (rt->msaa >= RS::VIEWPORT_MSAA_2X && rt->msaa <= RS::VIEWPORT_MSAA_8X) {
- rt->multisample_active = true;
-
- static const int msaa_value[] = { 0, 2, 4, 8, 16 };
- int msaa = msaa_value[rt->msaa];
-
- int max_samples = 0;
- glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
- if (msaa > max_samples) {
- WARN_PRINT("MSAA must be <= GL_MAX_SAMPLES, falling-back to GL_MAX_SAMPLES = " + itos(max_samples));
- msaa = max_samples;
- }
-
- //regular fbo
- glGenFramebuffers(1, &rt->multisample_fbo);
- glBindFramebuffer(GL_FRAMEBUFFER, rt->multisample_fbo);
-
- glGenRenderbuffers(1, &rt->multisample_depth);
- glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_depth);
- glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, config->depth_buffer_internalformat, rt->width, rt->height);
-
- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->multisample_depth);
-
- glGenRenderbuffers(1, &rt->multisample_color);
- glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_color);
- glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height);
-
- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rt->multisample_color);
-
- GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
-
- if (status != GL_FRAMEBUFFER_COMPLETE) {
- // Delete allocated resources and default to no MSAA
- WARN_PRINT_ONCE("Cannot allocate back framebuffer for MSAA");
- printf("err status: %x\n", status);
- rt->multisample_active = false;
-
- glDeleteFramebuffers(1, &rt->multisample_fbo);
- rt->multisample_fbo = 0;
-
- glDeleteRenderbuffers(1, &rt->multisample_depth);
- rt->multisample_depth = 0;
-
- glDeleteRenderbuffers(1, &rt->multisample_color);
- rt->multisample_color = 0;
- }
-
- glBindRenderbuffer(GL_RENDERBUFFER, 0);
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
-
- } else
-#endif // JAVASCRIPT_ENABLED
- {
- rt->multisample_active = false;
}
glClearColor(0, 0, 0, 0);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- // copy texscreen buffers
- // if (!(rt->flags[TextureStorage::RENDER_TARGET_NO_SAMPLING])) {
- if (true) {
- glGenTextures(1, &rt->copy_screen_effect.color);
- glBindTexture(GL_TEXTURE_2D, rt->copy_screen_effect.color);
-
- if (rt->flags[TextureStorage::RENDER_TARGET_TRANSPARENT]) {
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rt->width, rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
- } else {
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rt->width, rt->height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
- }
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- glGenFramebuffers(1, &rt->copy_screen_effect.fbo);
- glBindFramebuffer(GL_FRAMEBUFFER, rt->copy_screen_effect.fbo);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->copy_screen_effect.color, 0);
-
- glClearColor(0, 0, 0, 0);
- glClear(GL_COLOR_BUFFER_BIT);
-
- GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- if (status != GL_FRAMEBUFFER_COMPLETE) {
- _render_target_clear(rt);
- ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
- }
- }
+ glClear(GL_COLOR_BUFFER_BIT);
- // Allocate mipmap chains for post_process effects
- // if (!rt->flags[RendererStorage::RENDER_TARGET_NO_3D] && rt->width >= 2 && rt->height >= 2) {
- if (rt->width >= 2 && rt->height >= 2) {
+ // Allocate mipmap chains for full screen blur
+ if (rt->size.x >= 2 && rt->size.y >= 2) {
for (int i = 0; i < 2; i++) {
ERR_FAIL_COND(rt->mip_maps[i].sizes.size());
- int w = rt->width;
- int h = rt->height;
+ int w = rt->size.x;
+ int h = rt->size.y;
if (i > 0) {
w >>= 1;
@@ -1638,8 +1384,8 @@ void TextureStorage::_render_target_allocate(RenderTarget *rt) {
}
int level = 0;
- int fb_w = w;
- int fb_h = h;
+ GLsizei width = w;
+ GLsizei height = h;
while (true) {
RenderTarget::MipMaps::Size mm;
@@ -1657,97 +1403,52 @@ void TextureStorage::_render_target_allocate(RenderTarget *rt) {
level++;
}
- GLsizei width = fb_w;
- GLsizei height = fb_h;
+ glGenTextures(1, &rt->mip_maps[i].color);
+ glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].color);
- if (config->render_to_mipmap_supported) {
- glGenTextures(1, &rt->mip_maps[i].color);
- glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].color);
-
- for (int l = 0; l < level + 1; l++) {
- glTexImage2D(GL_TEXTURE_2D, l, color_internal_format, width, height, 0, color_format, color_type, nullptr);
- width = MAX(1, (width / 2));
- height = MAX(1, (height / 2));
- }
+ for (int l = 0; l < level + 1; l++) {
+ glTexImage2D(GL_TEXTURE_2D, l, rt->color_internal_format, width, height, 0, rt->color_format, rt->color_type, nullptr);
+ width = MAX(1, (width / 2));
+ height = MAX(1, (height / 2));
+ }
#ifdef GLES_OVER_GL
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
#endif
- } else {
- // Can't render to specific levels of a mipmap in ES 2.0 or Webgl so create a texture for each level
- for (int l = 0; l < level + 1; l++) {
- glGenTextures(1, &rt->mip_maps[i].sizes.write[l].color);
- glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].sizes[l].color);
- glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, width, height, 0, color_format, color_type, nullptr);
- width = MAX(1, (width / 2));
- height = MAX(1, (height / 2));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- }
- }
-
- glDisable(GL_SCISSOR_TEST);
- glColorMask(1, 1, 1, 1);
- glDepthMask(GL_TRUE);
for (int j = 0; j < rt->mip_maps[i].sizes.size(); j++) {
RenderTarget::MipMaps::Size &mm = rt->mip_maps[i].sizes.write[j];
glGenFramebuffers(1, &mm.fbo);
- glBindFramebuffer(GL_FRAMEBUFFER, mm.fbo);
-
- if (config->render_to_mipmap_supported) {
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->mip_maps[i].color, j);
- } else {
- glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].sizes[j].color);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->mip_maps[i].sizes[j].color, 0);
- }
+ bind_framebuffer(mm.fbo);
- bool used_depth = false;
- if (j == 0 && i == 0) { //use always
- if (config->support_depth_texture) {
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0);
- } else {
- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth);
- }
- used_depth = true;
- }
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->mip_maps[i].color, j);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- WARN_PRINT_ONCE("Cannot allocate mipmaps for 3D post processing effects");
- glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
+ WARN_PRINT_ONCE("Cannot allocate mipmaps for canvas screen blur. Status: " + get_framebuffer_error(status));
+ bind_framebuffer_system();
return;
}
glClearColor(1.0, 0.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
- if (used_depth) {
- glClearDepth(1.0);
- glClear(GL_DEPTH_BUFFER_BIT);
- }
}
rt->mip_maps[i].levels = level;
- if (config->render_to_mipmap_supported) {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- }
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
rt->mip_maps_allocated = true;
}
- glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
+ bind_framebuffer_system();
}
-void TextureStorage::_render_target_clear(RenderTarget *rt) {
- Config *config = Config::get_singleton();
-
+void TextureStorage::_clear_render_target(RenderTarget *rt) {
// there is nothing to clear when DIRECT_TO_SCREEN is used
if (rt->flags[RENDER_TARGET_DIRECT_TO_SCREEN]) {
return;
@@ -1757,8 +1458,9 @@ void TextureStorage::_render_target_clear(RenderTarget *rt) {
glDeleteFramebuffers(1, &rt->fbo);
glDeleteTextures(1, &rt->color);
rt->fbo = 0;
+ rt->color = 0;
}
-
+ /*
if (rt->external.fbo != 0) {
// free this
glDeleteFramebuffers(1, &rt->external.fbo);
@@ -1775,16 +1477,7 @@ void TextureStorage::_render_target_clear(RenderTarget *rt) {
rt->external.fbo = 0;
}
-
- if (rt->depth) {
- if (config->support_depth_texture) {
- glDeleteTextures(1, &rt->depth);
- } else {
- glDeleteRenderbuffers(1, &rt->depth);
- }
-
- rt->depth = 0;
- }
+ */
Texture *tex = get_texture(rt->texture);
tex->alloc_height = 0;
@@ -1793,19 +1486,10 @@ void TextureStorage::_render_target_clear(RenderTarget *rt) {
tex->height = 0;
tex->active = false;
- if (rt->copy_screen_effect.color) {
- glDeleteFramebuffers(1, &rt->copy_screen_effect.fbo);
- rt->copy_screen_effect.fbo = 0;
-
- glDeleteTextures(1, &rt->copy_screen_effect.color);
- rt->copy_screen_effect.color = 0;
- }
-
for (int i = 0; i < 2; i++) {
if (rt->mip_maps[i].sizes.size()) {
for (int j = 0; j < rt->mip_maps[i].sizes.size(); j++) {
glDeleteFramebuffers(1, &rt->mip_maps[i].sizes[j].fbo);
- glDeleteTextures(1, &rt->mip_maps[i].sizes[j].color);
}
glDeleteTextures(1, &rt->mip_maps[i].color);
@@ -1814,86 +1498,62 @@ void TextureStorage::_render_target_clear(RenderTarget *rt) {
rt->mip_maps[i].color = 0;
}
}
+}
- if (rt->multisample_active) {
- glDeleteFramebuffers(1, &rt->multisample_fbo);
- rt->multisample_fbo = 0;
-
- glDeleteRenderbuffers(1, &rt->multisample_depth);
- rt->multisample_depth = 0;
-
- glDeleteRenderbuffers(1, &rt->multisample_color);
+RID TextureStorage::render_target_create() {
+ RenderTarget render_target;
+ //render_target.was_used = false;
+ render_target.clear_requested = false;
- rt->multisample_color = 0;
+ for (int i = 0; i < RENDER_TARGET_FLAG_MAX; i++) {
+ render_target.flags[i] = false;
}
-}
+ Texture t;
+ t.active = true;
+ t.render_target = &render_target;
+ t.is_render_target = true;
-RID TextureStorage::render_target_create() {
- RenderTarget *rt = memnew(RenderTarget);
- Texture *t = memnew(Texture);
-
- t->type = RenderingDevice::TEXTURE_TYPE_2D;
- t->flags = 0;
- t->width = 0;
- t->height = 0;
- t->alloc_height = 0;
- t->alloc_width = 0;
- t->format = Image::FORMAT_R8;
- t->target = GL_TEXTURE_2D;
- t->gl_format_cache = 0;
- t->gl_internal_format_cache = 0;
- t->gl_type_cache = 0;
- t->data_size = 0;
- t->total_data_size = 0;
- t->ignore_mipmaps = false;
- t->compressed = false;
- t->mipmaps = 1;
- t->active = true;
- t->tex_id = 0;
- t->render_target = rt;
-
- rt->texture = make_rid(t);
- return render_target_owner.make_rid(rt);
+ render_target.texture = texture_owner.make_rid(t);
+ _update_render_target(&render_target);
+ return render_target_owner.make_rid(render_target);
}
void TextureStorage::render_target_free(RID p_rid) {
RenderTarget *rt = render_target_owner.get_or_null(p_rid);
- _render_target_clear(rt);
+ _clear_render_target(rt);
Texture *t = get_texture(rt->texture);
if (t) {
+ t->is_render_target = false;
texture_free(rt->texture);
- memdelete(t);
+ //memdelete(t);
}
render_target_owner.free(p_rid);
- memdelete(rt);
}
void TextureStorage::render_target_set_position(RID p_render_target, int p_x, int p_y) {
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND(!rt);
- rt->x = p_x;
- rt->y = p_y;
+ rt->position = Point2i(p_x, p_y);
}
void TextureStorage::render_target_set_size(RID p_render_target, int p_width, int p_height, uint32_t p_view_count) {
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND(!rt);
- if (p_width == rt->width && p_height == rt->height) {
+ if (p_width == rt->size.x && p_height == rt->size.y) {
return;
}
- _render_target_clear(rt);
+ _clear_render_target(rt);
- rt->width = p_width;
- rt->height = p_height;
+ rt->size = Size2i(p_width, p_height);
// print_line("render_target_set_size " + itos(p_render_target.get_id()) + ", w " + itos(p_width) + " h " + itos(p_height));
rt->allocate_is_dirty = true;
- //_render_target_allocate(rt);
+ _update_render_target(rt);
}
// TODO: convert to Size2i internally
@@ -1901,7 +1561,7 @@ Size2i TextureStorage::render_target_get_size(RID p_render_target) {
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND_V(!rt, Size2());
- return Size2i(rt->width, rt->height);
+ return rt->size;
}
RID TextureStorage::render_target_get_texture(RID p_render_target) {
@@ -1919,8 +1579,6 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND(!rt);
- Config *config = Config::get_singleton();
-
if (p_texture_id == 0) {
if (rt->external.fbo != 0) {
// free this
@@ -1939,7 +1597,7 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
t->height = 0;
t->active = false;
texture_free(rt->external.texture);
- memdelete(t);
+ //memdelete(t);
rt->external.fbo = 0;
rt->external.color = 0;
@@ -1956,8 +1614,7 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
// allocate a texture
t = memnew(Texture);
- t->type = RenderingDevice::TEXTURE_TYPE_2D;
- t->flags = 0;
+ t->type = Texture::TYPE_2D;
t->width = 0;
t->height = 0;
t->alloc_height = 0;
@@ -1967,17 +1624,15 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
t->gl_format_cache = 0;
t->gl_internal_format_cache = 0;
t->gl_type_cache = 0;
- t->data_size = 0;
- t->compressed = false;
t->srgb = false;
t->total_data_size = 0;
- t->ignore_mipmaps = false;
t->mipmaps = 1;
t->active = true;
t->tex_id = 0;
t->render_target = rt;
+ t->is_render_target = true;
- rt->external.texture = make_rid(t);
+ //rt->external.texture = make_rid(t);
} else {
// bind our frame buffer
@@ -1992,22 +1647,15 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
rt->external.color = p_texture_id;
// size shouldn't be different
- t->width = rt->width;
- t->height = rt->height;
- t->alloc_height = rt->width;
- t->alloc_width = rt->height;
+ t->width = rt->size.x;
+ t->height = rt->size.y;
+ t->alloc_height = rt->size.x;
+ t->alloc_width = rt->size.y;
// Switch our texture on our frame buffer
{
// set our texture as the destination for our framebuffer
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, p_texture_id, 0);
-
- // seeing we're rendering into this directly, better also use our depth buffer, just use our existing one :)
- if (config->support_depth_texture) {
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0);
- } else {
- glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth);
- }
}
// check status and unbind
@@ -2015,7 +1663,7 @@ void TextureStorage::render_target_set_external_texture(RID p_render_target, uns
glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- printf("framebuffer fail, status: %x\n", status);
+ WARN_PRINT("framebuffer fail, status: " + get_framebuffer_error(status));
}
ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
@@ -2029,26 +1677,19 @@ void TextureStorage::render_target_set_flag(RID p_render_target, RenderTargetFla
// When setting DIRECT_TO_SCREEN, you need to clear before the value is set, but allocate after as
// those functions change how they operate depending on the value of DIRECT_TO_SCREEN
if (p_flag == RENDER_TARGET_DIRECT_TO_SCREEN && p_value != rt->flags[RENDER_TARGET_DIRECT_TO_SCREEN]) {
- _render_target_clear(rt);
+ _clear_render_target(rt);
rt->flags[p_flag] = p_value;
- _render_target_allocate(rt);
+ _update_render_target(rt);
}
rt->flags[p_flag] = p_value;
switch (p_flag) {
- case RENDER_TARGET_TRANSPARENT:
- /*
- case RENDER_TARGET_HDR:
- case RENDER_TARGET_NO_3D:
- case RENDER_TARGET_NO_SAMPLING:
- case RENDER_TARGET_NO_3D_EFFECTS: */
- {
- //must reset for these formats
- _render_target_clear(rt);
- _render_target_allocate(rt);
- }
- break;
+ case RENDER_TARGET_TRANSPARENT: {
+ //must reset for these formats
+ _clear_render_target(rt);
+ _update_render_target(rt);
+ } break;
default: {
}
}
@@ -2068,46 +1709,11 @@ void TextureStorage::render_target_clear_used(RID p_render_target) {
rt->used_in_frame = false;
}
-void TextureStorage::render_target_set_msaa(RID p_render_target, RS::ViewportMSAA p_msaa) {
- RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
- ERR_FAIL_COND(!rt);
-
- if (rt->msaa == p_msaa) {
- return;
- }
-
- _render_target_clear(rt);
- rt->msaa = p_msaa;
- _render_target_allocate(rt);
-}
-
-void TextureStorage::render_target_set_use_fxaa(RID p_render_target, bool p_fxaa) {
- RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
- ERR_FAIL_COND(!rt);
-
- rt->use_fxaa = p_fxaa;
-}
-
-void TextureStorage::render_target_set_use_debanding(RID p_render_target, bool p_debanding) {
- RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
- ERR_FAIL_COND(!rt);
-
- if (p_debanding) {
- WARN_PRINT_ONCE("Debanding is not supported in the OpenGL backend. Switch to the Vulkan backend and make sure HDR is enabled.");
- }
-
- rt->use_debanding = p_debanding;
-}
-
void TextureStorage::render_target_request_clear(RID p_render_target, const Color &p_clear_color) {
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND(!rt);
rt->clear_requested = true;
rt->clear_color = p_clear_color;
-
- // ERR_FAIL_COND(!frame.current_rt);
- // frame.clear_request = true;
- // frame.clear_request_color = p_color;
}
bool TextureStorage::render_target_is_clear_requested(RID p_render_target) {
@@ -2128,6 +1734,14 @@ void TextureStorage::render_target_disable_clear_request(RID p_render_target) {
}
void TextureStorage::render_target_do_clear_request(RID p_render_target) {
+ RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
+ ERR_FAIL_COND(!rt);
+ if (!rt->clear_requested) {
+ return;
+ }
+
+ glClearBufferfv(GL_COLOR, 0, rt->clear_color.components);
+ rt->clear_requested = false;
}
void TextureStorage::render_target_set_sdf_size_and_scale(RID p_render_target, RS::ViewportSDFOversize p_size, RS::ViewportSDFScale p_scale) {
diff --git a/drivers/gles3/storage/texture_storage.h b/drivers/gles3/storage/texture_storage.h
index 7a5140a290..1e1cd3f9bf 100644
--- a/drivers/gles3/storage/texture_storage.h
+++ b/drivers/gles3/storage/texture_storage.h
@@ -49,6 +49,9 @@
namespace GLES3 {
+#define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
+#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+
#define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
@@ -86,15 +89,20 @@ namespace GLES3 {
#define glClearDepth glClearDepthf
#endif //!GLES_OVER_GL
-enum OpenGLTextureFlags {
- TEXTURE_FLAG_MIPMAPS = 1, /// Enable automatic mipmap generation - when available
- TEXTURE_FLAG_REPEAT = 2, /// Repeat texture (Tiling), otherwise Clamping
- TEXTURE_FLAG_FILTER = 4, /// Create texture with linear (or available) filter
- TEXTURE_FLAG_ANISOTROPIC_FILTER = 8,
- TEXTURE_FLAG_CONVERT_TO_LINEAR = 16,
- TEXTURE_FLAG_MIRRORED_REPEAT = 32, /// Repeat texture, with alternate sections mirrored
- TEXTURE_FLAG_USED_FOR_STREAMING = 2048,
- TEXTURE_FLAGS_DEFAULT = TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS | TEXTURE_FLAG_FILTER
+enum DefaultGLTexture {
+ DEFAULT_GL_TEXTURE_WHITE,
+ DEFAULT_GL_TEXTURE_BLACK,
+ DEFAULT_GL_TEXTURE_NORMAL,
+ DEFAULT_GL_TEXTURE_ANISO,
+ DEFAULT_GL_TEXTURE_DEPTH,
+ DEFAULT_GL_TEXTURE_CUBEMAP_BLACK,
+ //DEFAULT_GL_TEXTURE_CUBEMAP_ARRAY_BLACK, // Cubemap Arrays not supported in GL 3.3 or GL ES 3.0
+ DEFAULT_GL_TEXTURE_CUBEMAP_WHITE,
+ DEFAULT_GL_TEXTURE_3D_WHITE,
+ DEFAULT_GL_TEXTURE_3D_BLACK,
+ DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE,
+ DEFAULT_GL_TEXTURE_2D_UINT,
+ DEFAULT_GL_TEXTURE_MAX
};
struct CanvasTexture {
@@ -118,99 +126,81 @@ struct RenderTarget;
struct Texture {
RID self;
- Texture *proxy = nullptr;
- Set<Texture *> proxy_owners;
+ bool is_proxy = false;
+ bool is_render_target = false;
+
+ RID proxy_to = RID();
+ Vector<RID> proxies;
String path;
- uint32_t flags;
- int width, height, depth;
- int alloc_width, alloc_height;
- Image::Format format;
- RenderingDevice::TextureType type;
+ int width = 0;
+ int height = 0;
+ int depth = 0;
+ int mipmaps = 1;
+ int layers = 1;
+ int alloc_width = 0;
+ int alloc_height = 0;
+ Image::Format format = Image::FORMAT_R8;
+
+ enum Type {
+ TYPE_2D,
+ TYPE_LAYERED,
+ TYPE_3D
+ };
- GLenum target;
- GLenum gl_format_cache;
- GLenum gl_internal_format_cache;
- GLenum gl_type_cache;
+ Type type;
+ RS::TextureLayeredType layered_type = RS::TEXTURE_LAYERED_2D_ARRAY;
- int data_size;
- int total_data_size;
- bool ignore_mipmaps;
+ GLenum target = GL_TEXTURE_2D;
+ GLenum gl_format_cache = 0;
+ GLenum gl_internal_format_cache = 0;
+ GLenum gl_type_cache = 0;
- bool compressed;
+ int total_data_size = 0;
- bool srgb;
+ bool compressed = false;
- int mipmaps;
+ bool srgb = false;
- bool resize_to_po2;
+ bool resize_to_po2 = false;
- bool active;
- GLenum tex_id;
+ bool active = false;
+ GLuint tex_id = 0;
- uint16_t stored_cube_sides;
+ uint16_t stored_cube_sides = 0;
RenderTarget *render_target = nullptr;
- Vector<Ref<Image>> images;
+ Ref<Image> image_cache_2d;
- bool redraw_if_visible;
+ bool redraw_if_visible = false;
- RS::TextureDetectCallback detect_3d;
- void *detect_3d_ud = nullptr;
+ RS::TextureDetectCallback detect_3d_callback = nullptr;
+ void *detect_3d_callback_ud = nullptr;
- RS::TextureDetectCallback detect_srgb;
+ RS::TextureDetectCallback detect_srgb = nullptr;
void *detect_srgb_ud = nullptr;
- RS::TextureDetectCallback detect_normal;
- void *detect_normal_ud = nullptr;
-
- CanvasTexture *canvas_texture = nullptr;
-
- // some silly opengl shenanigans where
- // texture coords start from bottom left, means we need to draw render target textures upside down
- // to be compatible with vulkan etc.
- bool is_upside_down() const {
- if (proxy) {
- return proxy->is_upside_down();
- }
+ RS::TextureDetectCallback detect_normal_callback = nullptr;
+ void *detect_normal_callback_ud = nullptr;
- return render_target != nullptr;
- }
-
- Texture() {
- create();
- }
+ RS::TextureDetectRoughnessCallback detect_roughness_callback = nullptr;
+ void *detect_roughness_callback_ud = nullptr;
- _ALWAYS_INLINE_ Texture *get_ptr() {
- if (proxy) {
- return proxy; //->get_ptr(); only one level of indirection, else not inlining possible.
- } else {
- return this;
- }
- }
-
- ~Texture() {
- destroy();
-
- if (tex_id != 0) {
- glDeleteTextures(1, &tex_id);
- }
- }
+ CanvasTexture *canvas_texture = nullptr;
void copy_from(const Texture &o) {
- proxy = o.proxy;
- flags = o.flags;
+ proxy_to = o.proxy_to;
+ is_proxy = o.is_proxy;
width = o.width;
height = o.height;
alloc_width = o.alloc_width;
alloc_height = o.alloc_height;
format = o.format;
type = o.type;
+ layered_type = o.layered_type;
target = o.target;
- data_size = o.data_size;
total_data_size = o.total_data_size;
- ignore_mipmaps = o.ignore_mipmaps;
compressed = o.compressed;
mipmaps = o.mipmaps;
resize_to_po2 = o.resize_to_po2;
@@ -218,102 +208,95 @@ struct Texture {
tex_id = o.tex_id;
stored_cube_sides = o.stored_cube_sides;
render_target = o.render_target;
+ is_render_target = o.is_render_target;
redraw_if_visible = o.redraw_if_visible;
- detect_3d = o.detect_3d;
- detect_3d_ud = o.detect_3d_ud;
+ detect_3d_callback = o.detect_3d_callback;
+ detect_3d_callback_ud = o.detect_3d_callback_ud;
detect_srgb = o.detect_srgb;
detect_srgb_ud = o.detect_srgb_ud;
- detect_normal = o.detect_normal;
- detect_normal_ud = o.detect_normal_ud;
-
- images.clear();
- }
-
- void create() {
- proxy = nullptr;
- flags = 0;
- width = 0;
- height = 0;
- alloc_width = 0;
- alloc_height = 0;
- format = Image::FORMAT_L8;
- type = RenderingDevice::TEXTURE_TYPE_2D;
- target = 0;
- data_size = 0;
- total_data_size = 0;
- ignore_mipmaps = false;
- compressed = false;
- mipmaps = 0;
- resize_to_po2 = false;
- active = false;
- tex_id = 0;
- stored_cube_sides = 0;
- render_target = nullptr;
- redraw_if_visible = false;
- detect_3d = nullptr;
- detect_3d_ud = nullptr;
- detect_srgb = nullptr;
- detect_srgb_ud = nullptr;
- detect_normal = nullptr;
- detect_normal_ud = nullptr;
- }
- void destroy() {
- images.clear();
-
- for (Set<Texture *>::Element *E = proxy_owners.front(); E; E = E->next()) {
- E->get()->proxy = nullptr;
- }
-
- if (proxy) {
- proxy->proxy_owners.erase(this);
- }
+ detect_normal_callback = o.detect_normal_callback;
+ detect_normal_callback_ud = o.detect_normal_callback_ud;
+ detect_roughness_callback = o.detect_roughness_callback;
+ detect_roughness_callback_ud = o.detect_roughness_callback_ud;
}
// texture state
- void GLSetFilter(GLenum p_target, RS::CanvasItemTextureFilter p_filter) {
+ void gl_set_filter(RS::CanvasItemTextureFilter p_filter) {
if (p_filter == state_filter) {
return;
}
+ Config *config = Config::get_singleton();
state_filter = p_filter;
- GLint pmin = GL_LINEAR; // param min
- GLint pmag = GL_LINEAR; // param mag
+ GLenum pmin = GL_NEAREST; // param min
+ GLenum pmag = GL_NEAREST; // param mag
+ GLint max_lod = 1000;
+ bool use_anisotropy = false;
switch (state_filter) {
- default: {
- } break;
- case RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS: {
- pmin = GL_LINEAR_MIPMAP_LINEAR;
- pmag = GL_LINEAR;
- } break;
case RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST: {
pmin = GL_NEAREST;
pmag = GL_NEAREST;
+ max_lod = 0;
} break;
+ case RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR: {
+ pmin = GL_LINEAR;
+ pmag = GL_LINEAR;
+ max_lod = 0;
+ } break;
+ case RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC: {
+ use_anisotropy = true;
+ };
+ [[fallthrough]];
case RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS: {
- pmin = GL_NEAREST_MIPMAP_NEAREST;
pmag = GL_NEAREST;
+ if (config->use_nearest_mip_filter) {
+ pmin = GL_NEAREST_MIPMAP_NEAREST;
+ } else {
+ pmin = GL_NEAREST_MIPMAP_LINEAR;
+ }
} break;
+ case RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC: {
+ use_anisotropy = true;
+ };
+ [[fallthrough]];
+ case RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS: {
+ pmag = GL_LINEAR;
+ if (config->use_nearest_mip_filter) {
+ pmin = GL_LINEAR_MIPMAP_NEAREST;
+
+ } else {
+ pmin = GL_LINEAR_MIPMAP_LINEAR;
+ }
+ } break;
+ default: {
+ } break;
+ }
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, pmin);
+ glTexParameteri(target, GL_TEXTURE_MAG_FILTER, pmag);
+ glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0);
+ glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, max_lod);
+ if (config->support_anisotropic_filter && use_anisotropy) {
+ glTexParameterf(target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config->anisotropic_level);
}
- glTexParameteri(p_target, GL_TEXTURE_MIN_FILTER, pmin);
- glTexParameteri(p_target, GL_TEXTURE_MAG_FILTER, pmag);
}
- void GLSetRepeat(GLenum p_target, RS::CanvasItemTextureRepeat p_repeat) {
+ void gl_set_repeat(RS::CanvasItemTextureRepeat p_repeat) {
if (p_repeat == state_repeat) {
return;
}
state_repeat = p_repeat;
- GLint prep = GL_CLAMP_TO_EDGE; // parameter repeat
+ GLenum prep = GL_CLAMP_TO_EDGE; // parameter repeat
switch (state_repeat) {
- default: {
- } break;
case RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED: {
prep = GL_REPEAT;
} break;
case RS::CANVAS_ITEM_TEXTURE_REPEAT_MIRROR: {
prep = GL_MIRRORED_REPEAT;
} break;
+ default: {
+ } break;
}
- glTexParameteri(p_target, GL_TEXTURE_WRAP_S, prep);
- glTexParameteri(p_target, GL_TEXTURE_WRAP_T, prep);
+ glTexParameteri(target, GL_TEXTURE_WRAP_T, prep);
+ glTexParameteri(target, GL_TEXTURE_WRAP_R, prep);
+ glTexParameteri(target, GL_TEXTURE_WRAP_S, prep);
}
private:
@@ -322,54 +305,46 @@ private:
};
struct RenderTarget {
- RID self;
- GLuint fbo = 0;
- GLuint color = 0;
- GLuint depth = 0;
-
- GLuint multisample_fbo = 0;
- GLuint multisample_color = 0;
- GLuint multisample_depth = 0;
- bool multisample_active = false;
-
- struct Effect {
- GLuint fbo = 0;
- int width = 0;
- int height = 0;
-
- GLuint color = 0;
- };
-
- Effect copy_screen_effect;
-
struct MipMaps {
struct Size {
- GLuint fbo = 0;
- GLuint color = 0;
- int width = 0;
- int height = 0;
+ GLuint fbo;
+ int width;
+ int height;
};
Vector<Size> sizes;
GLuint color = 0;
int levels = 0;
- };
- MipMaps mip_maps[2];
+ MipMaps() {
+ }
+ };
struct External {
GLuint fbo = 0;
GLuint color = 0;
GLuint depth = 0;
RID texture;
+
+ External() {
+ }
} external;
- int x = 0;
- int y = 0;
- int width = 0;
- int height = 0;
+ Point2i position = Point2i(0, 0);
+ Size2i size = Size2i(0, 0);
+ RID self;
+ GLuint fbo = 0;
+ GLuint color = 0;
+
+ GLuint color_internal_format = GL_RGBA8;
+ GLuint color_format = GL_RGBA;
+ GLuint color_type = GL_UNSIGNED_BYTE;
+ Image::Format image_format = Image::FORMAT_RGBA8;
+
+ MipMaps mip_maps[2];
+ bool mip_maps_allocated = false;
- bool flags[RendererTextureStorage::RENDER_TARGET_FLAG_MAX] = {};
+ bool flags[RendererTextureStorage::RENDER_TARGET_FLAG_MAX];
// instead of allocating sized render targets immediately,
// defer this for faster startup
@@ -377,14 +352,8 @@ struct RenderTarget {
bool used_in_frame = false;
RS::ViewportMSAA msaa = RS::VIEWPORT_MSAA_DISABLED;
- bool use_fxaa = false;
- bool use_debanding = false;
-
RID texture;
- bool used_dof_blur_near = false;
- bool mip_maps_allocated = false;
-
Color clear_color = Color(1, 1, 1, 1);
bool clear_requested = false;
@@ -392,7 +361,6 @@ struct RenderTarget {
for (int i = 0; i < RendererTextureStorage::RENDER_TARGET_FLAG_MAX; ++i) {
flags[i] = false;
}
- external.fbo = 0;
}
};
@@ -400,6 +368,8 @@ class TextureStorage : public RendererTextureStorage {
private:
static TextureStorage *singleton;
+ RID default_gl_textures[DEFAULT_GL_TEXTURE_MAX];
+
Thread::ID _main_thread_id = 0;
bool _is_main_thread();
@@ -409,16 +379,13 @@ private:
/* Texture API */
- mutable RID_PtrOwner<Texture> texture_owner;
+ mutable RID_Owner<Texture> texture_owner;
Ref<Image> _get_gl_image_and_format(const Ref<Image> &p_image, Image::Format p_format, uint32_t p_flags, Image::Format &r_real_format, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool p_force_decompress) const;
- void _texture_set_state_from_flags(Texture *p_tex);
-
- void texture_set_proxy(RID p_texture, RID p_proxy);
/* Render Target API */
- mutable RID_PtrOwner<RenderTarget> render_target_owner;
+ mutable RID_Owner<RenderTarget> render_target_owner;
// make access easier to these
struct Dimensions {
@@ -443,6 +410,10 @@ public:
TextureStorage();
virtual ~TextureStorage();
+ _FORCE_INLINE_ RID texture_gl_get_default(DefaultGLTexture p_texture) {
+ return default_gl_textures[p_texture];
+ }
+
/* Canvas Texture API */
CanvasTexture *get_canvas_texture(RID p_rid) { return canvas_texture_owner.get_or_null(p_rid); };
@@ -460,16 +431,20 @@ public:
/* Texture API */
- Texture *get_texture(RID p_rid) { return texture_owner.get_or_null(p_rid); };
+ Texture *get_texture(RID p_rid) {
+ Texture *texture = texture_owner.get_or_null(p_rid);
+ if (texture && texture->is_proxy) {
+ return texture_owner.get_or_null(texture->proxy_to);
+ }
+ return texture;
+ };
bool owns_texture(RID p_rid) { return texture_owner.owns(p_rid); };
- RID make_rid(Texture *p_texture) { return texture_owner.make_rid(p_texture); };
void set_main_thread_id(Thread::ID p_id);
virtual bool can_create_resources_async() const override;
RID texture_create();
- void _texture_allocate_internal(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, RenderingDevice::TextureType p_type, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT);
virtual RID texture_allocate() override;
virtual void texture_free(RID p_rid) override;
@@ -481,7 +456,7 @@ public:
virtual void texture_2d_update(RID p_texture, const Ref<Image> &p_image, int p_layer = 0) override;
virtual void texture_3d_update(RID p_texture, const Vector<Ref<Image>> &p_data) override{};
- virtual void texture_proxy_update(RID p_proxy, RID p_base) override{};
+ virtual void texture_proxy_update(RID p_proxy, RID p_base) override;
//these two APIs can be used together or in combination with the others.
virtual void texture_2d_placeholder_initialize(RID p_texture) override;
@@ -501,7 +476,7 @@ public:
virtual void texture_set_detect_3d_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata) override;
void texture_set_detect_srgb_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata);
virtual void texture_set_detect_normal_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata) override;
- virtual void texture_set_detect_roughness_callback(RID p_texture, RS::TextureDetectRoughnessCallback p_callback, void *p_userdata) override{};
+ virtual void texture_set_detect_roughness_callback(RID p_texture, RS::TextureDetectRoughnessCallback p_callback, void *p_userdata) override;
virtual void texture_debug_usage(List<RS::TextureInfo> *r_info) override;
@@ -512,18 +487,14 @@ public:
void texture_set_data(RID p_texture, const Ref<Image> &p_image, int p_layer = 0);
void texture_set_data_partial(RID p_texture, const Ref<Image> &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_layer = 0);
//Ref<Image> texture_get_data(RID p_texture, int p_layer = 0) const;
- void texture_set_flags(RID p_texture, uint32_t p_flags);
- uint32_t texture_get_flags(RID p_texture) const;
+ void texture_set_sampler(RID p_texture, RS::CanvasItemTextureFilter p_filter, RS::CanvasItemTextureRepeat p_repeat);
Image::Format texture_get_format(RID p_texture) const;
- RenderingDevice::TextureType texture_get_type(RID p_texture) const;
uint32_t texture_get_texid(RID p_texture) const;
uint32_t texture_get_width(RID p_texture) const;
uint32_t texture_get_height(RID p_texture) const;
uint32_t texture_get_depth(RID p_texture) const;
void texture_bind(RID p_texture, uint32_t p_texture_no);
- void texture_set_shrink_all_x2_on_set_data(bool p_enable);
RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const;
- void textures_keep_original(bool p_enable);
/* DECAL API */
@@ -550,29 +521,18 @@ public:
static GLuint system_fbo;
+ // TODO this should be moved back to storage or removed
struct Frame {
GLES3::RenderTarget *current_rt;
-
- // these 2 may have been superseded by the equivalents in the render target.
- // these may be able to be removed.
- bool clear_request;
- Color clear_request_color;
-
- float time;
- float delta;
- uint64_t count;
-
- Frame() {
- // current_rt = nullptr;
- // clear_request = false;
- }
} frame;
RenderTarget *get_render_target(RID p_rid) { return render_target_owner.get_or_null(p_rid); };
bool owns_render_target(RID p_rid) { return render_target_owner.owns(p_rid); };
- void _render_target_clear(RenderTarget *rt);
- void _render_target_allocate(RenderTarget *rt);
+ // TODO these internals should be private
+ void _clear_render_target(RenderTarget *rt);
+ void _update_render_target(RenderTarget *rt);
+ void _create_render_target_backbuffer(RenderTarget *rt);
void _set_current_render_target(RID p_render_target);
virtual RID render_target_create() override;
@@ -586,9 +546,6 @@ public:
virtual void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) override;
virtual bool render_target_was_used(RID p_render_target) override;
void render_target_clear_used(RID p_render_target);
- void render_target_set_msaa(RID p_render_target, RS::ViewportMSAA p_msaa);
- void render_target_set_use_fxaa(RID p_render_target, bool p_fxaa);
- void render_target_set_use_debanding(RID p_render_target, bool p_debanding);
// new
void render_target_set_as_unused(RID p_render_target) override {
@@ -604,8 +561,33 @@ public:
void render_target_set_sdf_size_and_scale(RID p_render_target, RS::ViewportSDFOversize p_size, RS::ViewportSDFScale p_scale) override;
Rect2i render_target_get_sdf_rect(RID p_render_target) const override;
void render_target_mark_sdf_enabled(RID p_render_target, bool p_enabled) override;
+
+ void bind_framebuffer(GLuint framebuffer) {
+ glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
+ }
+
+ void bind_framebuffer_system() {
+ glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
+ }
+
+ String get_framebuffer_error(GLenum p_status);
};
+inline String TextureStorage::get_framebuffer_error(GLenum p_status) {
+#ifdef DEBUG_ENABLED
+ if (p_status == GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER";
+ } else if (p_status == GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER) {
+ return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER";
+ }
+#endif
+ return itos(p_status);
+}
+
} // namespace GLES3
#endif // !GLES3_ENABLED
diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
index 0c27b76ed8..a6c35b6837 100644
--- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp
+++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
@@ -379,7 +379,7 @@ float AudioDriverPulseAudio::get_latency() {
}
void AudioDriverPulseAudio::thread_func(void *p_udata) {
- AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)p_udata;
+ AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(p_udata);
unsigned int write_ofs = 0;
size_t avail_bytes = 0;
uint64_t default_device_msec = OS::get_singleton()->get_ticks_msec();
diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp
index 400802686e..59b4c34c3f 100644
--- a/drivers/vulkan/rendering_device_vulkan.cpp
+++ b/drivers/vulkan/rendering_device_vulkan.cpp
@@ -6255,7 +6255,7 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma
//validate with inputs
for (uint32_t i = 0; i < 32; i++) {
- if (!(shader->vertex_input_mask & (1 << i))) {
+ if (!(shader->vertex_input_mask & (1UL << i))) {
continue;
}
bool found = false;
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 2323578617..e724d4ccdb 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -586,20 +586,20 @@ public:
pi.name = "value";
p_list->push_back(pi);
} else {
- PropertyHint hint = PROPERTY_HINT_NONE;
- String hint_string;
+ PropertyHint val_hint = PROPERTY_HINT_NONE;
+ String val_hint_string;
if (v.get_type() == Variant::OBJECT) {
// Could actually check the object property if exists..? Yes I will!
Ref<Resource> res = v;
if (res.is_valid()) {
- hint = PROPERTY_HINT_RESOURCE_TYPE;
- hint_string = res->get_class();
+ val_hint = PROPERTY_HINT_RESOURCE_TYPE;
+ val_hint_string = res->get_class();
}
}
if (v.get_type() != Variant::NIL) {
- p_list->push_back(PropertyInfo(v.get_type(), "value", hint, hint_string));
+ p_list->push_back(PropertyInfo(v.get_type(), "value", val_hint, val_hint_string));
}
}
@@ -1264,20 +1264,20 @@ public:
pi.name = "value";
p_list->push_back(pi);
} else {
- PropertyHint hint = PROPERTY_HINT_NONE;
- String hint_string;
+ PropertyHint val_hint = PROPERTY_HINT_NONE;
+ String val_hint_string;
if (v.get_type() == Variant::OBJECT) {
// Could actually check the object property if exists..? Yes I will!
Ref<Resource> res = v;
if (res.is_valid()) {
- hint = PROPERTY_HINT_RESOURCE_TYPE;
- hint_string = res->get_class();
+ val_hint = PROPERTY_HINT_RESOURCE_TYPE;
+ val_hint_string = res->get_class();
}
}
if (v.get_type() != Variant::NIL) {
- p_list->push_back(PropertyInfo(v.get_type(), "value", hint, hint_string));
+ p_list->push_back(PropertyInfo(v.get_type(), "value", val_hint, val_hint_string));
}
}
}
@@ -1572,7 +1572,6 @@ void AnimationTimelineEdit::_notification(int p_what) {
Color color_time_dec = color;
color_time_dec.a *= 0.5;
#define SC_ADJ 100
- int min = 30;
int dec = 1;
int step = 1;
int decimals = 2;
@@ -1588,7 +1587,7 @@ void AnimationTimelineEdit::_notification(int p_what) {
const int max_sc_width = String::num(max_sc).length() * max_digit_width;
while (!step_found) {
- min = max_sc_width;
+ int min = max_sc_width;
if (decimals > 0) {
min += period_width + max_digit_width * decimals;
}
@@ -2552,7 +2551,7 @@ bool AnimationTrackEdit::_is_value_key_valid(const Variant &p_key_value, Variant
}
Ref<Texture2D> AnimationTrackEdit::_get_key_type_icon() const {
- Ref<Texture2D> type_icons[9] = {
+ const Ref<Texture2D> type_icons[9] = {
get_theme_icon(SNAME("KeyValue"), SNAME("EditorIcons")),
get_theme_icon(SNAME("KeyTrackPosition"), SNAME("EditorIcons")),
get_theme_icon(SNAME("KeyTrackRotation"), SNAME("EditorIcons")),
@@ -3534,31 +3533,75 @@ void AnimationTrackEditor::_timeline_changed(float p_new_pos, bool p_drag, bool
}
void AnimationTrackEditor::_track_remove_request(int p_track) {
- if (animation->track_is_compressed(p_track)) {
+ _animation_track_remove_request(p_track, animation);
+}
+
+void AnimationTrackEditor::_animation_track_remove_request(int p_track, Ref<Animation> p_from_animation) {
+ if (p_from_animation->track_is_compressed(p_track)) {
EditorNode::get_singleton()->show_warning(TTR("Compressed tracks can't be edited or removed. Re-import the animation with compression disabled in order to edit."));
return;
}
int idx = p_track;
- if (idx >= 0 && idx < animation->get_track_count()) {
+ if (idx >= 0 && idx < p_from_animation->get_track_count()) {
undo_redo->create_action(TTR("Remove Anim Track"));
+
+ // Remove corresponding reset tracks if they are no longer needed.
+ AnimationPlayer *player = AnimationPlayerEditor::get_singleton()->get_player();
+ if (player->has_animation(SceneStringNames::get_singleton()->RESET)) {
+ Ref<Animation> reset = player->get_animation(SceneStringNames::get_singleton()->RESET);
+ if (reset != p_from_animation) {
+ for (int i = 0; i < reset->get_track_count(); i++) {
+ if (reset->track_get_path(i) == p_from_animation->track_get_path(p_track)) {
+ // Check if the reset track isn't used by other animations.
+ bool used = false;
+ List<StringName> animation_list;
+ player->get_animation_list(&animation_list);
+
+ for (const StringName &anim_name : animation_list) {
+ Ref<Animation> anim = player->get_animation(anim_name);
+ if (anim == p_from_animation || anim == reset) {
+ continue;
+ }
+
+ for (int j = 0; j < anim->get_track_count(); j++) {
+ if (anim->track_get_path(j) == reset->track_get_path(i)) {
+ used = true;
+ break;
+ }
+ }
+
+ if (used) {
+ break;
+ }
+ }
+
+ if (!used) {
+ _animation_track_remove_request(i, reset);
+ }
+ break;
+ }
+ }
+ }
+ }
+
undo_redo->add_do_method(this, "_clear_selection", false);
- undo_redo->add_do_method(animation.ptr(), "remove_track", idx);
- undo_redo->add_undo_method(animation.ptr(), "add_track", animation->track_get_type(idx), idx);
- undo_redo->add_undo_method(animation.ptr(), "track_set_path", idx, animation->track_get_path(idx));
+ undo_redo->add_do_method(p_from_animation.ptr(), "remove_track", idx);
+ undo_redo->add_undo_method(p_from_animation.ptr(), "add_track", p_from_animation->track_get_type(idx), idx);
+ undo_redo->add_undo_method(p_from_animation.ptr(), "track_set_path", idx, p_from_animation->track_get_path(idx));
// TODO interpolation.
- for (int i = 0; i < animation->track_get_key_count(idx); i++) {
- Variant v = animation->track_get_key_value(idx, i);
- float time = animation->track_get_key_time(idx, i);
- float trans = animation->track_get_key_transition(idx, i);
+ for (int i = 0; i < p_from_animation->track_get_key_count(idx); i++) {
+ Variant v = p_from_animation->track_get_key_value(idx, i);
+ float time = p_from_animation->track_get_key_time(idx, i);
+ float trans = p_from_animation->track_get_key_transition(idx, i);
- undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, time, v);
- undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", idx, i, trans);
+ undo_redo->add_undo_method(p_from_animation.ptr(), "track_insert_key", idx, time, v);
+ undo_redo->add_undo_method(p_from_animation.ptr(), "track_set_key_transition", idx, i, trans);
}
- undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", idx, animation->track_get_interpolation_type(idx));
- if (animation->track_get_type(idx) == Animation::TYPE_VALUE) {
- undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", idx, animation->value_track_get_update_mode(idx));
+ undo_redo->add_undo_method(p_from_animation.ptr(), "track_set_interpolation_type", idx, p_from_animation->track_get_interpolation_type(idx));
+ if (p_from_animation->track_get_type(idx) == Animation::TYPE_VALUE) {
+ undo_redo->add_undo_method(p_from_animation.ptr(), "value_track_set_update_mode", idx, p_from_animation->value_track_get_update_mode(idx));
}
undo_redo->commit_action();
@@ -4033,12 +4076,20 @@ Ref<Animation> AnimationTrackEditor::_create_and_get_reset_animation() {
if (player->has_animation(SceneStringNames::get_singleton()->RESET)) {
return player->get_animation(SceneStringNames::get_singleton()->RESET);
} else {
+ Ref<AnimationLibrary> al;
+ if (!player->has_animation_library("")) {
+ al.instantiate();
+ player->add_animation_library("", al);
+ } else {
+ al = player->get_animation_library("");
+ }
+
Ref<Animation> reset_anim;
reset_anim.instantiate();
reset_anim->set_length(ANIM_MIN_LENGTH);
- undo_redo->add_do_method(player, "add_animation", SceneStringNames::get_singleton()->RESET, reset_anim);
+ undo_redo->add_do_method(al.ptr(), "add_animation", SceneStringNames::get_singleton()->RESET, reset_anim);
undo_redo->add_do_method(AnimationPlayerEditor::get_singleton(), "_animation_player_changed", player);
- undo_redo->add_undo_method(player, "remove_animation", SceneStringNames::get_singleton()->RESET);
+ undo_redo->add_undo_method(al.ptr(), "remove_animation", SceneStringNames::get_singleton()->RESET);
undo_redo->add_undo_method(AnimationPlayerEditor::get_singleton(), "_animation_player_changed", player);
return reset_anim;
}
diff --git a/editor/animation_track_editor.h b/editor/animation_track_editor.h
index 0f6d12b4d4..92b203d183 100644
--- a/editor/animation_track_editor.h
+++ b/editor/animation_track_editor.h
@@ -46,7 +46,6 @@
#include "scene/resources/animation.h"
#include "scene_tree_editor.h"
-class AnimationPlayer;
class AnimationTrackEdit;
class ViewPanner;
@@ -323,6 +322,7 @@ class AnimationTrackEditor : public VBoxContainer {
void _name_limit_changed();
void _timeline_changed(float p_new_pos, bool p_drag, bool p_timeline_only);
void _track_remove_request(int p_track);
+ void _animation_track_remove_request(int p_track, Ref<Animation> p_from_animation);
void _track_grab_focus(int p_track);
UndoRedo *undo_redo = nullptr;
diff --git a/editor/audio_stream_preview.cpp b/editor/audio_stream_preview.cpp
index f8bf12227a..bea95d873e 100644
--- a/editor/audio_stream_preview.cpp
+++ b/editor/audio_stream_preview.cpp
@@ -101,7 +101,7 @@ void AudioStreamPreviewGenerator::_update_emit(ObjectID p_id) {
}
void AudioStreamPreviewGenerator::_preview_thread(void *p_preview) {
- Preview *preview = (Preview *)p_preview;
+ Preview *preview = static_cast<Preview *>(p_preview);
float muxbuff_chunk_s = 0.25;
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index b6da21bc79..c9868bc3c2 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -151,6 +151,8 @@ bool FindReplaceBar::_search(uint32_t p_flags, int p_from_line, int p_from_col)
text_editor->set_caret_column(pos.x + text.length(), false);
text_editor->center_viewport_to_caret();
text_editor->select(pos.y, pos.x, pos.y, pos.x + text.length());
+
+ line_col_changed_for_result = true;
}
text_editor->set_search_text(text);
@@ -209,6 +211,8 @@ void FindReplaceBar::_replace() {
}
text_editor->end_complex_operation();
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
if (selection_enabled && is_selection_only()) {
// Reselect in order to keep 'Replace' restricted to selection
@@ -305,6 +309,8 @@ void FindReplaceBar::_replace_all() {
text_editor->call_deferred(SNAME("connect"), "text_changed", callable_mp(this, &FindReplaceBar::_editor_text_changed));
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
}
void FindReplaceBar::_get_search_from(int &r_line, int &r_col) {
@@ -321,40 +327,57 @@ void FindReplaceBar::_get_search_from(int &r_line, int &r_col) {
}
void FindReplaceBar::_update_results_count() {
- if (results_count != -1) {
+ if (!needs_to_count_results && (result_line != -1)) {
+ results_count_to_current += (flags & TextEdit::SEARCH_BACKWARDS) ? -1 : 1;
+
+ if (results_count_to_current > results_count) {
+ results_count_to_current = results_count_to_current - results_count;
+ } else if (results_count_to_current == 0) {
+ results_count_to_current = results_count;
+ }
+
return;
}
results_count = 0;
+ results_count_to_current = 0;
String searched = get_search_text();
if (searched.is_empty()) {
return;
}
- String full_text = text_editor->get_text();
+ needs_to_count_results = false;
- int from_pos = 0;
+ for (int i = 0; i < text_editor->get_line_count(); i++) {
+ String line_text = text_editor->get_line(i);
- while (true) {
- int pos = is_case_sensitive() ? full_text.find(searched, from_pos) : full_text.findn(searched, from_pos);
- if (pos == -1) {
- break;
- }
+ int col_pos = 0;
+
+ while (true) {
+ col_pos = is_case_sensitive() ? line_text.find(searched, col_pos) : line_text.findn(searched, col_pos);
- int pos_subsequent = pos + searched.length();
- if (is_whole_words()) {
- from_pos = pos + 1; // Making sure we won't hit the same match next time, if we get out via a continue.
- if (pos > 0 && !(is_symbol(full_text[pos - 1]) || full_text[pos - 1] == '\n')) {
- continue;
+ if (col_pos == -1) {
+ break;
}
- if (pos_subsequent < full_text.length() && !(is_symbol(full_text[pos_subsequent]) || full_text[pos_subsequent] == '\n')) {
- continue;
+
+ if (is_whole_words()) {
+ if (col_pos > 0 && !is_symbol(line_text[col_pos - 1])) {
+ break;
+ }
+ if (col_pos + line_text.length() < line_text.length() && !is_symbol(line_text[col_pos + searched.length()])) {
+ break;
+ }
}
- }
- results_count++;
- from_pos = pos_subsequent;
+ results_count++;
+
+ if (i == result_line && col_pos == result_col) {
+ results_count_to_current = results_count;
+ }
+
+ col_pos += searched.length();
+ }
}
}
@@ -365,12 +388,19 @@ void FindReplaceBar::_update_matches_label() {
matches_label->show();
matches_label->add_theme_color_override("font_color", results_count > 0 ? get_theme_color(SNAME("font_color"), SNAME("Label")) : get_theme_color(SNAME("error_color"), SNAME("Editor")));
- matches_label->set_text(vformat(results_count == 1 ? TTR("%d match.") : TTR("%d matches."), results_count));
+
+ if (results_count == 0) {
+ matches_label->set_text("No match");
+ } else if (results_count == 1) {
+ matches_label->set_text(vformat(TTR("%d match"), results_count));
+ } else {
+ matches_label->set_text(vformat(TTR("%d of %d matches"), results_count_to_current, results_count));
+ }
}
}
bool FindReplaceBar::search_current() {
- uint32_t flags = 0;
+ flags = 0;
if (is_whole_words()) {
flags |= TextEdit::SEARCH_WHOLE_WORDS;
@@ -390,7 +420,7 @@ bool FindReplaceBar::search_prev() {
popup_search(true);
}
- uint32_t flags = 0;
+ flags = 0;
String text = get_search_text();
if (is_whole_words()) {
@@ -425,7 +455,7 @@ bool FindReplaceBar::search_next() {
popup_search(true);
}
- uint32_t flags = 0;
+ flags = 0;
String text;
if (replace_all_mode) {
text = get_replace_text();
@@ -496,6 +526,8 @@ void FindReplaceBar::_show_search(bool p_focus_replace, bool p_show_only) {
}
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
_update_results_count();
_update_matches_label();
}
@@ -523,11 +555,15 @@ void FindReplaceBar::popup_replace() {
void FindReplaceBar::_search_options_changed(bool p_pressed) {
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
search_current();
}
void FindReplaceBar::_editor_text_changed() {
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
if (is_visible_in_tree()) {
preserve_cursor = true;
search_current();
@@ -537,6 +573,8 @@ void FindReplaceBar::_editor_text_changed() {
void FindReplaceBar::_search_text_changed(const String &p_text) {
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
search_current();
}
@@ -601,6 +639,8 @@ void FindReplaceBar::set_text_edit(CodeTextEditor *p_text_editor) {
}
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
base_text_editor = p_text_editor;
text_editor = base_text_editor->get_text_editor();
text_editor->connect("text_changed", callable_mp(this, &FindReplaceBar::_editor_text_changed));
@@ -618,6 +658,8 @@ void FindReplaceBar::_bind_methods() {
FindReplaceBar::FindReplaceBar() {
results_count = -1;
+ results_count_to_current = -1;
+ needs_to_count_results = true;
vbc_lineedit = memnew(VBoxContainer);
add_child(vbc_lineedit);
@@ -836,6 +878,14 @@ void CodeTextEditor::_line_col_changed() {
sb.append(itos(positional_column + 1).lpad(3));
line_and_col_txt->set_text(sb.as_string());
+
+ if (find_replace_bar) {
+ if (!find_replace_bar->line_col_changed_for_result) {
+ find_replace_bar->needs_to_count_results = true;
+ }
+
+ find_replace_bar->line_col_changed_for_result = false;
+ }
}
void CodeTextEditor::_text_changed() {
@@ -844,6 +894,10 @@ void CodeTextEditor::_text_changed() {
}
idle->start();
+
+ if (find_replace_bar) {
+ find_replace_bar->needs_to_count_results = true;
+ }
}
void CodeTextEditor::_code_complete_timer_timeout() {
diff --git a/editor/code_editor.h b/editor/code_editor.h
index d52f57860c..bb1791940e 100644
--- a/editor/code_editor.h
+++ b/editor/code_editor.h
@@ -82,9 +82,12 @@ class FindReplaceBar : public HBoxContainer {
CodeTextEditor *base_text_editor = nullptr;
CodeEdit *text_editor = nullptr;
+ uint32_t flags = 0;
+
int result_line;
int result_col;
int results_count;
+ int results_count_to_current;
bool replace_all_mode = false;
bool preserve_cursor = false;
@@ -131,6 +134,9 @@ public:
bool search_prev();
bool search_next();
+ bool needs_to_count_results = true;
+ bool line_col_changed_for_result = false;
+
FindReplaceBar();
};
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index 0f8667f81a..c9d612d4dd 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -365,6 +365,24 @@ void ConnectDialog::init(ConnectionData p_cd, bool p_edit) {
deferred->set_pressed(b_deferred);
oneshot->set_pressed(b_oneshot);
+
+ MethodInfo r_signal;
+ Ref<Script> source_script = source->get_script();
+ if (source_script.is_valid() && source_script->has_script_signal(signal)) {
+ List<MethodInfo> signals;
+ source_script->get_script_signal_list(&signals);
+ for (MethodInfo &mi : signals) {
+ if (mi.name == signal) {
+ r_signal = mi;
+ break;
+ }
+ }
+ } else {
+ ClassDB::get_signal(source->get_class(), signal, &r_signal);
+ }
+
+ unbind_count->set_max(r_signal.arguments.size());
+
unbind_count->set_value(p_cd.unbinds);
_unbind_count_changed(p_cd.unbinds);
@@ -619,6 +637,7 @@ void ConnectionsDock::_make_or_edit_connection() {
if (add_script_function) {
// Pick up args here before "it" is deleted by update_tree.
script_function_args = it->get_metadata(0).operator Dictionary()["args"];
+ script_function_args.resize(script_function_args.size() - cd.unbinds);
for (int i = 0; i < cd.binds.size(); i++) {
script_function_args.push_back("extra_arg_" + itos(i) + ":" + Variant::get_type_name(cd.binds[i].get_type()));
}
diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp
index 58a9175df1..74993f567a 100644
--- a/editor/editor_export.cpp
+++ b/editor/editor_export.cpp
@@ -1820,6 +1820,18 @@ bool EditorExportPlatformPC::can_export(const Ref<EditorExportPreset> &p_preset,
Error EditorExportPlatformPC::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
+ Error err = prepare_template(p_preset, p_debug, p_path, p_flags);
+ if (err == OK) {
+ err = export_project_data(p_preset, p_debug, p_path, p_flags);
+ }
+
+ return err;
+}
+
+Error EditorExportPlatformPC::prepare_template(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
+ if (!DirAccess::exists(p_path.get_base_dir())) {
+ return ERR_FILE_BAD_PATH;
+ }
String custom_debug = p_preset->get("custom_template/debug");
String custom_release = p_preset->get("custom_template/release");
@@ -1841,49 +1853,52 @@ Error EditorExportPlatformPC::export_project(const Ref<EditorExportPreset> &p_pr
da->make_dir_recursive(p_path.get_base_dir());
Error err = da->copy(template_path, p_path, get_chmod_flags());
- if (err == OK) {
- String pck_path;
- if (p_preset->get("binary_format/embed_pck")) {
- pck_path = p_path;
- } else {
- pck_path = p_path.get_basename() + ".pck";
- }
+ return err;
+}
- Vector<SharedObject> so_files;
+Error EditorExportPlatformPC::export_project_data(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
+ String pck_path;
+ if (p_preset->get("binary_format/embed_pck")) {
+ pck_path = p_path;
+ } else {
+ pck_path = p_path.get_basename() + ".pck";
+ }
- int64_t embedded_pos;
- int64_t embedded_size;
- err = save_pack(p_preset, p_debug, pck_path, &so_files, p_preset->get("binary_format/embed_pck"), &embedded_pos, &embedded_size);
- if (err == OK && p_preset->get("binary_format/embed_pck")) {
- if (embedded_size >= 0x100000000 && !p_preset->get("binary_format/64_bits")) {
- EditorNode::get_singleton()->show_warning(TTR("On 32-bit exports the embedded PCK cannot be bigger than 4 GiB."));
- return ERR_INVALID_PARAMETER;
- }
+ Vector<SharedObject> so_files;
- err = fixup_embedded_pck(p_path, embedded_pos, embedded_size);
+ int64_t embedded_pos;
+ int64_t embedded_size;
+ Error err = save_pack(p_preset, p_debug, pck_path, &so_files, p_preset->get("binary_format/embed_pck"), &embedded_pos, &embedded_size);
+ if (err == OK && p_preset->get("binary_format/embed_pck")) {
+ if (embedded_size >= 0x100000000 && !p_preset->get("binary_format/64_bits")) {
+ EditorNode::get_singleton()->show_warning(TTR("On 32-bit exports the embedded PCK cannot be bigger than 4 GiB."));
+ return ERR_INVALID_PARAMETER;
}
- if (err == OK && !so_files.is_empty()) {
- // If shared object files, copy them.
- for (int i = 0; i < so_files.size() && err == OK; i++) {
- String src_path = ProjectSettings::get_singleton()->globalize_path(so_files[i].path);
- String target_path;
- if (so_files[i].target.is_empty()) {
- target_path = p_path.get_base_dir().plus_file(src_path.get_file());
- } else {
- target_path = p_path.get_base_dir().plus_file(so_files[i].target).plus_file(src_path.get_file());
- }
+ err = fixup_embedded_pck(p_path, embedded_pos, embedded_size);
+ }
- if (da->dir_exists(src_path)) {
- err = da->make_dir_recursive(target_path);
- if (err == OK) {
- err = da->copy_dir(src_path, target_path, -1, true);
- }
- } else {
- err = da->copy(src_path, target_path);
- if (err == OK) {
- err = sign_shared_object(p_preset, p_debug, target_path);
- }
+ if (err == OK && !so_files.is_empty()) {
+ // If shared object files, copy them.
+ Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ for (int i = 0; i < so_files.size() && err == OK; i++) {
+ String src_path = ProjectSettings::get_singleton()->globalize_path(so_files[i].path);
+ String target_path;
+ if (so_files[i].target.is_empty()) {
+ target_path = p_path.get_base_dir().plus_file(src_path.get_file());
+ } else {
+ target_path = p_path.get_base_dir().plus_file(so_files[i].target).plus_file(src_path.get_file());
+ }
+
+ if (da->dir_exists(src_path)) {
+ err = da->make_dir_recursive(target_path);
+ if (err == OK) {
+ err = da->copy_dir(src_path, target_path, -1, true);
+ }
+ } else {
+ err = da->copy(src_path, target_path);
+ if (err == OK) {
+ err = sign_shared_object(p_preset, p_debug, target_path);
}
}
}
diff --git a/editor/editor_export.h b/editor/editor_export.h
index 236f4d129c..ab09c98941 100644
--- a/editor/editor_export.h
+++ b/editor/editor_export.h
@@ -442,6 +442,10 @@ public:
virtual Error sign_shared_object(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path);
virtual String get_template_file_name(const String &p_target, const String &p_arch) const = 0;
+ Error prepare_template(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags);
+ Error export_project_data(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags);
+
+ void set_extension(const String &p_extension, const String &p_feature_key = "default");
void set_name(const String &p_name);
void set_os_name(const String &p_name);
diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp
index bd9b0ae1c8..9a30c6a1e3 100644
--- a/editor/editor_inspector.cpp
+++ b/editor/editor_inspector.cpp
@@ -2456,8 +2456,6 @@ void EditorInspector::update_tree() {
_parse_added_editors(main_vbox, ped);
}
- bool in_script_variables = false;
-
// Get the lists of editors for properties.
for (List<PropertyInfo>::Element *E_property = plist.front(); E_property; E_property = E_property->next()) {
PropertyInfo &p = E_property->get();
@@ -2549,9 +2547,6 @@ void EditorInspector::update_tree() {
if (category->icon.is_null() && has_theme_icon(base_type, SNAME("EditorIcons"))) {
category->icon = get_theme_icon(base_type, SNAME("EditorIcons"));
}
- in_script_variables = true;
- } else {
- in_script_variables = false;
}
if (category->icon.is_null()) {
if (!type.is_empty()) { // Can happen for built-in scripts.
@@ -2687,9 +2682,9 @@ void EditorInspector::update_tree() {
}
}
- // Don't localize properties in Script Variables category.
+ // Don't localize script variables.
EditorPropertyNameProcessor::Style name_style = property_name_style;
- if (in_script_variables && name_style == EditorPropertyNameProcessor::STYLE_LOCALIZED) {
+ if ((p.usage & PROPERTY_USAGE_SCRIPT_VARIABLE) && name_style == EditorPropertyNameProcessor::STYLE_LOCALIZED) {
name_style = EditorPropertyNameProcessor::STYLE_CAPITALIZED;
}
const String property_label_string = EditorPropertyNameProcessor::get_singleton()->process_name(name_override, name_style) + feature_tag;
@@ -2745,9 +2740,15 @@ void EditorInspector::update_tree() {
String label;
String tooltip;
+ // Don't localize groups for script variables.
+ EditorPropertyNameProcessor::Style section_name_style = property_name_style;
+ if ((p.usage & PROPERTY_USAGE_SCRIPT_VARIABLE) && section_name_style == EditorPropertyNameProcessor::STYLE_LOCALIZED) {
+ section_name_style = EditorPropertyNameProcessor::STYLE_CAPITALIZED;
+ }
+
// Only process group label if this is not the group or subgroup.
if ((i == 0 && component == group) || (i == 1 && component == subgroup)) {
- if (property_name_style == EditorPropertyNameProcessor::STYLE_LOCALIZED) {
+ if (section_name_style == EditorPropertyNameProcessor::STYLE_LOCALIZED) {
label = TTRGET(component);
tooltip = component;
} else {
@@ -2755,8 +2756,8 @@ void EditorInspector::update_tree() {
tooltip = TTRGET(component);
}
} else {
- label = EditorPropertyNameProcessor::get_singleton()->process_name(component, property_name_style);
- tooltip = EditorPropertyNameProcessor::get_singleton()->process_name(component, EditorPropertyNameProcessor::get_tooltip_style(property_name_style));
+ label = EditorPropertyNameProcessor::get_singleton()->process_name(component, section_name_style);
+ tooltip = EditorPropertyNameProcessor::get_singleton()->process_name(component, EditorPropertyNameProcessor::get_tooltip_style(section_name_style));
}
Color c = sscolor;
@@ -3515,7 +3516,9 @@ void EditorInspector::_notification(int p_what) {
get_v_scroll_bar()->call_deferred(SNAME("set_value"), update_scroll_request);
update_scroll_request = -1;
}
- if (refresh_countdown > 0) {
+ if (update_tree_pending) {
+ refresh_countdown = float(EditorSettings::get_singleton()->get("docks/property_editor/auto_refresh_interval"));
+ } else if (refresh_countdown > 0) {
refresh_countdown -= get_process_delta_time();
if (refresh_countdown <= 0) {
for (const KeyValue<StringName, List<EditorProperty *>> &F : editor_property_map) {
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 3cc4821f95..3d52686378 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -134,6 +134,7 @@
#include "editor/plugins/asset_library_editor_plugin.h"
#include "editor/plugins/audio_stream_editor_plugin.h"
#include "editor/plugins/audio_stream_randomizer_editor_plugin.h"
+#include "editor/plugins/bit_map_editor_plugin.h"
#include "editor/plugins/camera_3d_editor_plugin.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
#include "editor/plugins/collision_polygon_2d_editor_plugin.h"
@@ -171,6 +172,7 @@
#include "editor/plugins/physical_bone_3d_editor_plugin.h"
#include "editor/plugins/polygon_2d_editor_plugin.h"
#include "editor/plugins/polygon_3d_editor_plugin.h"
+#include "editor/plugins/ray_cast_2d_editor_plugin.h"
#include "editor/plugins/replication_editor_plugin.h"
#include "editor/plugins/resource_preloader_editor_plugin.h"
#include "editor/plugins/root_motion_editor_plugin.h"
@@ -2658,25 +2660,6 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
project_export->popup_export();
} break;
- case FILE_EXPORT_MESH_LIBRARY: {
- if (!editor_data.get_edited_scene_root()) {
- show_accept(TTR("This operation can't be done without a scene."), TTR("OK"));
- break;
- }
-
- List<String> extensions;
- Ref<MeshLibrary> ml(memnew(MeshLibrary));
- ResourceSaver::get_recognized_extensions(ml, &extensions);
- file_export_lib->clear_filters();
- for (const String &E : extensions) {
- file_export_lib->add_filter("*." + E);
- }
-
- file_export_lib->popup_file_dialog();
- file_export_lib->set_title(TTR("Export Mesh Library"));
-
- } break;
-
case FILE_EXTERNAL_OPEN_SCENE: {
if (unsaved_cache && !p_confirmed) {
confirmation->get_ok_button()->set_text(TTR("Open"));
@@ -3020,6 +3003,40 @@ void EditorNode::_tool_menu_option(int p_idx) {
}
}
+void EditorNode::_export_as_menu_option(int p_idx) {
+ if (p_idx == 0) { // MeshLibrary
+ current_menu_option = FILE_EXPORT_MESH_LIBRARY;
+
+ if (!editor_data.get_edited_scene_root()) {
+ show_accept(TTR("This operation can't be done without a scene."), TTR("OK"));
+ return;
+ }
+
+ List<String> extensions;
+ Ref<MeshLibrary> ml(memnew(MeshLibrary));
+ ResourceSaver::get_recognized_extensions(ml, &extensions);
+ file_export_lib->clear_filters();
+ for (const String &E : extensions) {
+ file_export_lib->add_filter("*." + E);
+ }
+
+ file_export_lib->popup_file_dialog();
+ file_export_lib->set_title(TTR("Export Mesh Library"));
+ } else { // Custom menu options added by plugins
+ if (export_as_menu->get_item_submenu(p_idx).is_empty()) { // If not a submenu
+ Callable callback = export_as_menu->get_item_metadata(p_idx);
+ Callable::CallError ce;
+ Variant result;
+ callback.call(nullptr, 0, result, ce);
+
+ if (ce.error != Callable::CallError::CALL_OK) {
+ String err = Variant::get_callable_error_text(callback, nullptr, 0, ce);
+ ERR_PRINT("Error calling function from export_as menu: " + err);
+ }
+ }
+ }
+}
+
int EditorNode::_next_unsaved_scene(bool p_valid_filename, int p_start) {
for (int i = p_start; i < editor_data.get_edited_scene_count(); i++) {
if (!editor_data.get_edited_scene_root(i)) {
@@ -4094,22 +4111,31 @@ Ref<Texture2D> EditorNode::get_class_icon(const String &p_class, const String &p
ERR_FAIL_COND_V_MSG(p_class.is_empty(), nullptr, "Class name cannot be empty.");
if (ScriptServer::is_global_class(p_class)) {
- Ref<ImageTexture> icon;
- Ref<Script> script = EditorNode::get_editor_data().script_class_load_script(p_class);
- StringName name = p_class;
-
- while (script.is_valid()) {
- name = EditorNode::get_editor_data().script_class_get_name(script->get_path());
- String current_icon_path = EditorNode::get_editor_data().script_class_get_icon_path(name);
- icon = _load_custom_class_icon(current_icon_path);
- if (icon.is_valid()) {
- return icon;
- }
- script = script->get_base_script();
- }
+ String class_name = p_class;
+ Ref<Script> script = EditorNode::get_editor_data().script_class_load_script(class_name);
- if (icon.is_null()) {
- icon = gui_base->get_theme_icon(ScriptServer::get_global_class_base(name), SNAME("EditorIcons"));
+ while (true) {
+ String icon_path = EditorNode::get_editor_data().script_class_get_icon_path(class_name);
+ Ref<Texture> icon = _load_custom_class_icon(icon_path);
+ if (icon.is_valid()) {
+ return icon; // Current global class has icon.
+ }
+
+ // Find next global class along the inheritance chain.
+ do {
+ Ref<Script> base_script = script->get_base_script();
+ if (base_script.is_null()) {
+ // We've reached a native class, use its icon.
+ String base_type;
+ script->get_language()->get_global_class_name(script->get_path(), &base_type);
+ if (gui_base->has_theme_icon(base_type, "EditorIcons")) {
+ return gui_base->get_theme_icon(base_type, "EditorIcons");
+ }
+ return gui_base->get_theme_icon(p_fallback, "EditorIcons");
+ }
+ script = base_script;
+ class_name = EditorNode::get_editor_data().script_class_get_name(script->get_path());
+ } while (class_name.is_empty());
}
}
@@ -5465,6 +5491,10 @@ void EditorNode::remove_tool_menu_item(const String &p_name) {
}
}
+PopupMenu *EditorNode::get_export_as_menu() {
+ return export_as_menu;
+}
+
void EditorNode::_global_menu_scene(const Variant &p_tag) {
int idx = (int)p_tag;
scene_tabs->set_current_tab(idx);
@@ -6439,12 +6469,12 @@ EditorNode::EditorNode() {
p->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_script", TTR("Quick Open Script..."), KeyModifierMask::CMD + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN_SCRIPT);
p->add_separator();
- PopupMenu *pm_export = memnew(PopupMenu);
- pm_export->set_name("Export");
- p->add_child(pm_export);
- p->add_submenu_item(TTR("Convert To..."), "Export");
- pm_export->add_shortcut(ED_SHORTCUT("editor/convert_to_MeshLibrary", TTR("MeshLibrary...")), FILE_EXPORT_MESH_LIBRARY);
- pm_export->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option));
+ export_as_menu = memnew(PopupMenu);
+ export_as_menu->set_name("Export");
+ p->add_child(export_as_menu);
+ p->add_submenu_item(TTR("Export As..."), "Export");
+ export_as_menu->add_shortcut(ED_SHORTCUT("editor/export_as_mesh_library", TTR("MeshLibrary...")), FILE_EXPORT_MESH_LIBRARY);
+ export_as_menu->connect("index_pressed", callable_mp(this, &EditorNode::_export_as_menu_option));
p->add_separator();
p->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO, true);
@@ -7066,6 +7096,8 @@ EditorNode::EditorNode() {
add_editor_plugin(memnew(TextControlEditorPlugin));
add_editor_plugin(memnew(ControlEditorPlugin));
add_editor_plugin(memnew(GradientTexture2DEditorPlugin));
+ add_editor_plugin(memnew(BitMapEditorPlugin));
+ add_editor_plugin(memnew(RayCast2DEditorPlugin));
for (int i = 0; i < EditorPlugins::get_plugin_count(); i++) {
add_editor_plugin(EditorPlugins::create(i));
@@ -7084,6 +7116,7 @@ EditorNode::EditorNode() {
resource_preview->add_preview_generator(Ref<EditorMeshPreviewPlugin>(memnew(EditorMeshPreviewPlugin)));
resource_preview->add_preview_generator(Ref<EditorBitmapPreviewPlugin>(memnew(EditorBitmapPreviewPlugin)));
resource_preview->add_preview_generator(Ref<EditorFontPreviewPlugin>(memnew(EditorFontPreviewPlugin)));
+ resource_preview->add_preview_generator(Ref<EditorGradientPreviewPlugin>(memnew(EditorGradientPreviewPlugin)));
{
Ref<StandardMaterial3DConversionPlugin> spatial_mat_convert;
diff --git a/editor/editor_node.h b/editor/editor_node.h
index c6c1f09938..82118b8b70 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -323,6 +323,7 @@ private:
MenuButton *settings_menu = nullptr;
MenuButton *help_menu = nullptr;
PopupMenu *tool_menu = nullptr;
+ PopupMenu *export_as_menu = nullptr;
Button *export_button = nullptr;
Button *prev_scene = nullptr;
Button *play_button = nullptr;
@@ -524,6 +525,7 @@ private:
void _save_screenshot(NodePath p_path);
void _tool_menu_option(int p_idx);
+ void _export_as_menu_option(int p_idx);
void _update_file_menu_opened();
void _update_file_menu_closed();
@@ -840,6 +842,8 @@ public:
void add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu);
void remove_tool_menu_item(const String &p_name);
+ PopupMenu *get_export_as_menu();
+
void save_all_scenes();
void save_scene_list(Vector<String> p_scene_filenames);
void restart_editor();
diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp
index 6596c245bc..639846861b 100644
--- a/editor/editor_plugin.cpp
+++ b/editor/editor_plugin.cpp
@@ -524,6 +524,10 @@ void EditorPlugin::remove_tool_menu_item(const String &p_name) {
EditorNode::get_singleton()->remove_tool_menu_item(p_name);
}
+PopupMenu *EditorPlugin::get_export_as_menu() {
+ return EditorNode::get_singleton()->get_export_as_menu();
+}
+
void EditorPlugin::set_input_event_forwarding_always_enabled() {
input_event_forwarding_always_enabled = true;
EditorPluginList *always_input_forwarding_list = EditorNode::get_singleton()->get_editor_plugins_force_input_forwarding();
@@ -870,6 +874,7 @@ void EditorPlugin::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_tool_menu_item", "name", "callable"), &EditorPlugin::add_tool_menu_item);
ClassDB::bind_method(D_METHOD("add_tool_submenu_item", "name", "submenu"), &EditorPlugin::add_tool_submenu_item);
ClassDB::bind_method(D_METHOD("remove_tool_menu_item", "name"), &EditorPlugin::remove_tool_menu_item);
+ ClassDB::bind_method(D_METHOD("get_export_as_menu"), &EditorPlugin::get_export_as_menu);
ClassDB::bind_method(D_METHOD("add_custom_type", "type", "base", "script", "icon"), &EditorPlugin::add_custom_type);
ClassDB::bind_method(D_METHOD("remove_custom_type", "type"), &EditorPlugin::remove_custom_type);
diff --git a/editor/editor_plugin.h b/editor/editor_plugin.h
index 1a5be7a89b..c666b4639d 100644
--- a/editor/editor_plugin.h
+++ b/editor/editor_plugin.h
@@ -220,6 +220,8 @@ public:
void add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu);
void remove_tool_menu_item(const String &p_name);
+ PopupMenu *get_export_as_menu();
+
void set_input_event_forwarding_always_enabled();
bool is_input_event_forwarding_always_enabled() { return input_event_forwarding_always_enabled; }
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index 677d22cb62..581a807e27 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -3361,10 +3361,8 @@ struct EditorPropertyRangeHint {
static EditorPropertyRangeHint _parse_range_hint(PropertyHint p_hint, const String &p_hint_text, double p_default_step) {
EditorPropertyRangeHint hint;
hint.step = p_default_step;
- bool degrees = false;
-
+ Vector<String> slices = p_hint_text.split(",");
if (p_hint == PROPERTY_HINT_RANGE) {
- Vector<String> slices = p_hint_text.split(",");
ERR_FAIL_COND_V_MSG(slices.size() < 2, hint,
vformat("Invalid PROPERTY_HINT_RANGE with hint \"%s\": Missing required min and/or max values.", p_hint_text));
@@ -3381,11 +3379,7 @@ static EditorPropertyRangeHint _parse_range_hint(PropertyHint p_hint, const Stri
hint.hide_slider = false;
for (int i = 2; i < slices.size(); i++) {
String slice = slices[i].strip_edges();
- if (slice == "radians") {
- hint.radians = true;
- } else if (slice == "degrees") {
- degrees = true;
- } else if (slice == "or_greater") {
+ if (slice == "or_greater") {
hint.greater = true;
} else if (slice == "or_lesser") {
hint.lesser = true;
@@ -3393,11 +3387,20 @@ static EditorPropertyRangeHint _parse_range_hint(PropertyHint p_hint, const Stri
hint.hide_slider = true;
} else if (slice == "exp") {
hint.exp_range = true;
- } else if (slice.begins_with("suffix:")) {
- hint.suffix = " " + slice.replace_first("suffix:", "").strip_edges();
}
}
}
+ bool degrees = false;
+ for (int i = 0; i < slices.size(); i++) {
+ String slice = slices[i].strip_edges();
+ if (slice == "radians") {
+ hint.radians = true;
+ } else if (slice == "degrees") {
+ degrees = true;
+ } else if (slice.begins_with("suffix:")) {
+ hint.suffix = " " + slice.replace_first("suffix:", "").strip_edges();
+ }
+ }
if ((hint.radians || degrees) && hint.suffix.is_empty()) {
hint.suffix = U"\u00B0";
diff --git a/editor/editor_properties_array_dict.cpp b/editor/editor_properties_array_dict.cpp
index f59ba66862..ffbe50285c 100644
--- a/editor/editor_properties_array_dict.cpp
+++ b/editor/editor_properties_array_dict.cpp
@@ -209,46 +209,13 @@ void EditorPropertyArray::_object_id_selected(const StringName &p_property, Obje
void EditorPropertyArray::update_property() {
Variant array = get_edited_object()->get(get_edited_property());
- String arrtype = "";
- switch (array_type) {
- case Variant::ARRAY: {
- arrtype = "Array";
- } break;
-
- // Arrays.
- case Variant::PACKED_BYTE_ARRAY: {
- arrtype = "PackedByteArray";
- } break;
- case Variant::PACKED_INT32_ARRAY: {
- arrtype = "PackedInt32Array";
- } break;
- case Variant::PACKED_FLOAT32_ARRAY: {
- arrtype = "PackedFloat32Array";
- } break;
- case Variant::PACKED_INT64_ARRAY: {
- arrtype = "PackedInt64Array";
- } break;
- case Variant::PACKED_FLOAT64_ARRAY: {
- arrtype = "PackedFloat64Array";
- } break;
- case Variant::PACKED_STRING_ARRAY: {
- arrtype = "PackedStringArray";
- } break;
- case Variant::PACKED_VECTOR2_ARRAY: {
- arrtype = "PackedVector2Array";
- } break;
- case Variant::PACKED_VECTOR3_ARRAY: {
- arrtype = "PackedVector3Array";
- } break;
- case Variant::PACKED_COLOR_ARRAY: {
- arrtype = "PackedColorArray";
- } break;
- default: {
- }
+ String array_type_name = Variant::get_type_name(array_type);
+ if (array_type == Variant::ARRAY && subtype != Variant::NIL) {
+ array_type_name = vformat("%s[%s]", array_type_name, Variant::get_type_name(subtype));
}
if (array.get_type() == Variant::NIL) {
- edit->set_text(String("(Nil) ") + arrtype);
+ edit->set_text(vformat(TTR("(Nil) %s"), array_type_name));
edit->set_pressed(false);
if (vbox) {
set_bottom_editor(nullptr);
@@ -264,7 +231,7 @@ void EditorPropertyArray::update_property() {
page_index = MIN(page_index, max_page);
int offset = page_index * page_length;
- edit->set_text(arrtype + " (size " + itos(size) + ")");
+ edit->set_text(vformat(TTR("%s (size %s)"), array_type_name, itos(size)));
bool unfolded = get_edited_object()->editor_is_section_unfolded(get_edited_property());
if (edit->is_pressed() != unfolded) {
diff --git a/editor/editor_property_name_processor.cpp b/editor/editor_property_name_processor.cpp
index 9541c4a4ec..1e222c02a3 100644
--- a/editor/editor_property_name_processor.cpp
+++ b/editor/editor_property_name_processor.cpp
@@ -110,6 +110,7 @@ EditorPropertyNameProcessor::EditorPropertyNameProcessor() {
capitalize_string_remaps["arm64-v8a"] = "arm64-v8a";
capitalize_string_remaps["armeabi-v7a"] = "armeabi-v7a";
capitalize_string_remaps["arvr"] = "ARVR";
+ capitalize_string_remaps["bidi"] = "BiDi";
capitalize_string_remaps["bg"] = "BG";
capitalize_string_remaps["bp"] = "BP";
capitalize_string_remaps["bpc"] = "BPC";
@@ -127,6 +128,7 @@ EditorPropertyNameProcessor::EditorPropertyNameProcessor() {
capitalize_string_remaps["erp"] = "ERP";
capitalize_string_remaps["etc"] = "ETC";
capitalize_string_remaps["etc2"] = "ETC2";
+ capitalize_string_remaps["filesystem"] = "FileSystem";
capitalize_string_remaps["fbx"] = "FBX";
capitalize_string_remaps["fbx2gltf"] = "FBX2glTF";
capitalize_string_remaps["fft"] = "FFT";
@@ -180,6 +182,7 @@ EditorPropertyNameProcessor::EditorPropertyNameProcessor() {
//capitalize_string_remaps["msec"] = "(msec)"; // Unit.
capitalize_string_remaps["msaa"] = "MSAA";
capitalize_string_remaps["nfc"] = "NFC";
+ capitalize_string_remaps["navmesh"] = "NavMesh";
capitalize_string_remaps["ok"] = "OK";
capitalize_string_remaps["opengl"] = "OpenGL";
capitalize_string_remaps["opentype"] = "OpenType";
diff --git a/editor/editor_resource_picker.cpp b/editor/editor_resource_picker.cpp
index a1d09d4df3..3c68a715c3 100644
--- a/editor/editor_resource_picker.cpp
+++ b/editor/editor_resource_picker.cpp
@@ -90,7 +90,8 @@ void EditorResourcePicker::_update_resource_preview(const String &p_path, const
if (p_preview.is_valid()) {
preview_rect->set_offset(SIDE_LEFT, assign_button->get_icon()->get_width() + assign_button->get_theme_stylebox(SNAME("normal"))->get_default_margin(SIDE_LEFT) + get_theme_constant(SNAME("h_separation"), SNAME("Button")));
- if (Ref<GradientTexture1D>(edited_resource).is_valid()) {
+ // Resource-specific stretching.
+ if (Ref<GradientTexture1D>(edited_resource).is_valid() || Ref<Gradient>(edited_resource).is_valid()) {
preview_rect->set_stretch_mode(TextureRect::STRETCH_SCALE);
assign_button->set_custom_minimum_size(Size2(1, 1));
} else {
diff --git a/editor/editor_run.cpp b/editor/editor_run.cpp
index 574acdff1c..6a2ff50ee0 100644
--- a/editor/editor_run.cpp
+++ b/editor/editor_run.cpp
@@ -98,67 +98,79 @@ Error EditorRun::run(const String &p_scene) {
screen_rect.position = DisplayServer::get_singleton()->screen_get_position(screen);
screen_rect.size = DisplayServer::get_singleton()->screen_get_size(screen);
- Size2 window_size;
- window_size.x = ProjectSettings::get_singleton()->get("display/window/size/viewport_width");
- window_size.y = ProjectSettings::get_singleton()->get("display/window/size/viewport_height");
-
- Size2 desired_size;
- desired_size.x = ProjectSettings::get_singleton()->get("display/window/size/window_width_override");
- desired_size.y = ProjectSettings::get_singleton()->get("display/window/size/window_height_override");
- if (desired_size.x > 0 && desired_size.y > 0) {
- window_size = desired_size;
- }
-
int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect");
- if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) {
- bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi");
- int display_scale = 1;
+ if (screen_rect != Rect2()) {
+ Size2 window_size;
+ window_size.x = ProjectSettings::get_singleton()->get("display/window/size/viewport_width");
+ window_size.y = ProjectSettings::get_singleton()->get("display/window/size/viewport_height");
+
+ Size2 desired_size;
+ desired_size.x = ProjectSettings::get_singleton()->get("display/window/size/window_width_override");
+ desired_size.y = ProjectSettings::get_singleton()->get("display/window/size/window_height_override");
+ if (desired_size.x > 0 && desired_size.y > 0) {
+ window_size = desired_size;
+ }
- if (OS::get_singleton()->is_hidpi_allowed()) {
- if (hidpi_proj) {
- display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale.
- } else {
- display_scale = DisplayServer::get_singleton()->screen_get_max_scale(); // Editor is in hiDPI mode, project is not, scale down.
- }
- } else {
- if (hidpi_proj) {
- display_scale = (1.f / DisplayServer::get_singleton()->screen_get_max_scale()); // Editor is not in hiDPI mode, project is, scale up.
+ if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) {
+ bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi");
+ int display_scale = 1;
+
+ if (OS::get_singleton()->is_hidpi_allowed()) {
+ if (hidpi_proj) {
+ display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale.
+ } else {
+ display_scale = DisplayServer::get_singleton()->screen_get_max_scale(); // Editor is in hiDPI mode, project is not, scale down.
+ }
} else {
- display_scale = 1; // Both editor and project runs in lowDPI mode, do not scale.
+ if (hidpi_proj) {
+ display_scale = (1.f / DisplayServer::get_singleton()->screen_get_max_scale()); // Editor is not in hiDPI mode, project is, scale up.
+ } else {
+ display_scale = 1; // Both editor and project runs in lowDPI mode, do not scale.
+ }
}
+ screen_rect.position /= display_scale;
+ screen_rect.size /= display_scale;
}
- screen_rect.position /= display_scale;
- screen_rect.size /= display_scale;
- }
- switch (window_placement) {
- case 0: { // top left
- args.push_back("--position");
- args.push_back(itos(screen_rect.position.x) + "," + itos(screen_rect.position.y));
- } break;
- case 1: { // centered
- Vector2 pos = (screen_rect.position) + ((screen_rect.size - window_size) / 2).floor();
- args.push_back("--position");
- args.push_back(itos(pos.x) + "," + itos(pos.y));
- } break;
- case 2: { // custom pos
- Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
- pos += screen_rect.position;
- args.push_back("--position");
- args.push_back(itos(pos.x) + "," + itos(pos.y));
- } break;
- case 3: { // force maximized
- Vector2 pos = screen_rect.position;
- args.push_back("--position");
- args.push_back(itos(pos.x) + "," + itos(pos.y));
- args.push_back("--maximized");
- } break;
- case 4: { // force fullscreen
- Vector2 pos = screen_rect.position;
- args.push_back("--position");
- args.push_back(itos(pos.x) + "," + itos(pos.y));
- args.push_back("--fullscreen");
- } break;
+ switch (window_placement) {
+ case 0: { // top left
+ args.push_back("--position");
+ args.push_back(itos(screen_rect.position.x) + "," + itos(screen_rect.position.y));
+ } break;
+ case 1: { // centered
+ Vector2 pos = (screen_rect.position) + ((screen_rect.size - window_size) / 2).floor();
+ args.push_back("--position");
+ args.push_back(itos(pos.x) + "," + itos(pos.y));
+ } break;
+ case 2: { // custom pos
+ Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
+ pos += screen_rect.position;
+ args.push_back("--position");
+ args.push_back(itos(pos.x) + "," + itos(pos.y));
+ } break;
+ case 3: { // force maximized
+ Vector2 pos = screen_rect.position;
+ args.push_back("--position");
+ args.push_back(itos(pos.x) + "," + itos(pos.y));
+ args.push_back("--maximized");
+ } break;
+ case 4: { // force fullscreen
+ Vector2 pos = screen_rect.position;
+ args.push_back("--position");
+ args.push_back(itos(pos.x) + "," + itos(pos.y));
+ args.push_back("--fullscreen");
+ } break;
+ }
+ } else {
+ // Unable to get screen info, skip setting position.
+ switch (window_placement) {
+ case 3: { // force maximized
+ args.push_back("--maximized");
+ } break;
+ case 4: { // force fullscreen
+ args.push_back("--fullscreen");
+ } break;
+ }
}
List<String> breakpoints;
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index 48f04694aa..bdabff20f9 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -1365,6 +1365,12 @@ float EditorSettings::get_auto_display_scale() const {
return DisplayServer::get_singleton()->screen_get_max_scale();
#else
const int screen = DisplayServer::get_singleton()->window_get_current_screen();
+
+ if (DisplayServer::get_singleton()->screen_get_size(screen) == Vector2i()) {
+ // Invalid screen size, skip.
+ return 1.0;
+ }
+
// Use the smallest dimension to use a correct display scale on portrait displays.
const int smallest_dimension = MIN(DisplayServer::get_singleton()->screen_get_size(screen).x, DisplayServer::get_singleton()->screen_get_size(screen).y);
if (DisplayServer::get_singleton()->screen_get_dpi(screen) >= 192 && smallest_dimension >= 1400) {
diff --git a/editor/export_template_manager.cpp b/editor/export_template_manager.cpp
index b34b08b5de..3526b4ce4c 100644
--- a/editor/export_template_manager.cpp
+++ b/editor/export_template_manager.cpp
@@ -128,7 +128,7 @@ void ExportTemplateManager::_download_current() {
}
_download_template(mirror_url, true);
- } else if (!mirrors_available && !is_refreshing_mirrors) {
+ } else if (!is_refreshing_mirrors) {
_set_current_progress_status(TTR("Retrieving the mirror list..."));
_refresh_mirrors();
}
diff --git a/editor/icons/ExternalLink.svg b/editor/icons/ExternalLink.svg
index 7fd78ae009..94148b2798 100644
--- a/editor/icons/ExternalLink.svg
+++ b/editor/icons/ExternalLink.svg
@@ -1 +1 @@
-<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><clipPath id="a"><path d="m0 0h16v16h-16z"/></clipPath><g clip-path="url(#a)" fill="#e0e0e0"><path d="m-1940-64.061 5.5-5.5-2.44-2.439h7v7l-2.439-2.439-5.5 5.5z" transform="translate(1944.939 73)"/><path d="m12 15h-8a3.079 3.079 0 0 1 -3-3v-8a3.04 3.04 0 0 1 3-3h2a1 1 0 0 1 0 2h-2a1.04 1.04 0 0 0 -1 1v8a1.083 1.083 0 0 0 1 1h8a1.068 1.068 0 0 0 1-1v-2a1 1 0 0 1 2 0v2a3.063 3.063 0 0 1 -3 3z"/></g></svg>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g fill="#e0e0e0"><path d="m-1940-64.061 5.5-5.5-2.44-2.439h7v7l-2.439-2.439-5.5 5.5z" transform="translate(1944.939 73)"/><path d="m12 15h-8a3.079 3.079 0 0 1 -3-3v-8a3.04 3.04 0 0 1 3-3h2a1 1 0 0 1 0 2h-2a1.04 1.04 0 0 0 -1 1v8a1.083 1.083 0 0 0 1 1h8a1.068 1.068 0 0 0 1-1v-2a1 1 0 0 1 2 0v2a3.063 3.063 0 0 1 -3 3z"/></g></svg>
diff --git a/editor/import/collada.cpp b/editor/import/collada.cpp
index fe32399fc6..af91ced570 100644
--- a/editor/import/collada.cpp
+++ b/editor/import/collada.cpp
@@ -58,7 +58,7 @@ Transform3D Collada::get_root_transform() const {
return unit_scale_transform;
}
-void Collada::Vertex::fix_unit_scale(Collada &state) {
+void Collada::Vertex::fix_unit_scale(const Collada &state) {
#ifdef COLLADA_IMPORT_SCALE_SCENE
vertex *= state.state.unit_scale;
#endif
@@ -122,7 +122,7 @@ static Transform3D _read_transform_from_array(const Vector<float> &array, int of
/* STRUCTURES */
-Transform3D Collada::Node::compute_transform(Collada &state) const {
+Transform3D Collada::Node::compute_transform(const Collada &state) const {
Transform3D xform;
for (int i = 0; i < xform_list.size(); i++) {
diff --git a/editor/import/collada.h b/editor/import/collada.h
index b5e4cd9983..df2b789081 100644
--- a/editor/import/collada.h
+++ b/editor/import/collada.h
@@ -266,7 +266,7 @@ public:
}
}
- void fix_unit_scale(Collada &state);
+ void fix_unit_scale(const Collada &state);
bool operator<(const Vertex &p_vert) const {
if (uid == p_vert.uid) {
@@ -348,7 +348,7 @@ public:
Node *parent = nullptr;
- Transform3D compute_transform(Collada &state) const;
+ Transform3D compute_transform(const Collada &state) const;
Transform3D get_global_transform() const;
Transform3D get_transform() const;
diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp
index de51a28c5a..6770eef543 100644
--- a/editor/import/resource_importer_texture.cpp
+++ b/editor/import/resource_importer_texture.cpp
@@ -198,12 +198,12 @@ int ResourceImporterTexture::get_preset_count() const {
String ResourceImporterTexture::get_preset_name(int p_idx) const {
static const char *preset_names[] = {
- "2D/3D (Auto-Detect)",
- "2D",
- "3D",
+ TTRC("2D/3D (Auto-Detect)"),
+ TTRC("2D"),
+ TTRC("3D"),
};
- return preset_names[p_idx];
+ return TTRGET(preset_names[p_idx]);
}
void ResourceImporterTexture::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
@@ -221,6 +221,7 @@ void ResourceImporterTexture::get_import_options(const String &p_path, List<Impo
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/premult_alpha"), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/normal_map_invert_y"), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_as_srgb"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_clamp_exposure"), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/size_limit", PROPERTY_HINT_RANGE, "0,4096,1"), 0));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "detect_3d/compress_to", PROPERTY_HINT_ENUM, "Disabled,VRAM Compressed,Basis Universal"), (p_preset == PRESET_DETECT) ? 1 : 0));
@@ -414,6 +415,7 @@ Error ResourceImporterTexture::import(const String &p_source_file, const String
const bool stream = false;
const int size_limit = p_options["process/size_limit"];
const bool hdr_as_srgb = p_options["process/hdr_as_srgb"];
+ const bool hdr_clamp_exposure = p_options["process/hdr_clamp_exposure"];
const int normal = p_options["compress/normal_map"];
const int hdr_compression = p_options["compress/hdr_compression"];
const int bptc_ldr = p_options["compress/bptc_ldr"];
@@ -485,6 +487,34 @@ Error ResourceImporterTexture::import(const String &p_source_file, const String
}
}
+ if (hdr_clamp_exposure) {
+ // Clamp HDR exposure following Filament's tonemapping formula.
+ // This can be used to reduce fireflies in environment maps or reduce the influence
+ // of the sun from an HDRI panorama on environment lighting (when a DirectionalLight3D is used instead).
+ const int height = image->get_height();
+ const int width = image->get_width();
+
+ // These values are chosen arbitrarily and seem to produce good results with 4,096 samples.
+ const float linear = 4096.0;
+ const float compressed = 16384.0;
+
+ for (int i = 0; i < width; i++) {
+ for (int j = 0; j < height; j++) {
+ const Color color = image->get_pixel(i, j);
+ const float luma = color.get_luminance();
+
+ Color clamped_color;
+ if (luma <= linear) {
+ clamped_color = color;
+ } else {
+ clamped_color = (color / luma) * ((linear * linear - compressed * luma) / (2 * linear - compressed - luma));
+ }
+
+ image->set_pixel(i, j, clamped_color);
+ }
+ }
+ }
+
if (compress_mode == COMPRESS_BASIS_UNIVERSAL && image->get_format() >= Image::FORMAT_RF) {
//basis universal does not support float formats, fall back
compress_mode = COMPRESS_VRAM_COMPRESSED;
diff --git a/editor/import/scene_import_settings.cpp b/editor/import/scene_import_settings.cpp
index 4e53a644ee..b08622b910 100644
--- a/editor/import/scene_import_settings.cpp
+++ b/editor/import/scene_import_settings.cpp
@@ -423,7 +423,7 @@ void SceneImportSettings::_update_view_gizmos() {
continue;
}
- TypedArray<Node> descendants = mesh_node->find_nodes("collider_view", "MeshInstance3D");
+ TypedArray<Node> descendants = mesh_node->find_children("collider_view", "MeshInstance3D");
CRASH_COND_MSG(descendants.is_empty(), "This is unreachable, since the collider view is always created even when the collision is not used! If this is triggered there is a bug on the function `_fill_scene`.");
diff --git a/editor/plugins/animation_library_editor.cpp b/editor/plugins/animation_library_editor.cpp
index 2e9a82a7c2..581c3c05a5 100644
--- a/editor/plugins/animation_library_editor.cpp
+++ b/editor/plugins/animation_library_editor.cpp
@@ -55,17 +55,15 @@ void AnimationLibraryEditor::_add_library_validate(const String &p_name) {
ERR_FAIL_COND(al.is_null());
if (p_name == "") {
error = TTR("Animation name can't be empty.");
-
- } else if (String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("[")) {
+ } else if (!AnimationLibrary::is_valid_name(p_name)) {
error = TTR("Animation name contains invalid characters: '/', ':', ',' or '['.");
} else if (al->has_animation(p_name)) {
error = TTR("Animation with the same name already exists.");
}
-
} else {
if (p_name == "" && bool(player->call("has_animation_library", ""))) {
error = TTR("Enter a library name.");
- } else if (String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("[")) {
+ } else if (!AnimationLibrary::is_valid_name(p_name)) {
error = TTR("Library name contains invalid characters: '/', ':', ',' or '['.");
} else if (bool(player->call("has_animation_library", p_name))) {
error = TTR("Library with the same name already exists.");
@@ -258,7 +256,7 @@ void AnimationLibraryEditor::_load_file(String p_path) {
}
}
- String name = p_path.get_file().get_basename();
+ String name = AnimationLibrary::validate_name(p_path.get_file().get_basename());
int attempt = 1;
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index 17a1bd1048..67d6c66c89 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -427,7 +427,7 @@ void AnimationPlayerEditor::_animation_name_edited() {
player->stop();
String new_name = name->get_text();
- if (new_name.is_empty() || new_name.contains(":") || new_name.contains("/")) {
+ if (!AnimationLibrary::is_valid_name(new_name)) {
error_dialog->set_text(TTR("Invalid animation name!"));
error_dialog->popup_centered();
return;
diff --git a/editor/plugins/animation_state_machine_editor.cpp b/editor/plugins/animation_state_machine_editor.cpp
index 2415615a45..8397772bf8 100644
--- a/editor/plugins/animation_state_machine_editor.cpp
+++ b/editor/plugins/animation_state_machine_editor.cpp
@@ -530,25 +530,25 @@ void AnimationNodeStateMachineEditor::_connection_draw(const Vector2 &p_from, co
state_machine_draw->draw_set_transform_matrix(Transform2D());
}
-void AnimationNodeStateMachineEditor::_clip_src_line_to_rect(Vector2 &r_from, Vector2 &r_to, const Rect2 &p_rect) {
- if (r_to == r_from) {
+void AnimationNodeStateMachineEditor::_clip_src_line_to_rect(Vector2 &r_from, const Vector2 &p_to, const Rect2 &p_rect) {
+ if (p_to == r_from) {
return;
}
//this could be optimized...
- Vector2 n = (r_to - r_from).normalized();
+ Vector2 n = (p_to - r_from).normalized();
while (p_rect.has_point(r_from)) {
r_from += n;
}
}
-void AnimationNodeStateMachineEditor::_clip_dst_line_to_rect(Vector2 &r_from, Vector2 &r_to, const Rect2 &p_rect) {
- if (r_to == r_from) {
+void AnimationNodeStateMachineEditor::_clip_dst_line_to_rect(const Vector2 &p_from, Vector2 &r_to, const Rect2 &p_rect) {
+ if (r_to == p_from) {
return;
}
//this could be optimized...
- Vector2 n = (r_to - r_from).normalized();
+ Vector2 n = (r_to - p_from).normalized();
while (p_rect.has_point(r_to)) {
r_to -= n;
}
diff --git a/editor/plugins/animation_state_machine_editor.h b/editor/plugins/animation_state_machine_editor.h
index bf3f7e93cf..fe3f6f370c 100644
--- a/editor/plugins/animation_state_machine_editor.h
+++ b/editor/plugins/animation_state_machine_editor.h
@@ -147,8 +147,8 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin {
void _open_editor(const String &p_name);
void _scroll_changed(double);
- void _clip_src_line_to_rect(Vector2 &r_from, Vector2 &r_to, const Rect2 &p_rect);
- void _clip_dst_line_to_rect(Vector2 &r_from, Vector2 &r_to, const Rect2 &p_rect);
+ void _clip_src_line_to_rect(Vector2 &r_from, const Vector2 &p_to, const Rect2 &p_rect);
+ void _clip_dst_line_to_rect(const Vector2 &p_from, Vector2 &r_to, const Rect2 &p_rect);
void _erase_selected();
void _update_mode();
diff --git a/editor/plugins/bit_map_editor_plugin.cpp b/editor/plugins/bit_map_editor_plugin.cpp
new file mode 100644
index 0000000000..9003c4480b
--- /dev/null
+++ b/editor/plugins/bit_map_editor_plugin.cpp
@@ -0,0 +1,86 @@
+/*************************************************************************/
+/* bit_map_editor_plugin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "bit_map_editor_plugin.h"
+
+#include "editor/editor_scale.h"
+
+void BitMapEditor::setup(const Ref<BitMap> &p_bitmap) {
+ Ref<ImageTexture> texture;
+ texture.instantiate();
+ texture->create_from_image(p_bitmap->convert_to_image());
+ texture_rect->set_texture(texture);
+
+ size_label->set_text(vformat(String::utf8("%s×%s"), p_bitmap->get_size().width, p_bitmap->get_size().height));
+}
+
+BitMapEditor::BitMapEditor() {
+ texture_rect = memnew(TextureRect);
+ texture_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
+ texture_rect->set_texture_filter(TEXTURE_FILTER_NEAREST);
+ texture_rect->set_custom_minimum_size(Size2(0, 250) * EDSCALE);
+ add_child(texture_rect);
+
+ size_label = memnew(Label);
+ size_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
+ add_child(size_label);
+
+ // Reduce extra padding on top and bottom of size label.
+ Ref<StyleBoxEmpty> stylebox;
+ stylebox.instantiate();
+ stylebox->set_default_margin(SIDE_RIGHT, 4 * EDSCALE);
+ size_label->add_theme_style_override("normal", stylebox);
+}
+
+///////////////////////
+
+bool EditorInspectorPluginBitMap::can_handle(Object *p_object) {
+ return Object::cast_to<BitMap>(p_object) != nullptr;
+}
+
+void EditorInspectorPluginBitMap::parse_begin(Object *p_object) {
+ BitMap *bitmap = Object::cast_to<BitMap>(p_object);
+ if (!bitmap) {
+ return;
+ }
+ Ref<BitMap> bm(bitmap);
+
+ BitMapEditor *editor = memnew(BitMapEditor);
+ editor->setup(bm);
+ add_custom_control(editor);
+}
+
+///////////////////////
+
+BitMapEditorPlugin::BitMapEditorPlugin() {
+ Ref<EditorInspectorPluginBitMap> plugin;
+ plugin.instantiate();
+ add_inspector_plugin(plugin);
+}
diff --git a/editor/plugins/bit_map_editor_plugin.h b/editor/plugins/bit_map_editor_plugin.h
new file mode 100644
index 0000000000..c883e5542f
--- /dev/null
+++ b/editor/plugins/bit_map_editor_plugin.h
@@ -0,0 +1,64 @@
+/*************************************************************************/
+/* bit_map_editor_plugin.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef BIT_MAP_PREVIEW_EDITOR_PLUGIN_H
+#define BIT_MAP_PREVIEW_EDITOR_PLUGIN_H
+
+#include "editor/editor_plugin.h"
+#include "scene/resources/bit_map.h"
+
+class BitMapEditor : public VBoxContainer {
+ GDCLASS(BitMapEditor, VBoxContainer);
+
+ TextureRect *texture_rect = nullptr;
+ Label *size_label = nullptr;
+
+public:
+ void setup(const Ref<BitMap> &p_bitmap);
+
+ BitMapEditor();
+};
+
+class EditorInspectorPluginBitMap : public EditorInspectorPlugin {
+ GDCLASS(EditorInspectorPluginBitMap, EditorInspectorPlugin);
+
+public:
+ virtual bool can_handle(Object *p_object) override;
+ virtual void parse_begin(Object *p_object) override;
+};
+
+class BitMapEditorPlugin : public EditorPlugin {
+ GDCLASS(BitMapEditorPlugin, EditorPlugin);
+
+public:
+ BitMapEditorPlugin();
+};
+
+#endif // BIT_MAP_PREVIEW_EDITOR_PLUGIN_H
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 8d0db697e2..c840ce22ce 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -3372,7 +3372,7 @@ void CanvasItemEditor::_draw_selection() {
// Draw the resize handles
if (tool == TOOL_SELECT && canvas_item->_edit_use_rect() && _is_node_movable(canvas_item)) {
Rect2 rect = canvas_item->_edit_get_rect();
- Vector2 endpoints[4] = {
+ const Vector2 endpoints[4] = {
xform.xform(rect.position),
xform.xform(rect.position + Vector2(rect.size.x, 0)),
xform.xform(rect.position + rect.size),
@@ -4575,7 +4575,7 @@ void CanvasItemEditor::_focus_selection(int p_op) {
Rect2 rect;
int count = 0;
- Map<Node *, Object *> &selection = editor_selection->get_selection();
+ const Map<Node *, Object *> &selection = editor_selection->get_selection();
for (const KeyValue<Node *, Object *> &E : selection) {
CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E.key);
if (!canvas_item) {
diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp
index b8556220d2..a160ca463b 100644
--- a/editor/plugins/editor_preview_plugins.cpp
+++ b/editor/plugins/editor_preview_plugins.cpp
@@ -904,3 +904,34 @@ EditorFontPreviewPlugin::~EditorFontPreviewPlugin() {
RS::get_singleton()->free(canvas);
RS::get_singleton()->free(viewport);
}
+
+////////////////////////////////////////////////////////////////////////////
+
+static const real_t GRADIENT_PREVIEW_TEXTURE_SCALE_FACTOR = 4.0;
+
+bool EditorGradientPreviewPlugin::handles(const String &p_type) const {
+ return ClassDB::is_parent_class(p_type, "Gradient");
+}
+
+bool EditorGradientPreviewPlugin::generate_small_preview_automatically() const {
+ return true;
+}
+
+Ref<Texture2D> EditorGradientPreviewPlugin::generate(const RES &p_from, const Size2 &p_size) const {
+ Ref<Gradient> gradient = p_from;
+ if (gradient.is_valid()) {
+ Ref<GradientTexture1D> ptex;
+ ptex.instantiate();
+ ptex->set_width(p_size.width * GRADIENT_PREVIEW_TEXTURE_SCALE_FACTOR * EDSCALE);
+ ptex->set_gradient(gradient);
+
+ Ref<ImageTexture> itex;
+ itex.instantiate();
+ itex->create_from_image(ptex->get_image());
+ return itex;
+ }
+ return Ref<Texture2D>();
+}
+
+EditorGradientPreviewPlugin::EditorGradientPreviewPlugin() {
+}
diff --git a/editor/plugins/editor_preview_plugins.h b/editor/plugins/editor_preview_plugins.h
index 803f03f17e..73eb90dd86 100644
--- a/editor/plugins/editor_preview_plugins.h
+++ b/editor/plugins/editor_preview_plugins.h
@@ -182,4 +182,15 @@ public:
EditorTileMapPatternPreviewPlugin();
~EditorTileMapPatternPreviewPlugin();
};
+
+class EditorGradientPreviewPlugin : public EditorResourcePreviewGenerator {
+ GDCLASS(EditorGradientPreviewPlugin, EditorResourcePreviewGenerator);
+
+public:
+ virtual bool handles(const String &p_type) const override;
+ virtual bool generate_small_preview_automatically() const override;
+ virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override;
+
+ EditorGradientPreviewPlugin();
+};
#endif // EDITORPREVIEWPLUGINS_H
diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.cpp b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
index b15aec87d9..72caa15e9c 100644
--- a/editor/plugins/gpu_particles_2d_editor_plugin.cpp
+++ b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
@@ -290,7 +290,7 @@ void GPUParticles2DEditorPlugin::_generate_emission_mask() {
{
uint8_t *tw = texdata.ptrw();
- float *twf = (float *)tw;
+ float *twf = reinterpret_cast<float *>(tw);
for (int i = 0; i < vpc; i++) {
twf[i * 2 + 0] = valid_positions[i].x;
twf[i * 2 + 1] = valid_positions[i].y;
@@ -334,7 +334,7 @@ void GPUParticles2DEditorPlugin::_generate_emission_mask() {
{
uint8_t *tw = normdata.ptrw();
- float *twf = (float *)tw;
+ float *twf = reinterpret_cast<float *>(tw);
for (int i = 0; i < vpc; i++) {
twf[i * 2 + 0] = valid_normals[i].x;
twf[i * 2 + 1] = valid_normals[i].y;
diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.cpp b/editor/plugins/gpu_particles_3d_editor_plugin.cpp
index 35cbff53f4..4b1081ed92 100644
--- a/editor/plugins/gpu_particles_3d_editor_plugin.cpp
+++ b/editor/plugins/gpu_particles_3d_editor_plugin.cpp
@@ -354,7 +354,7 @@ void GPUParticles3DEditor::_generate_emission_points() {
uint8_t *iw = point_img.ptrw();
memset(iw, 0, w * h * 3 * sizeof(float));
const Vector3 *r = points.ptr();
- float *wf = (float *)iw;
+ float *wf = reinterpret_cast<float *>(iw);
for (int i = 0; i < point_count; i++) {
wf[i * 3 + 0] = r[i].x;
wf[i * 3 + 1] = r[i].y;
@@ -383,7 +383,7 @@ void GPUParticles3DEditor::_generate_emission_points() {
uint8_t *iw = point_img2.ptrw();
memset(iw, 0, w * h * 3 * sizeof(float));
const Vector3 *r = normals.ptr();
- float *wf = (float *)iw;
+ float *wf = reinterpret_cast<float *>(iw);
for (int i = 0; i < point_count; i++) {
wf[i * 3 + 0] = r[i].x;
wf[i * 3 + 1] = r[i].y;
diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.h b/editor/plugins/gpu_particles_3d_editor_plugin.h
index 190fb9954b..6ba6d102ef 100644
--- a/editor/plugins/gpu_particles_3d_editor_plugin.h
+++ b/editor/plugins/gpu_particles_3d_editor_plugin.h
@@ -55,7 +55,7 @@ protected:
Vector<Face3> geometry;
bool _generate(Vector<Vector3> &points, Vector<Vector3> &normals);
- virtual void _generate_emission_points() = 0;
+ virtual void _generate_emission_points(){};
void _node_selected(const NodePath &p_path);
static void _bind_methods();
diff --git a/editor/plugins/node_3d_editor_gizmos.cpp b/editor/plugins/node_3d_editor_gizmos.cpp
index 179f78325c..47c8c66c57 100644
--- a/editor/plugins/node_3d_editor_gizmos.cpp
+++ b/editor/plugins/node_3d_editor_gizmos.cpp
@@ -476,7 +476,7 @@ void EditorNode3DGizmo::add_handles(const Vector<Vector3> &p_handles, const Ref<
}
}
-void EditorNode3DGizmo::add_solid_box(Ref<Material> &p_material, Vector3 p_size, Vector3 p_position, const Transform3D &p_xform) {
+void EditorNode3DGizmo::add_solid_box(const Ref<Material> &p_material, Vector3 p_size, Vector3 p_position, const Transform3D &p_xform) {
ERR_FAIL_COND(!spatial_node);
BoxMesh box_mesh;
diff --git a/editor/plugins/node_3d_editor_gizmos.h b/editor/plugins/node_3d_editor_gizmos.h
index 8adb753a51..f859ceda3b 100644
--- a/editor/plugins/node_3d_editor_gizmos.h
+++ b/editor/plugins/node_3d_editor_gizmos.h
@@ -99,7 +99,7 @@ public:
void add_collision_triangles(const Ref<TriangleMesh> &p_tmesh);
void add_unscaled_billboard(const Ref<Material> &p_material, real_t p_scale = 1, const Color &p_modulate = Color(1, 1, 1));
void add_handles(const Vector<Vector3> &p_handles, const Ref<Material> &p_material, const Vector<int> &p_ids = Vector<int>(), bool p_billboard = false, bool p_secondary = false);
- void add_solid_box(Ref<Material> &p_material, Vector3 p_size, Vector3 p_position = Vector3(), const Transform3D &p_xform = Transform3D());
+ void add_solid_box(const Ref<Material> &p_material, Vector3 p_size, Vector3 p_position = Vector3(), const Transform3D &p_xform = Transform3D());
virtual bool is_handle_highlighted(int p_id, bool p_secondary) const;
virtual String get_handle_name(int p_id, bool p_secondary) const;
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 6eed85e370..7e01593bda 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -2087,9 +2087,8 @@ void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const
const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
real_t pan_speed = 1 / 150.0;
- int pan_speed_modifier = 10;
if (nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
- pan_speed *= pan_speed_modifier;
+ pan_speed *= 10;
}
Transform3D camera_transform;
@@ -2112,9 +2111,8 @@ void Node3DEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const
const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
real_t zoom_speed = 1 / 80.0;
- int zoom_speed_modifier = 10;
if (nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
- zoom_speed *= zoom_speed_modifier;
+ zoom_speed *= 10;
}
NavigationZoomStyle zoom_style = (NavigationZoomStyle)EditorSettings::get_singleton()->get("editors/3d/navigation/zoom_style").operator int();
@@ -2818,7 +2816,7 @@ void Node3DEditorViewport::_draw() {
real_t scale_length = (max_speed - min_speed);
if (!Math::is_zero_approx(scale_length)) {
- real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length);
+ real_t logscale_t = 1.0 - Math::log1p(freelook_speed - min_speed) / Math::log1p(scale_length);
// Display the freelook speed to help the user get a better sense of scale.
const int precision = freelook_speed < 1.0 ? 2 : 1;
@@ -2841,7 +2839,7 @@ void Node3DEditorViewport::_draw() {
real_t scale_length = (max_distance - min_distance);
if (!Math::is_zero_approx(scale_length)) {
- real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length);
+ real_t logscale_t = 1.0 - Math::log1p(cursor.distance - min_distance) / Math::log1p(scale_length);
// Display the zoom center distance to help the user get a better sense of scale.
const int precision = cursor.distance < 1.0 ? 2 : 1;
@@ -3644,7 +3642,7 @@ void Node3DEditorViewport::focus_selection() {
Vector3 center;
int count = 0;
- List<Node *> &selection = editor_selection->get_selected_node_list();
+ const List<Node *> &selection = editor_selection->get_selected_node_list();
for (Node *E : selection) {
Node3D *sp = Object::cast_to<Node3D>(E);
@@ -5515,7 +5513,7 @@ void Node3DEditor::_xform_dialog_action() {
undo_redo->create_action(TTR("XForm Dialog"));
- List<Node *> &selection = editor_selection->get_selected_node_list();
+ const List<Node *> &selection = editor_selection->get_selected_node_list();
for (Node *E : selection) {
Node3D *sp = Object::cast_to<Node3D>(E);
@@ -6720,7 +6718,7 @@ Set<RID> _get_physics_bodies_rid(Node *node) {
}
void Node3DEditor::snap_selected_nodes_to_floor() {
- List<Node *> &selection = editor_selection->get_selected_node_list();
+ const List<Node *> &selection = editor_selection->get_selected_node_list();
Dictionary snap_data;
for (Node *E : selection) {
diff --git a/editor/plugins/path_3d_editor_plugin.cpp b/editor/plugins/path_3d_editor_plugin.cpp
index e52b274908..3284af7bb5 100644
--- a/editor/plugins/path_3d_editor_plugin.cpp
+++ b/editor/plugins/path_3d_editor_plugin.cpp
@@ -320,14 +320,14 @@ EditorPlugin::AfterGUIInput Path3DEditorPlugin::forward_spatial_gui_input(Camera
if (mb->is_pressed() && mb->get_button_index() == MouseButton::LEFT && (curve_create->is_pressed() || (curve_edit->is_pressed() && mb->is_ctrl_pressed()))) {
//click into curve, break it down
Vector<Vector3> v3a = c->tessellate();
- int idx = 0;
int rc = v3a.size();
int closest_seg = -1;
Vector3 closest_seg_point;
- float closest_d = 1e20;
if (rc >= 2) {
+ int idx = 0;
const Vector3 *r = v3a.ptr();
+ float closest_d = 1e20;
if (p_camera->unproject_position(gt.xform(c->get_point_position(0))).distance_to(mbpos) < click_dist) {
return EditorPlugin::AFTER_GUI_INPUT_PASS; //nope, existing
diff --git a/editor/plugins/ray_cast_2d_editor_plugin.cpp b/editor/plugins/ray_cast_2d_editor_plugin.cpp
new file mode 100644
index 0000000000..6f247a37ef
--- /dev/null
+++ b/editor/plugins/ray_cast_2d_editor_plugin.cpp
@@ -0,0 +1,151 @@
+/*************************************************************************/
+/* ray_cast_2d_editor_plugin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "ray_cast_2d_editor_plugin.h"
+
+#include "canvas_item_editor_plugin.h"
+#include "editor/editor_node.h"
+
+void RayCast2DEditor::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ get_tree()->connect("node_removed", callable_mp(this, &RayCast2DEditor::_node_removed));
+ } break;
+
+ case NOTIFICATION_EXIT_TREE: {
+ get_tree()->disconnect("node_removed", callable_mp(this, &RayCast2DEditor::_node_removed));
+ } break;
+ }
+}
+
+void RayCast2DEditor::_node_removed(Node *p_node) {
+ if (p_node == node) {
+ node = nullptr;
+ }
+}
+
+bool RayCast2DEditor::forward_canvas_gui_input(const Ref<InputEvent> &p_event) {
+ if (!node || !node->is_visible_in_tree()) {
+ return false;
+ }
+
+ Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
+
+ Ref<InputEventMouseButton> mb = p_event;
+ if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
+ if (mb->is_pressed()) {
+ if (xform.xform(node->get_target_position()).distance_to(mb->get_position()) < 8) {
+ pressed = true;
+ original_target_position = node->get_target_position();
+
+ return true;
+ } else {
+ pressed = false;
+
+ return false;
+ }
+ } else if (pressed) {
+ undo_redo->create_action(TTR("Set target_position"));
+ undo_redo->add_do_method(node, "set_target_position", node->get_target_position());
+ undo_redo->add_do_method(canvas_item_editor, "update_viewport");
+ undo_redo->add_undo_method(node, "set_target_position", original_target_position);
+ undo_redo->add_undo_method(canvas_item_editor, "update_viewport");
+ undo_redo->commit_action();
+
+ pressed = false;
+
+ return true;
+ }
+ }
+
+ Ref<InputEventMouseMotion> mm = p_event;
+ if (mm.is_valid() && pressed) {
+ Vector2 point = canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(mm->get_position()));
+ point = node->get_global_transform().affine_inverse().xform(point);
+
+ node->set_target_position(point);
+ canvas_item_editor->update_viewport();
+ node->notify_property_list_changed();
+
+ return true;
+ }
+
+ return false;
+}
+
+void RayCast2DEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
+ if (!node || !node->is_visible_in_tree()) {
+ return;
+ }
+
+ Transform2D gt = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
+
+ const Ref<Texture2D> handle = get_theme_icon(SNAME("EditorHandle"), SNAME("EditorIcons"));
+ p_overlay->draw_texture(handle, gt.xform(node->get_target_position()) - handle->get_size() / 2);
+}
+
+void RayCast2DEditor::edit(Node *p_node) {
+ if (!canvas_item_editor) {
+ canvas_item_editor = CanvasItemEditor::get_singleton();
+ }
+
+ if (p_node) {
+ node = Object::cast_to<RayCast2D>(p_node);
+ } else {
+ node = nullptr;
+ }
+
+ canvas_item_editor->update_viewport();
+}
+
+RayCast2DEditor::RayCast2DEditor() {
+ undo_redo = EditorNode::get_singleton()->get_undo_redo();
+}
+
+///////////////////////
+
+void RayCast2DEditorPlugin::edit(Object *p_object) {
+ ray_cast_2d_editor->edit(Object::cast_to<RayCast2D>(p_object));
+}
+
+bool RayCast2DEditorPlugin::handles(Object *p_object) const {
+ return Object::cast_to<RayCast2D>(p_object) != nullptr;
+}
+
+void RayCast2DEditorPlugin::make_visible(bool p_visible) {
+ if (!p_visible) {
+ edit(nullptr);
+ }
+}
+
+RayCast2DEditorPlugin::RayCast2DEditorPlugin() {
+ ray_cast_2d_editor = memnew(RayCast2DEditor);
+ EditorNode::get_singleton()->get_gui_base()->add_child(ray_cast_2d_editor);
+}
diff --git a/editor/plugins/ray_cast_2d_editor_plugin.h b/editor/plugins/ray_cast_2d_editor_plugin.h
new file mode 100644
index 0000000000..74628da0e4
--- /dev/null
+++ b/editor/plugins/ray_cast_2d_editor_plugin.h
@@ -0,0 +1,79 @@
+/*************************************************************************/
+/* ray_cast_2d_editor_plugin.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef RAY_CAST_2D_EDITOR_PLUGIN_H
+#define RAY_CAST_2D_EDITOR_PLUGIN_H
+
+#include "editor/editor_plugin.h"
+#include "scene/2d/ray_cast_2d.h"
+
+class CanvasItemEditor;
+
+class RayCast2DEditor : public Control {
+ GDCLASS(RayCast2DEditor, Control);
+
+ UndoRedo *undo_redo = nullptr;
+ CanvasItemEditor *canvas_item_editor = nullptr;
+ RayCast2D *node;
+
+ bool pressed = false;
+ Point2 original_target_position;
+
+protected:
+ void _notification(int p_what);
+ void _node_removed(Node *p_node);
+
+public:
+ bool forward_canvas_gui_input(const Ref<InputEvent> &p_event);
+ void forward_canvas_draw_over_viewport(Control *p_overlay);
+ void edit(Node *p_node);
+
+ RayCast2DEditor();
+};
+
+class RayCast2DEditorPlugin : public EditorPlugin {
+ GDCLASS(RayCast2DEditorPlugin, EditorPlugin);
+
+ RayCast2DEditor *ray_cast_2d_editor = nullptr;
+
+public:
+ virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return ray_cast_2d_editor->forward_canvas_gui_input(p_event); }
+ virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { ray_cast_2d_editor->forward_canvas_draw_over_viewport(p_overlay); }
+
+ virtual String get_name() const override { return "RayCast2D"; }
+ bool has_main_screen() const override { return false; }
+ virtual void edit(Object *p_object) override;
+ virtual bool handles(Object *p_object) const override;
+ virtual void make_visible(bool visible) override;
+
+ RayCast2DEditorPlugin();
+};
+
+#endif // RAY_CAST_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/skeleton_3d_editor_plugin.cpp b/editor/plugins/skeleton_3d_editor_plugin.cpp
index 065683d632..1b703a097c 100644
--- a/editor/plugins/skeleton_3d_editor_plugin.cpp
+++ b/editor/plugins/skeleton_3d_editor_plugin.cpp
@@ -1209,8 +1209,7 @@ void Skeleton3DGizmoPlugin::set_subgizmo_transform(const EditorNode3DGizmo *p_gi
t.basis = to_local * p_transform.get_basis();
// Origin.
- Vector3 orig = Vector3();
- orig = skeleton->get_bone_pose(p_id).origin;
+ Vector3 orig = skeleton->get_bone_pose(p_id).origin;
Vector3 sub = p_transform.origin - skeleton->get_bone_global_pose(p_id).origin;
t.origin = orig + to_local.xform(sub);
@@ -1283,9 +1282,6 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
surface_tool->set_material(unselected_mat);
}
- Vector<Transform3D> grests;
- grests.resize(skeleton->get_bone_count());
-
LocalVector<int> bones;
LocalVector<float> weights;
bones.resize(4);
@@ -1309,11 +1305,6 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
child_bones_vector = skeleton->get_bone_children(current_bone_idx);
int child_bones_size = child_bones_vector.size();
- // You have children but no parent, then you must be a root/parentless bone.
- if (skeleton->get_bone_parent(current_bone_idx) < 0) {
- grests.write[current_bone_idx] = skeleton->get_bone_rest(current_bone_idx);
- }
-
for (int i = 0; i < child_bones_size; i++) {
// Something wrong.
if (child_bones_vector[i] < 0) {
@@ -1322,10 +1313,8 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
int child_bone_idx = child_bones_vector[i];
- grests.write[child_bone_idx] = grests[current_bone_idx] * skeleton->get_bone_rest(child_bone_idx);
-
- Vector3 v0 = grests[current_bone_idx].origin;
- Vector3 v1 = grests[child_bone_idx].origin;
+ Vector3 v0 = skeleton->get_bone_global_rest(current_bone_idx).origin;
+ Vector3 v1 = skeleton->get_bone_global_rest(child_bone_idx).origin;
Vector3 d = (v1 - v0).normalized();
real_t dist = v0.distance_to(v1);
@@ -1333,7 +1322,7 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
int closest = -1;
real_t closest_d = 0.0;
for (int j = 0; j < 3; j++) {
- real_t dp = Math::abs(grests[current_bone_idx].basis[j].normalized().dot(d));
+ real_t dp = Math::abs(skeleton->get_bone_global_rest(current_bone_idx).basis[j].normalized().dot(d));
if (j == 0 || dp > closest_d) {
closest = j;
}
@@ -1360,7 +1349,7 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
for (int j = 0; j < 3; j++) {
Vector3 axis;
if (first == Vector3()) {
- axis = d.cross(d.cross(grests[current_bone_idx].basis[j])).normalized();
+ axis = d.cross(d.cross(skeleton->get_bone_global_rest(current_bone_idx).basis[j])).normalized();
first = axis;
} else {
axis = d.cross(first).normalized();
@@ -1415,7 +1404,7 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
surface_tool->add_vertex(v0);
surface_tool->set_bones(bones);
surface_tool->set_weights(weights);
- surface_tool->add_vertex(v0 + (grests[current_bone_idx].basis.inverse())[j].normalized() * dist * bone_axis_length);
+ surface_tool->add_vertex(v0 + (skeleton->get_bone_global_rest(current_bone_idx).basis.inverse())[j].normalized() * dist * bone_axis_length);
if (j == closest) {
continue;
@@ -1432,7 +1421,7 @@ void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
surface_tool->add_vertex(v1);
surface_tool->set_bones(bones);
surface_tool->set_weights(weights);
- surface_tool->add_vertex(v1 + (grests[child_bone_idx].basis.inverse())[j].normalized() * dist * bone_axis_length);
+ surface_tool->add_vertex(v1 + (skeleton->get_bone_global_rest(child_bone_idx).basis.inverse())[j].normalized() * dist * bone_axis_length);
if (j == closest) {
continue;
diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp
index 27160f8c86..29beb8be84 100644
--- a/editor/plugins/sprite_frames_editor_plugin.cpp
+++ b/editor/plugins/sprite_frames_editor_plugin.cpp
@@ -48,9 +48,6 @@ static void _draw_shadowed_line(Control *p_control, const Point2 &p_from, const
p_control->draw_line(p_from + p_shadow_offset, p_from + p_size + p_shadow_offset, p_shadow_color);
}
-void SpriteFramesEditor::gui_input(const Ref<InputEvent> &p_event) {
-}
-
void SpriteFramesEditor::_open_sprite_sheet() {
file_split_sheet->clear_filters();
List<String> extensions;
diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h
index 9a00fe5771..d31ce84d09 100644
--- a/editor/plugins/sprite_frames_editor_plugin.h
+++ b/editor/plugins/sprite_frames_editor_plugin.h
@@ -170,7 +170,6 @@ class SpriteFramesEditor : public HSplitContainer {
protected:
void _notification(int p_what);
- virtual void gui_input(const Ref<InputEvent> &p_event) override;
static void _bind_methods();
public:
diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp
index adb8590246..3fa12233a8 100644
--- a/editor/plugins/texture_region_editor_plugin.cpp
+++ b/editor/plugins/texture_region_editor_plugin.cpp
@@ -145,7 +145,7 @@ void TextureRegionEditor::_region_draw() {
}
} else if (snap_mode == SNAP_AUTOSLICE) {
for (const Rect2 &r : autoslice_cache) {
- Vector2 endpoints[4] = {
+ const Vector2 endpoints[4] = {
mtx.basis_xform(r.position),
mtx.basis_xform(r.position + Vector2(r.size.x, 0)),
mtx.basis_xform(r.position + r.size),
diff --git a/editor/plugins/tiles/tile_atlas_view.cpp b/editor/plugins/tiles/tile_atlas_view.cpp
index 71947ae185..4de2f42fe0 100644
--- a/editor/plugins/tiles/tile_atlas_view.cpp
+++ b/editor/plugins/tiles/tile_atlas_view.cpp
@@ -350,7 +350,7 @@ void TileAtlasView::_draw_alternatives() {
bool transposed = tile_data->get_transpose();
// Update the y to max value.
- Vector2i offset_pos = current_pos;
+ Vector2i offset_pos;
if (transposed) {
offset_pos = (current_pos + Vector2(texture_region_size.y, texture_region_size.x) / 2 + tile_set_atlas_source->get_tile_effective_texture_offset(atlas_coords, alternative_id));
y_increment = MAX(y_increment, texture_region_size.x);
diff --git a/editor/plugins/tiles/tile_data_editors.cpp b/editor/plugins/tiles/tile_data_editors.cpp
index 6c12573cc4..70bcd7e39a 100644
--- a/editor/plugins/tiles/tile_data_editors.cpp
+++ b/editor/plugins/tiles/tile_data_editors.cpp
@@ -2057,7 +2057,7 @@ void TileDataTerrainsEditor::forward_painting_atlas_gui_input(TileAtlasView *p_t
}
drag_last_pos = mb->get_position();
}
- } else if (tile_data && tile_data->get_terrain_set() == terrain_set) {
+ } else if (tile_data->get_terrain_set() == terrain_set) {
if (mb->is_ctrl_pressed()) {
// Paint terrain set with rect.
drag_type = DRAG_TYPE_PAINT_TERRAIN_BITS_RECT;
@@ -2387,7 +2387,7 @@ void TileDataTerrainsEditor::forward_painting_alternatives_gui_input(TileAtlasVi
tile_data->set_terrain_set(drag_painted_value);
}
drag_last_pos = mb->get_position();
- } else if (tile_data && tile_data->get_terrain_set() == terrain_set) {
+ } else if (tile_data->get_terrain_set() == terrain_set) {
// Paint terrain bits.
drag_type = DRAG_TYPE_PAINT_TERRAIN_BITS;
drag_modified.clear();
diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
index 144697698c..44b18f48fc 100644
--- a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
+++ b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp
@@ -1695,8 +1695,8 @@ void TileSetAtlasSourceEditor::_tile_atlas_control_draw() {
Size2 zoomed_size = resize_handle->get_size() / tile_atlas_view->get_zoom();
Rect2 region = tile_set_atlas_source->get_tile_texture_region(selected.tile);
Rect2 rect = region.grow_individual(zoomed_size.x, zoomed_size.y, 0, 0);
- Vector2i coords[] = { Vector2i(0, 0), Vector2i(1, 0), Vector2i(1, 1), Vector2i(0, 1) };
- Vector2i directions[] = { Vector2i(0, -1), Vector2i(1, 0), Vector2i(0, 1), Vector2i(-1, 0) };
+ const Vector2i coords[] = { Vector2i(0, 0), Vector2i(1, 0), Vector2i(1, 1), Vector2i(0, 1) };
+ const Vector2i directions[] = { Vector2i(0, -1), Vector2i(1, 0), Vector2i(0, 1), Vector2i(-1, 0) };
bool can_grow[4];
for (int i = 0; i < 4; i++) {
can_grow[i] = tile_set_atlas_source->has_room_for_tile(selected.tile + directions[i], tile_set_atlas_source->get_tile_size_in_atlas(selected.tile), tile_set_atlas_source->get_tile_animation_columns(selected.tile), tile_set_atlas_source->get_tile_animation_separation(selected.tile), tile_set_atlas_source->get_tile_animation_frames_count(selected.tile), selected.tile);
diff --git a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.cpp b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.cpp
index 21ebcbd655..9a4b14616f 100644
--- a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.cpp
+++ b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.cpp
@@ -394,13 +394,12 @@ void TileSetScenesCollectionSourceEditor::_drop_data_fw(const Point2 &p_point, c
if (p_from == scene_tiles_list) {
// Handle dropping a texture in the list of atlas resources.
- int scene_id = -1;
Dictionary d = p_data;
Vector<String> files = d["files"];
for (int i = 0; i < files.size(); i++) {
Ref<PackedScene> resource = ResourceLoader::load(files[i]);
if (resource.is_valid()) {
- scene_id = tile_set_scenes_collection_source->get_next_scene_tile_id();
+ int scene_id = tile_set_scenes_collection_source->get_next_scene_tile_id();
undo_redo->create_action(TTR("Add a Scene Tile"));
undo_redo->add_do_method(tile_set_scenes_collection_source, "create_scene_tile", resource, scene_id);
undo_redo->add_undo_method(tile_set_scenes_collection_source, "remove_scene_tile", scene_id);
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index c4a5ec7a87..dc07ac7c39 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -119,7 +119,7 @@ void VisualShaderGraphPlugin::register_shader(VisualShader *p_shader) {
visual_shader = Ref<VisualShader>(p_shader);
}
-void VisualShaderGraphPlugin::set_connections(List<VisualShader::Connection> &p_connections) {
+void VisualShaderGraphPlugin::set_connections(const List<VisualShader::Connection> &p_connections) {
connections = p_connections;
}
@@ -2765,9 +2765,9 @@ void VisualShaderEditor::_add_node(int p_idx, const Vector<Variant> &p_ops, Stri
}
if (vsnode->get_output_port_count() > 0 || created_expression_port) {
int _from_node = id_to_use;
- int _from_slot = 0;
if (created_expression_port) {
+ int _from_slot = 0;
undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, _from_node, _from_slot, to_node, to_slot);
undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, _from_node, _from_slot, to_node, to_slot);
undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, _from_node, _from_slot, to_node, to_slot);
@@ -2805,9 +2805,9 @@ void VisualShaderEditor::_add_node(int p_idx, const Vector<Variant> &p_ops, Stri
if (vsnode->get_input_port_count() > 0 || created_expression_port) {
int _to_node = id_to_use;
- int _to_slot = 0;
if (created_expression_port) {
+ int _to_slot = 0;
undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, _to_slot);
undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, _to_slot);
undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, _to_slot);
diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h
index 9f82b2ed7f..8db2cf07f9 100644
--- a/editor/plugins/visual_shader_editor_plugin.h
+++ b/editor/plugins/visual_shader_editor_plugin.h
@@ -92,7 +92,7 @@ protected:
public:
void register_shader(VisualShader *p_visual_shader);
- void set_connections(List<VisualShader::Connection> &p_connections);
+ void set_connections(const List<VisualShader::Connection> &p_connections);
void register_link(VisualShader::Type p_type, int p_id, VisualShaderNode *p_visual_node, GraphNode *p_graph_node);
void register_output_port(int p_id, int p_port, TextureButton *p_button);
void register_uniform_name(int p_id, LineEdit *p_uniform_name);
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 81df7ee30a..9c745e6a41 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -575,16 +575,16 @@ private:
unzClose(pkg);
if (failed_files.size()) {
- String msg = TTR("The following files failed extraction from package:") + "\n\n";
+ String err_msg = TTR("The following files failed extraction from package:") + "\n\n";
for (int i = 0; i < failed_files.size(); i++) {
if (i > 15) {
- msg += "\nAnd " + itos(failed_files.size() - i) + " more files.";
+ err_msg += "\nAnd " + itos(failed_files.size() - i) + " more files.";
break;
}
- msg += failed_files[i] + "\n";
+ err_msg += failed_files[i] + "\n";
}
- dialog_error->set_text(msg);
+ dialog_error->set_text(err_msg);
dialog_error->popup_centered();
} else if (!project_path->get_text().ends_with(".zip")) {
@@ -2877,17 +2877,15 @@ ProjectManager::ProjectManager() {
Vector2i screen_size = DisplayServer::get_singleton()->screen_get_size();
Vector2i screen_position = DisplayServer::get_singleton()->screen_get_position();
- // Consider the editor display scale.
- window_size.x = round((float)window_size.x * scale_factor);
- window_size.y = round((float)window_size.y * scale_factor);
-
- // Make the window centered on the screen.
- Vector2i window_position;
- window_position.x = screen_position.x + (screen_size.x - window_size.x) / 2;
- window_position.y = screen_position.y + (screen_size.y - window_size.y) / 2;
+ window_size *= scale_factor;
DisplayServer::get_singleton()->window_set_size(window_size);
- DisplayServer::get_singleton()->window_set_position(window_position);
+ if (screen_size != Vector2i()) {
+ Vector2i window_position;
+ window_position.x = screen_position.x + (screen_size.x - window_size.x) / 2;
+ window_position.y = screen_position.y + (screen_size.y - window_size.y) / 2;
+ DisplayServer::get_singleton()->window_set_position(window_position);
+ }
}
OS::get_singleton()->set_low_processor_usage_mode(true);
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index c63471720b..3e8eb6b4ee 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -2999,7 +2999,7 @@ void SceneTreeDock::attach_shader_to_selected(int p_preferred_mode) {
shader_create_dialog->popup_centered();
}
-void SceneTreeDock::open_shader_dialog(Ref<ShaderMaterial> &p_for_material, int p_preferred_mode) {
+void SceneTreeDock::open_shader_dialog(const Ref<ShaderMaterial> &p_for_material, int p_preferred_mode) {
selected_shader_material = p_for_material;
attach_shader_to_selected(p_preferred_mode);
}
diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h
index 842995dfe3..77e727b2c8 100644
--- a/editor/scene_tree_dock.h
+++ b/editor/scene_tree_dock.h
@@ -309,7 +309,7 @@ public:
void open_script_dialog(Node *p_for_node, bool p_extend);
void attach_shader_to_selected(int p_preferred_mode = -1);
- void open_shader_dialog(Ref<ShaderMaterial> &p_for_material, int p_preferred_mode = -1);
+ void open_shader_dialog(const Ref<ShaderMaterial> &p_for_material, int p_preferred_mode = -1);
void open_add_child_dialog();
void open_instance_child_dialog();
diff --git a/main/main.cpp b/main/main.cpp
index f20ec94fa5..755924929c 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -120,10 +120,10 @@ static RenderingServer *rendering_server = nullptr;
static CameraServer *camera_server = nullptr;
static XRServer *xr_server = nullptr;
static TextServerManager *tsman = nullptr;
-static PhysicsServer3D *physics_server = nullptr;
-static PhysicsServer2D *physics_2d_server = nullptr;
-static NavigationServer3D *navigation_server = nullptr;
-static NavigationServer2D *navigation_2d_server = nullptr;
+static PhysicsServer3D *physics_server_3d = nullptr;
+static PhysicsServer2D *physics_server_2d = nullptr;
+static NavigationServer3D *navigation_server_3d = nullptr;
+static NavigationServer2D *navigation_server_2d = nullptr;
// We error out if setup2() doesn't turn this true
static bool _start_success = false;
@@ -204,32 +204,32 @@ static String get_full_version_string() {
// to have less code in main.cpp.
void initialize_physics() {
/// 3D Physics Server
- physics_server = PhysicsServer3DManager::new_server(
+ physics_server_3d = PhysicsServer3DManager::new_server(
ProjectSettings::get_singleton()->get(PhysicsServer3DManager::setting_property_name));
- if (!physics_server) {
+ if (!physics_server_3d) {
// Physics server not found, Use the default physics
- physics_server = PhysicsServer3DManager::new_default_server();
+ physics_server_3d = PhysicsServer3DManager::new_default_server();
}
- ERR_FAIL_COND(!physics_server);
- physics_server->init();
+ ERR_FAIL_COND(!physics_server_3d);
+ physics_server_3d->init();
/// 2D Physics server
- physics_2d_server = PhysicsServer2DManager::new_server(
+ physics_server_2d = PhysicsServer2DManager::new_server(
ProjectSettings::get_singleton()->get(PhysicsServer2DManager::setting_property_name));
- if (!physics_2d_server) {
+ if (!physics_server_2d) {
// Physics server not found, Use the default physics
- physics_2d_server = PhysicsServer2DManager::new_default_server();
+ physics_server_2d = PhysicsServer2DManager::new_default_server();
}
- ERR_FAIL_COND(!physics_2d_server);
- physics_2d_server->init();
+ ERR_FAIL_COND(!physics_server_2d);
+ physics_server_2d->init();
}
void finalize_physics() {
- physics_server->finish();
- memdelete(physics_server);
+ physics_server_3d->finish();
+ memdelete(physics_server_3d);
- physics_2d_server->finish();
- memdelete(physics_2d_server);
+ physics_server_2d->finish();
+ memdelete(physics_server_2d);
}
void finalize_display() {
@@ -240,18 +240,18 @@ void finalize_display() {
}
void initialize_navigation_server() {
- ERR_FAIL_COND(navigation_server != nullptr);
+ ERR_FAIL_COND(navigation_server_3d != nullptr);
- navigation_server = NavigationServer3DManager::new_default_server();
- navigation_2d_server = memnew(NavigationServer2D);
+ navigation_server_3d = NavigationServer3DManager::new_default_server();
+ navigation_server_2d = memnew(NavigationServer2D);
}
void finalize_navigation_server() {
- memdelete(navigation_server);
- navigation_server = nullptr;
+ memdelete(navigation_server_3d);
+ navigation_server_3d = nullptr;
- memdelete(navigation_2d_server);
- navigation_2d_server = nullptr;
+ memdelete(navigation_server_2d);
+ navigation_server_2d = nullptr;
}
//#define DEBUG_INIT
diff --git a/modules/csg/editor/csg_gizmos.cpp b/modules/csg/editor/csg_gizmos.cpp
index be29810252..4d972e46c6 100644
--- a/modules/csg/editor/csg_gizmos.cpp
+++ b/modules/csg/editor/csg_gizmos.cpp
@@ -347,14 +347,12 @@ void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
p_gizmo->add_lines(lines, material);
p_gizmo->add_collision_segments(lines);
- Array csg_meshes = cs->get_meshes();
- if (csg_meshes.size() != 2) {
- return;
- }
-
- Ref<Mesh> csg_mesh = csg_meshes[1];
- if (csg_mesh.is_valid()) {
- p_gizmo->add_collision_triangles(csg_mesh->generate_triangle_mesh());
+ if (cs->is_root_shape()) {
+ Array csg_meshes = cs->get_meshes();
+ Ref<Mesh> csg_mesh = csg_meshes[1];
+ if (csg_mesh.is_valid()) {
+ p_gizmo->add_collision_triangles(csg_mesh->generate_triangle_mesh());
+ }
}
if (p_gizmo->is_selected()) {
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 59254fc3ad..55c7ace938 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -1032,7 +1032,13 @@ Error GDScript::load_source_code(const String &p_path) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V(err, err);
+ const char *err_name;
+ if (err < 0 || err >= ERR_MAX) {
+ err_name = "(invalid error code)";
+ } else {
+ err_name = error_names[err];
+ }
+ ERR_FAIL_COND_V_MSG(err, err, "Attempt to open script '" + p_path + "' resulted in error '" + err_name + "'.");
}
uint64_t len = f->get_length();
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index 79171cac73..caca7d8ca5 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -262,6 +262,7 @@ class GDScriptInstance : public ScriptInstance {
friend class GDScript;
friend class GDScriptFunction;
friend class GDScriptLambdaCallable;
+ friend class GDScriptLambdaSelfCallable;
friend class GDScriptCompiler;
friend struct GDScriptUtilityFunctionsDefinitions;
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index 01118a6b4f..d346264933 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -2498,12 +2498,17 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a
}
if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
- push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parser->current_function->identifier->name), p_call);
+ // Get the parent function above any lambda.
+ GDScriptParser::FunctionNode *parent_function = parser->current_function;
+ while (parent_function->source_lambda) {
+ parent_function = parent_function->source_lambda->parent_function;
+ }
+ push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);
} else if (!is_self && base_type.is_meta_type && !is_static) {
base_type.is_meta_type = false; // For `to_string()`.
push_error(vformat(R"*(Cannot call non-static function "%s()" on the class "%s" directly. Make an instance instead.)*", p_call->function_name, base_type.to_string()), p_call);
- } else if (is_self && !is_static && !lambda_stack.is_empty()) {
- push_error(vformat(R"*(Cannot call non-static function "%s()" from a lambda function.)*", p_call->function_name), p_call);
+ } else if (is_self && !is_static) {
+ mark_lambda_use_self();
}
call_type = return_type;
@@ -2636,10 +2641,10 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node)
if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, result.native_type)) {
push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
- } else if (!lambda_stack.is_empty()) {
- push_error(R"*(Cannot use shorthand "get_node()" notation ("$") inside a lambda. Use a captured variable instead.)*", p_get_node);
}
+ mark_lambda_use_self();
+
p_get_node->set_datatype(result);
}
@@ -2854,21 +2859,25 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod
MethodBind *getter = ClassDB::get_method(native, getter_name);
if (getter != nullptr) {
p_identifier->set_datatype(type_from_property(getter->get_return_info()));
+ p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
}
return;
}
if (ClassDB::get_method_info(native, name, &method_info)) {
// Method is callable.
p_identifier->set_datatype(make_callable_type(method_info));
+ p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
return;
}
if (ClassDB::get_signal(native, name, &method_info)) {
// Signal is a type too.
p_identifier->set_datatype(make_signal_type(method_info));
+ p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
return;
}
if (ClassDB::has_enum(native, name)) {
p_identifier->set_datatype(make_native_enum_type(native, name));
+ p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
return;
}
bool valid = false;
@@ -2877,6 +2886,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod
p_identifier->is_constant = true;
p_identifier->reduced_value = int_constant;
p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
+ p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
return;
}
}
@@ -2927,7 +2937,11 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident
p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
found_source = true;
break;
+ case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
+ mark_lambda_use_self();
+ break;
case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
+ mark_lambda_use_self();
p_identifier->variable_source->usages++;
[[fallthrough]];
case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
@@ -2958,18 +2972,37 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident
}
if (found_source) {
- // If the identifier is local, check if it's any kind of capture by comparing their source function.
- // Only capture locals and members and enum values. Constants are still accessible from the lambda using the script reference.
- if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT || lambda_stack.is_empty()) {
- return;
+ if ((p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE) && parser->current_function && parser->current_function->is_static) {
+ // Get the parent function above any lambda.
+ GDScriptParser::FunctionNode *parent_function = parser->current_function;
+ while (parent_function->source_lambda) {
+ parent_function = parent_function->source_lambda->parent_function;
+ }
+ push_error(vformat(R"*(Cannot access instance variable "%s" from the static function "%s()".)*", p_identifier->name, parent_function->identifier->name), p_identifier);
}
- GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
- while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {
- function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
- function_test->source_lambda->captures.push_back(p_identifier);
- function_test = function_test->source_lambda->parent_function;
+ if (!lambda_stack.is_empty()) {
+ // If the identifier is a member variable (including the native class properties), we consider the lambda to be using `self`, so we keep a reference to the current instance.
+ if (p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE) {
+ mark_lambda_use_self();
+ return; // No need to capture.
+ }
+ // If the identifier is local, check if it's any kind of capture by comparing their source function.
+ // Only capture locals and enum values. Constants are still accessible from the lambda using the script reference. If not, this method is done.
+ if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT) {
+ return;
+ }
+
+ GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
+ // Make sure we aren't capturing variable in the same lambda.
+ // This also add captures for nested lambdas.
+ while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {
+ function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
+ function_test->source_lambda->captures.push_back(p_identifier);
+ function_test = function_test->source_lambda->parent_function;
+ }
}
+
return;
}
@@ -3149,6 +3182,7 @@ void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
p_self->is_constant = false;
p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
+ mark_lambda_use_self();
}
void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
@@ -3159,6 +3193,12 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri
reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
} else {
reduce_expression(p_subscript->base);
+
+ if (p_subscript->base->type == GDScriptParser::Node::ARRAY) {
+ const_fold_array(static_cast<GDScriptParser::ArrayNode *>(p_subscript->base));
+ } else if (p_subscript->base->type == GDScriptParser::Node::DICTIONARY) {
+ const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_subscript->base));
+ }
}
GDScriptParser::DataType result_type;
@@ -3476,6 +3516,13 @@ void GDScriptAnalyzer::const_fold_array(GDScriptParser::ArrayNode *p_array) {
for (int i = 0; i < p_array->elements.size(); i++) {
GDScriptParser::ExpressionNode *element = p_array->elements[i];
+
+ if (element->type == GDScriptParser::Node::ARRAY) {
+ const_fold_array(static_cast<GDScriptParser::ArrayNode *>(element));
+ } else if (element->type == GDScriptParser::Node::DICTIONARY) {
+ const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(element));
+ }
+
all_is_constant = all_is_constant && element->is_constant;
if (!all_is_constant) {
return;
@@ -3496,6 +3543,13 @@ void GDScriptAnalyzer::const_fold_dictionary(GDScriptParser::DictionaryNode *p_d
for (int i = 0; i < p_dictionary->elements.size(); i++) {
const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
+
+ if (element.value->type == GDScriptParser::Node::ARRAY) {
+ const_fold_array(static_cast<GDScriptParser::ArrayNode *>(element.value));
+ } else if (element.value->type == GDScriptParser::Node::DICTIONARY) {
+ const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(element.value));
+ }
+
all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
if (!all_is_constant) {
return;
@@ -4121,6 +4175,12 @@ void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
#endif
}
+void GDScriptAnalyzer::mark_lambda_use_self() {
+ for (GDScriptParser::LambdaNode *lambda : lambda_stack) {
+ lambda->use_self = true;
+ }
+}
+
bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
}
diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h
index 7b8883e1d3..519e1975c4 100644
--- a/modules/gdscript/gdscript_analyzer.h
+++ b/modules/gdscript/gdscript_analyzer.h
@@ -42,7 +42,7 @@ class GDScriptAnalyzer {
HashMap<String, Ref<GDScriptParserRef>> depended_parsers;
const GDScriptParser::EnumNode *current_enum = nullptr;
- List<const GDScriptParser::LambdaNode *> lambda_stack;
+ List<GDScriptParser::LambdaNode *> lambda_stack;
// Tests for detecting invalid overloading of script members
static _FORCE_INLINE_ bool has_member_name_conflict_in_script_class(const StringName &p_name, const GDScriptParser::ClassNode *p_current_class_node);
@@ -115,6 +115,7 @@ class GDScriptAnalyzer {
bool is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion = false, const GDScriptParser::Node *p_source_node = nullptr);
void push_error(const String &p_message, const GDScriptParser::Node *p_origin);
void mark_node_unsafe(const GDScriptParser::Node *p_node);
+ void mark_lambda_use_self();
bool class_exists(const StringName &p_class) const;
Ref<GDScriptParserRef> get_parser_for(const String &p_path);
#ifdef DEBUG_ENABLED
diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp
index a7e25f5aab..e72069bcd5 100644
--- a/modules/gdscript/gdscript_byte_codegen.cpp
+++ b/modules/gdscript/gdscript_byte_codegen.cpp
@@ -1211,8 +1211,8 @@ void GDScriptByteCodeGenerator::write_call_script_function(const Address &p_targ
append(p_function_name);
}
-void GDScriptByteCodeGenerator::write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) {
- append(GDScriptFunction::OPCODE_CREATE_LAMBDA, 1 + p_captures.size());
+void GDScriptByteCodeGenerator::write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures, bool p_use_self) {
+ append(p_use_self ? GDScriptFunction::OPCODE_CREATE_SELF_LAMBDA : GDScriptFunction::OPCODE_CREATE_LAMBDA, 1 + p_captures.size());
for (int i = 0; i < p_captures.size(); i++) {
append(p_captures[i]);
}
diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h
index 222ae13390..0503f66161 100644
--- a/modules/gdscript/gdscript_byte_codegen.h
+++ b/modules/gdscript/gdscript_byte_codegen.h
@@ -470,7 +470,7 @@ public:
virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
- virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) override;
+ virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures, bool p_use_self) override;
virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) override;
virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) override;
virtual void write_construct_typed_array(const Address &p_target, const GDScriptDataType &p_element_type, const Vector<Address> &p_arguments) override;
diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h
index 3d42ce06c0..326b66a295 100644
--- a/modules/gdscript/gdscript_codegen.h
+++ b/modules/gdscript/gdscript_codegen.h
@@ -131,7 +131,7 @@ public:
virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
- virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) = 0;
+ virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures, bool p_use_self) = 0;
virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) = 0;
virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) = 0;
virtual void write_construct_typed_array(const Address &p_target, const GDScriptDataType &p_element_type, const Vector<Address> &p_arguments) = 0;
diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp
index 0138147fcc..225c2d0d45 100644
--- a/modules/gdscript/gdscript_compiler.cpp
+++ b/modules/gdscript/gdscript_compiler.cpp
@@ -1197,7 +1197,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code
return GDScriptCodeGenerator::Address();
}
- gen->write_lambda(result, function, captures);
+ gen->write_lambda(result, function, captures, lambda->use_self);
for (int i = 0; i < captures.size(); i++) {
if (captures[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp
index 74090d0aa9..dc114f2eff 100644
--- a/modules/gdscript/gdscript_disassembler.cpp
+++ b/modules/gdscript/gdscript_disassembler.cpp
@@ -792,6 +792,25 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const {
incr = 3 + captures_count;
} break;
+ case OPCODE_CREATE_SELF_LAMBDA: {
+ int captures_count = _code_ptr[ip + 1 + instr_var_args];
+ GDScriptFunction *lambda = _lambdas_ptr[_code_ptr[ip + 2 + instr_var_args]];
+
+ text += DADDR(1 + captures_count);
+ text += "create self lambda from ";
+ text += lambda->name.operator String();
+ text += "function, captures (";
+
+ for (int i = 0; i < captures_count; i++) {
+ if (i > 0) {
+ text += ", ";
+ }
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 3 + captures_count;
+ } break;
case OPCODE_JUMP: {
text += "jump ";
text += itos(_code_ptr[ip + 1]);
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index 718df7a0a6..b3f9914b7d 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -1140,7 +1140,7 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base
}
}
-static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool p_only_functions, Map<String, ScriptLanguage::CodeCompletionOption> &r_result, int p_recursion_depth) {
+static void _find_identifiers(const GDScriptParser::CompletionContext &p_context, bool p_only_functions, Map<String, ScriptLanguage::CodeCompletionOption> &r_result, int p_recursion_depth) {
if (!p_only_functions && p_context.current_suite) {
// This includes function parameters, since they are also locals.
_find_identifiers_in_suite(p_context.current_suite, r_result);
diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h
index d07a167ca2..ba0d51c5cc 100644
--- a/modules/gdscript/gdscript_function.h
+++ b/modules/gdscript/gdscript_function.h
@@ -299,6 +299,7 @@ public:
OPCODE_AWAIT,
OPCODE_AWAIT_RESUME,
OPCODE_CREATE_LAMBDA,
+ OPCODE_CREATE_SELF_LAMBDA,
OPCODE_JUMP,
OPCODE_JUMP_IF,
OPCODE_JUMP_IF_NOT,
diff --git a/modules/gdscript/gdscript_lambda_callable.cpp b/modules/gdscript/gdscript_lambda_callable.cpp
index baf93e1098..c43fa12c8c 100644
--- a/modules/gdscript/gdscript_lambda_callable.cpp
+++ b/modules/gdscript/gdscript_lambda_callable.cpp
@@ -93,3 +93,81 @@ GDScriptLambdaCallable::GDScriptLambdaCallable(Ref<GDScript> p_script, GDScriptF
h = (uint32_t)hash_djb2_one_64((uint64_t)this);
}
+
+bool GDScriptLambdaSelfCallable::compare_equal(const CallableCustom *p_a, const CallableCustom *p_b) {
+ // Lambda callables are only compared by reference.
+ return p_a == p_b;
+}
+
+bool GDScriptLambdaSelfCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
+ // Lambda callables are only compared by reference.
+ return p_a < p_b;
+}
+
+uint32_t GDScriptLambdaSelfCallable::hash() const {
+ return h;
+}
+
+String GDScriptLambdaSelfCallable::get_as_text() const {
+ if (function->get_name() != StringName()) {
+ return function->get_name().operator String() + "(lambda)";
+ }
+ return "(anonymous lambda)";
+}
+
+CallableCustom::CompareEqualFunc GDScriptLambdaSelfCallable::get_compare_equal_func() const {
+ return compare_equal;
+}
+
+CallableCustom::CompareLessFunc GDScriptLambdaSelfCallable::get_compare_less_func() const {
+ return compare_less;
+}
+
+ObjectID GDScriptLambdaSelfCallable::get_object() const {
+ return object->get_instance_id();
+}
+
+void GDScriptLambdaSelfCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
+#ifdef DEBUG_ENABLED
+ if (object->get_script_instance() == nullptr || object->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) {
+ ERR_PRINT("Trying to call a lambda with an invalid instance.");
+ r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ return;
+ }
+#endif
+
+ int captures_amount = captures.size();
+
+ if (captures_amount > 0) {
+ Vector<const Variant *> args;
+ args.resize(p_argcount + captures_amount);
+ for (int i = 0; i < captures_amount; i++) {
+ args.write[i] = &captures[i];
+ }
+ for (int i = 0; i < p_argcount; i++) {
+ args.write[i + captures_amount] = p_arguments[i];
+ }
+
+ r_return_value = function->call(static_cast<GDScriptInstance *>(object->get_script_instance()), args.ptrw(), args.size(), r_call_error);
+ r_call_error.argument -= captures_amount;
+ } else {
+ r_return_value = function->call(static_cast<GDScriptInstance *>(object->get_script_instance()), p_arguments, p_argcount, r_call_error);
+ }
+}
+
+GDScriptLambdaSelfCallable::GDScriptLambdaSelfCallable(Ref<RefCounted> p_self, GDScriptFunction *p_function, const Vector<Variant> &p_captures) {
+ reference = p_self;
+ object = p_self.ptr();
+ function = p_function;
+ captures = p_captures;
+
+ h = (uint32_t)hash_djb2_one_64((uint64_t)this);
+}
+
+GDScriptLambdaSelfCallable::GDScriptLambdaSelfCallable(Object *p_self, GDScriptFunction *p_function, const Vector<Variant> &p_captures) {
+ object = p_self;
+ function = p_function;
+ captures = p_captures;
+
+ h = (uint32_t)hash_djb2_one_64((uint64_t)this);
+}
diff --git a/modules/gdscript/gdscript_lambda_callable.h b/modules/gdscript/gdscript_lambda_callable.h
index f6a54a1a2f..248176e32c 100644
--- a/modules/gdscript/gdscript_lambda_callable.h
+++ b/modules/gdscript/gdscript_lambda_callable.h
@@ -62,4 +62,29 @@ public:
virtual ~GDScriptLambdaCallable() = default;
};
+// Lambda callable that references a particular object, so it can use `self` in the body.
+class GDScriptLambdaSelfCallable : public CallableCustom {
+ GDScriptFunction *function = nullptr;
+ Ref<RefCounted> reference; // For objects that are RefCounted, keep a reference.
+ Object *object = nullptr; // For non RefCounted objects, use a direct pointer.
+ uint32_t h;
+
+ Vector<Variant> captures;
+
+ static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b);
+ static bool compare_less(const CallableCustom *p_a, const CallableCustom *p_b);
+
+public:
+ uint32_t hash() const override;
+ String get_as_text() const override;
+ CompareEqualFunc get_compare_equal_func() const override;
+ CompareLessFunc get_compare_less_func() const override;
+ ObjectID get_object() const override;
+ void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override;
+
+ GDScriptLambdaSelfCallable(Ref<RefCounted> p_self, GDScriptFunction *p_function, const Vector<Variant> &p_captures);
+ GDScriptLambdaSelfCallable(Object *p_self, GDScriptFunction *p_function, const Vector<Variant> &p_captures);
+ virtual ~GDScriptLambdaSelfCallable() = default;
+};
+
#endif // GDSCRIPT_LAMBDA_CALLABLE
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 67d778f932..67f6b61f14 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -2200,9 +2200,6 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_pre
if (current_function && current_function->is_static) {
push_error(R"(Cannot use "self" inside a static function.)");
}
- if (in_lambda) {
- push_error(R"(Cannot use "self" inside a lambda.)");
- }
SelfNode *self = alloc_node<SelfNode>();
self->current_class = current_class;
return self;
diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h
index 487b7d0449..10474db02f 100644
--- a/modules/gdscript/gdscript_parser.h
+++ b/modules/gdscript/gdscript_parser.h
@@ -767,6 +767,7 @@ public:
LOCAL_BIND, // Pattern bind.
MEMBER_VARIABLE,
MEMBER_CONSTANT,
+ INHERITED_VARIABLE,
};
Source source = UNDEFINED_SOURCE;
@@ -800,6 +801,7 @@ public:
FunctionNode *parent_function = nullptr;
Vector<IdentifierNode *> captures;
Map<StringName, int> captures_indices;
+ bool use_self = false;
bool has_name() const {
return function && function->identifier;
diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp
index 2afb850c32..e28dd26c28 100644
--- a/modules/gdscript/gdscript_vm.cpp
+++ b/modules/gdscript/gdscript_vm.cpp
@@ -306,6 +306,7 @@ void (*type_init_function_table[])(Variant *) = {
&&OPCODE_AWAIT, \
&&OPCODE_AWAIT_RESUME, \
&&OPCODE_CREATE_LAMBDA, \
+ &&OPCODE_CREATE_SELF_LAMBDA, \
&&OPCODE_JUMP, \
&&OPCODE_JUMP_IF, \
&&OPCODE_JUMP_IF_NOT, \
@@ -2277,6 +2278,41 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
}
DISPATCH_OPCODE;
+ OPCODE(OPCODE_CREATE_SELF_LAMBDA) {
+ CHECK_SPACE(2 + instr_arg_count);
+
+ GD_ERR_BREAK(p_instance == nullptr);
+
+ ip += instr_arg_count;
+
+ int captures_count = _code_ptr[ip + 1];
+ GD_ERR_BREAK(captures_count < 0);
+
+ int lambda_index = _code_ptr[ip + 2];
+ GD_ERR_BREAK(lambda_index < 0 || lambda_index >= _lambdas_count);
+ GDScriptFunction *lambda = _lambdas_ptr[lambda_index];
+
+ Vector<Variant> captures;
+ captures.resize(captures_count);
+ for (int i = 0; i < captures_count; i++) {
+ GET_INSTRUCTION_ARG(arg, i);
+ captures.write[i] = *arg;
+ }
+
+ GDScriptLambdaSelfCallable *callable;
+ if (Object::cast_to<RefCounted>(p_instance->owner)) {
+ callable = memnew(GDScriptLambdaSelfCallable(Ref<RefCounted>(Object::cast_to<RefCounted>(p_instance->owner)), lambda, captures));
+ } else {
+ callable = memnew(GDScriptLambdaSelfCallable(p_instance->owner, lambda, captures));
+ }
+
+ GET_INSTRUCTION_ARG(result, captures_count);
+ *result = Callable(callable);
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
OPCODE(OPCODE_JUMP) {
CHECK_SPACE(2);
int to = _code_ptr[ip + 1];
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out
index 015ad756f8..6f7f0783f0 100644
--- a/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out
@@ -1,2 +1,2 @@
GDTEST_ANALYZER_ERROR
-Invalid index type "bool" for a base of type "Array".
+Cannot get index "true" from "[0, 1]".
diff --git a/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.gd b/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.gd
new file mode 100644
index 0000000000..cc78309ae4
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.gd
@@ -0,0 +1,58 @@
+# https://github.com/godotengine/godot/issues/50285
+
+@warning_ignore(unused_local_constant)
+func test():
+ const CONST_INNER_DICTIONARY = { "key": true }
+ const CONST_NESTED_DICTIONARY_OLD_WORKAROUND = {
+ "key1": "value1",
+ "key2": CONST_INNER_DICTIONARY
+ }
+ # All of these should be valid
+ const CONST_NESTED_DICTIONARY = {
+ "key1": "value1",
+ "key2": { "key": true }
+ }
+
+
+ const CONST_DICTIONARY_WITH_ARRAY = {
+ "key1": [1,2,3,4]
+ }
+
+ const CONST_NESTED_ARRAY = [[],[2],[1,2,3]]
+ const CONST_ARRAY_WITH_DICT = [{"key1": 3}, {"key2": 5}]
+
+ const THREE_DIMENSIONAL_ARRAY = [[[],[],[]],[[],[],[]],[[],[],[]]]
+ const MANY_NESTED_DICT = {
+ "key1": {
+ "key11": {
+ "key111": {},
+ "key112": {},
+ },
+ "key12": {
+ "key121": {},
+ "key122": {},
+ },
+ },
+ "key2": {
+ "key21": {
+ "key211": {},
+ "key212": {},
+ },
+ "key22": {
+ "key221": {},
+ "key222": {},
+ },
+ }
+ }
+
+
+ const CONST_ARRAY_ACCESS = [1,2,3][0]
+ const CONST_DICT_ACCESS = {"key1": 5}["key1"]
+
+ const CONST_ARRAY_NESTED_ACCESS = [[1,2,3],[4,5,6],[8,9,10]][0][1]
+ const CONST_DICT_NESTED_ACCESS = {"key1": {"key2": 1}}["key1"]["key2"]
+
+ print(CONST_ARRAY_ACCESS)
+ print(CONST_DICT_ACCESS)
+ print(CONST_ARRAY_NESTED_ACCESS)
+ print(CONST_DICT_NESTED_ACCESS)
diff --git a/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.out b/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.out
new file mode 100644
index 0000000000..5883fc5c18
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/arrays_dictionaries_nested_const.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+1
+5
+2
+1
diff --git a/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.gd b/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.gd
new file mode 100644
index 0000000000..3d063869ab
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.gd
@@ -0,0 +1,23 @@
+var member = "foo"
+
+func bar():
+ print("bar")
+
+func test():
+ var lambda1 = func():
+ print(member)
+ lambda1.call()
+
+ var lambda2 = func():
+ var nested = func():
+ print(member)
+ nested.call()
+ lambda2.call()
+
+ var lambda3 = func():
+ bar()
+ lambda3.call()
+
+ var lambda4 = func():
+ return self
+ print(lambda4.call() == self)
diff --git a/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.out b/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.out
new file mode 100644
index 0000000000..53d602b234
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/features/lambda_use_self.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+foo
+foo
+bar
+true
diff --git a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.cpp
index 23a7b7fed6..95db1c0965 100644
--- a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.cpp
+++ b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.cpp
@@ -64,9 +64,12 @@ SceneExporterGLTFPlugin::SceneExporterGLTFPlugin() {
file_export_lib->clear_filters();
file_export_lib->add_filter("*.glb");
file_export_lib->add_filter("*.gltf");
- file_export_lib->set_title(TTR("Export Mesh GLTF2"));
- String gltf_scene_name = TTR("Export GLTF...");
- add_tool_menu_item(gltf_scene_name, callable_mp(this, &SceneExporterGLTFPlugin::convert_scene_to_gltf2));
+ file_export_lib->set_title(TTR("Export Scene to glTF 2.0 File"));
+
+ PopupMenu *menu = get_export_as_menu();
+ int idx = menu->get_item_count();
+ menu->add_item(TTR("glTF 2.0 Scene..."));
+ menu->set_item_metadata(idx, callable_mp(this, &SceneExporterGLTFPlugin::convert_scene_to_gltf2));
}
void SceneExporterGLTFPlugin::_gltf2_dialog_action(String p_file) {
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index 784733aba2..281f62c4ad 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -65,6 +65,7 @@
#include "scene/3d/node_3d.h"
#include "scene/animation/animation_player.h"
#include "scene/resources/importer_mesh.h"
+#include "scene/resources/material.h"
#include "scene/resources/mesh.h"
#include "scene/resources/multimesh.h"
#include "scene/resources/surface_tool.h"
@@ -80,6 +81,7 @@
// FIXME: Hardcoded to avoid editor dependency.
#define GLTF_IMPORT_USE_NAMED_SKIN_BINDS 16
+#define GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS 32
#include <stdio.h>
#include <stdlib.h>
@@ -2918,30 +2920,32 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
}
}
- //just add it
-
Ref<BaseMaterial3D> mat;
- if (p.has("material")) {
- const int material = p["material"];
- ERR_FAIL_INDEX_V(material, state->materials.size(), ERR_FILE_CORRUPT);
- Ref<BaseMaterial3D> mat3d = state->materials[material];
- ERR_FAIL_NULL_V(mat3d, ERR_FILE_CORRUPT);
- if (has_vertex_color) {
- mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
- }
- mat = mat3d;
+ String mat_name;
+ if (!state->discard_meshes_and_materials) {
+ if (p.has("material")) {
+ const int material = p["material"];
+ ERR_FAIL_INDEX_V(material, state->materials.size(), ERR_FILE_CORRUPT);
+ Ref<BaseMaterial3D> mat3d = state->materials[material];
+ ERR_FAIL_NULL_V(mat3d, ERR_FILE_CORRUPT);
+ if (has_vertex_color) {
+ mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ }
+ mat = mat3d;
- } else {
- Ref<StandardMaterial3D> mat3d;
- mat3d.instantiate();
- if (has_vertex_color) {
- mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ } else {
+ Ref<StandardMaterial3D> mat3d;
+ mat3d.instantiate();
+ if (has_vertex_color) {
+ mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ }
+ mat = mat3d;
}
- mat = mat3d;
+ ERR_FAIL_NULL_V(mat, ERR_FILE_CORRUPT);
+ mat_name = mat->get_name();
}
- ERR_FAIL_NULL_V(mat, ERR_FILE_CORRUPT);
import_mesh->add_surface(primitive, array, morphs,
- Dictionary(), mat, mat->get_name(), flags);
+ Dictionary(), mat, mat_name, flags);
}
Vector<float> blend_weights;
@@ -6908,8 +6912,8 @@ Node *GLTFDocument::generate_scene(Ref<GLTFState> state, int32_t p_bake_fps) {
Error GLTFDocument::append_from_scene(Node *p_node, Ref<GLTFState> state, uint32_t p_flags, int32_t p_bake_fps) {
ERR_FAIL_COND_V(state.is_null(), FAILED);
- state->use_named_skin_binds =
- p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
+ state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
+ state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
_convert_scene_node(state, p_node, -1, -1);
if (!state->buffers.size()) {
@@ -6929,6 +6933,7 @@ Error GLTFDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_pa
// TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
Error err = FAILED;
state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
+ state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
Ref<FileAccessMemory> file_access;
file_access.instantiate();
@@ -6968,20 +6973,22 @@ Error GLTFDocument::_parse_gltf_state(Ref<GLTFState> state, const String &p_sear
ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
- /* PARSE IMAGES */
- err = _parse_images(state, p_search_path);
+ if (!state->discard_meshes_and_materials) {
+ /* PARSE IMAGES */
+ err = _parse_images(state, p_search_path);
- ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
- /* PARSE TEXTURES */
- err = _parse_textures(state);
+ /* PARSE TEXTURES */
+ err = _parse_textures(state);
- ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
- /* PARSE TEXTURES */
- err = _parse_materials(state);
+ /* PARSE TEXTURES */
+ err = _parse_materials(state);
- ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
+ }
/* PARSE SKINS */
err = _parse_skins(state);
@@ -7033,6 +7040,7 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint
}
r_state->filename = p_path.get_file().get_basename();
r_state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
+ r_state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp
index 3f638bbca5..6ead2f69c3 100644
--- a/modules/gltf/gltf_state.cpp
+++ b/modules/gltf/gltf_state.cpp
@@ -305,3 +305,11 @@ AnimationPlayer *GLTFState::get_animation_player(int idx) {
ERR_FAIL_INDEX_V(idx, animation_players.size(), nullptr);
return animation_players[idx];
}
+
+void GLTFState::set_discard_meshes_and_materials(bool p_discard_meshes_and_materials) {
+ discard_meshes_and_materials = p_discard_meshes_and_materials;
+}
+
+bool GLTFState::get_discard_meshes_and_materials() {
+ return discard_meshes_and_materials;
+}
diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h
index d03434d2f1..42ca079f1c 100644
--- a/modules/gltf/gltf_state.h
+++ b/modules/gltf/gltf_state.h
@@ -62,6 +62,7 @@ class GLTFState : public Resource {
Vector<uint8_t> glb_data;
bool use_named_skin_binds = false;
+ bool discard_meshes_and_materials = false;
Vector<Ref<GLTFNode>> nodes;
Vector<Vector<uint8_t>> buffers;
@@ -112,6 +113,9 @@ public:
bool get_use_named_skin_binds();
void set_use_named_skin_binds(bool p_use_named_skin_binds);
+ bool get_discard_meshes_and_materials();
+ void set_discard_meshes_and_materials(bool p_discard_meshes_and_materials);
+
Array get_nodes();
void set_nodes(Array p_nodes);
diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp
index ddc2e945a7..1296a4587c 100644
--- a/modules/mbedtls/packet_peer_mbed_dtls.cpp
+++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp
@@ -115,7 +115,7 @@ Error PacketPeerMbedDTLS::_do_handshake() {
}
Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) {
- ERR_FAIL_COND_V(!p_base.is_valid() || !p_base->is_connected_to_host(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!p_base.is_valid() || !p_base->is_socket_connected(), ERR_INVALID_PARAMETER);
base = p_base;
int ret = 0;
diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp
index ca4fc4f628..d16d41b438 100644
--- a/modules/navigation/godot_navigation_server.cpp
+++ b/modules/navigation/godot_navigation_server.cpp
@@ -40,43 +40,43 @@
/// an instance of that struct with the submitted parameters.
/// Then, that struct is stored in an array; the `sync` function consume that array.
-#define COMMAND_1(F_NAME, T_0, D_0) \
- struct MERGE(F_NAME, _command) : public SetCommand { \
- T_0 d_0; \
- MERGE(F_NAME, _command) \
- (T_0 p_d_0) : \
- d_0(p_d_0) {} \
- virtual void exec(GodotNavigationServer *server) { \
- server->MERGE(_cmd_, F_NAME)(d_0); \
- } \
- }; \
- void GodotNavigationServer::F_NAME(T_0 D_0) const { \
- auto cmd = memnew(MERGE(F_NAME, _command)( \
- D_0)); \
- add_command(cmd); \
- } \
+#define COMMAND_1(F_NAME, T_0, D_0) \
+ struct MERGE(F_NAME, _command) : public SetCommand { \
+ T_0 d_0; \
+ MERGE(F_NAME, _command) \
+ (T_0 p_d_0) : \
+ d_0(p_d_0) {} \
+ virtual void exec(GodotNavigationServer *server) override { \
+ server->MERGE(_cmd_, F_NAME)(d_0); \
+ } \
+ }; \
+ void GodotNavigationServer::F_NAME(T_0 D_0) const { \
+ auto cmd = memnew(MERGE(F_NAME, _command)( \
+ D_0)); \
+ add_command(cmd); \
+ } \
void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0)
-#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \
- struct MERGE(F_NAME, _command) : public SetCommand { \
- T_0 d_0; \
- T_1 d_1; \
- MERGE(F_NAME, _command) \
- ( \
- T_0 p_d_0, \
- T_1 p_d_1) : \
- d_0(p_d_0), \
- d_1(p_d_1) {} \
- virtual void exec(GodotNavigationServer *server) { \
- server->MERGE(_cmd_, F_NAME)(d_0, d_1); \
- } \
- }; \
- void GodotNavigationServer::F_NAME(T_0 D_0, T_1 D_1) const { \
- auto cmd = memnew(MERGE(F_NAME, _command)( \
- D_0, \
- D_1)); \
- add_command(cmd); \
- } \
+#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \
+ struct MERGE(F_NAME, _command) : public SetCommand { \
+ T_0 d_0; \
+ T_1 d_1; \
+ MERGE(F_NAME, _command) \
+ ( \
+ T_0 p_d_0, \
+ T_1 p_d_1) : \
+ d_0(p_d_0), \
+ d_1(p_d_1) {} \
+ virtual void exec(GodotNavigationServer *server) override { \
+ server->MERGE(_cmd_, F_NAME)(d_0, d_1); \
+ } \
+ }; \
+ void GodotNavigationServer::F_NAME(T_0 D_0, T_1 D_1) const { \
+ auto cmd = memnew(MERGE(F_NAME, _command)( \
+ D_0, \
+ D_1)); \
+ add_command(cmd); \
+ } \
void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1)
#define COMMAND_4(F_NAME, T_0, D_0, T_1, D_1, T_2, D_2, T_3, D_3) \
@@ -95,7 +95,7 @@
d_1(p_d_1), \
d_2(p_d_2), \
d_3(p_d_3) {} \
- virtual void exec(GodotNavigationServer *server) { \
+ virtual void exec(GodotNavigationServer *server) override { \
server->MERGE(_cmd_, F_NAME)(d_0, d_1, d_2, d_3); \
} \
}; \
diff --git a/modules/navigation/nav_map.cpp b/modules/navigation/nav_map.cpp
index a6df6bb72c..cbc0adc574 100644
--- a/modules/navigation/nav_map.cpp
+++ b/modules/navigation/nav_map.cpp
@@ -30,7 +30,6 @@
#include "nav_map.h"
-#include "core/os/threaded_array_processor.h"
#include "nav_region.h"
#include "rvo_agent.h"
@@ -674,7 +673,10 @@ void NavMap::compute_single_step(uint32_t index, RvoAgent **agent) {
void NavMap::step(real_t p_deltatime) {
deltatime = p_deltatime;
if (controlled_agents.size() > 0) {
- thread_process_array(
+ if (step_work_pool.get_thread_count() == 0) {
+ step_work_pool.init();
+ }
+ step_work_pool.do_work(
controlled_agents.size(),
this,
&NavMap::compute_single_step,
@@ -719,3 +721,10 @@ void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys
}
}
}
+
+NavMap::NavMap() {
+}
+
+NavMap::~NavMap() {
+ step_work_pool.finish();
+}
diff --git a/modules/navigation/nav_map.h b/modules/navigation/nav_map.h
index f46297a7ce..5232e42bed 100644
--- a/modules/navigation/nav_map.h
+++ b/modules/navigation/nav_map.h
@@ -35,6 +35,7 @@
#include "core/math/math_defs.h"
#include "core/templates/map.h"
+#include "core/templates/thread_work_pool.h"
#include "nav_utils.h"
#include <KdTree.h>
@@ -80,8 +81,12 @@ class NavMap : public NavRid {
/// Change the id each time the map is updated.
uint32_t map_update_id = 0;
+ /// Pooled threads for computing steps
+ ThreadWorkPool step_work_pool;
+
public:
- NavMap() {}
+ NavMap();
+ ~NavMap();
void set_up(Vector3 p_up);
Vector3 get_up() const {
diff --git a/modules/noise/SCsub b/modules/noise/SCsub
index 3e8395b9b1..1430aa0c4e 100644
--- a/modules/noise/SCsub
+++ b/modules/noise/SCsub
@@ -27,6 +27,7 @@ env.modules_sources += thirdparty_obj
module_obj = []
env_noise.add_source_files(module_obj, "*.cpp")
+env_noise.add_source_files(module_obj, "editor/*.cpp")
env.modules_sources += module_obj
# Needed to force rebuilding the module files when the thirdparty library is updated.
diff --git a/modules/noise/doc_classes/FastNoiseLite.xml b/modules/noise/doc_classes/FastNoiseLite.xml
index b6d91850c4..6ca4ba2d46 100644
--- a/modules/noise/doc_classes/FastNoiseLite.xml
+++ b/modules/noise/doc_classes/FastNoiseLite.xml
@@ -16,12 +16,9 @@
<member name="cellular_jitter" type="float" setter="set_cellular_jitter" getter="get_cellular_jitter" default="0.45">
Maximum distance a point can move off of its grid position. Set to [code]0[/code] for an even grid.
</member>
- <member name="cellular_return_type" type="int" setter="set_cellular_return_type" getter="get_cellular_return_type" enum="FastNoiseLite.CellularReturnType" default="0">
+ <member name="cellular_return_type" type="int" setter="set_cellular_return_type" getter="get_cellular_return_type" enum="FastNoiseLite.CellularReturnType" default="1">
Return type from cellular noise calculations. See [enum CellularReturnType].
</member>
- <member name="color_ramp" type="Gradient" setter="set_color_ramp" getter="get_color_ramp">
- A [Gradient] which is used to map the luminance of each pixel to a color value.
- </member>
<member name="domain_warp_amplitude" type="float" setter="set_domain_warp_amplitude" getter="get_domain_warp_amplitude" default="30.0">
Sets the maximum warp distance from the origin.
</member>
@@ -69,9 +66,6 @@
<member name="frequency" type="float" setter="set_frequency" getter="get_frequency" default="0.01">
The frequency for all noise types. Low frequency results in smooth noise while high frequency results in rougher, more granular noise.
</member>
- <member name="in_3d_space" type="bool" setter="set_in_3d_space" getter="is_in_3d_space" default="false">
- Determines whether the noise image returned by [method Noise.get_image] is calculated in 3d space. May result in reduced contrast.
- </member>
<member name="noise_type" type="int" setter="set_noise_type" getter="get_noise_type" enum="FastNoiseLite.NoiseType" default="1">
The noise algorithm used. See [enum NoiseType].
</member>
diff --git a/modules/noise/doc_classes/Noise.xml b/modules/noise/doc_classes/Noise.xml
index db0dec18d2..5af204575c 100644
--- a/modules/noise/doc_classes/Noise.xml
+++ b/modules/noise/doc_classes/Noise.xml
@@ -11,23 +11,24 @@
<tutorials>
</tutorials>
<methods>
- <method name="get_image">
+ <method name="get_image" qualifiers="const">
<return type="Image" />
<argument index="0" name="width" type="int" />
<argument index="1" name="height" type="int" />
<argument index="2" name="invert" type="bool" default="false" />
+ <argument index="3" name="in_3d_space" type="bool" default="false" />
<description>
Returns a 2D [Image] noise image.
</description>
</method>
- <method name="get_noise_1d">
+ <method name="get_noise_1d" qualifiers="const">
<return type="float" />
<argument index="0" name="x" type="float" />
<description>
Returns the 1D noise value at the given (x) coordinate.
</description>
</method>
- <method name="get_noise_2d">
+ <method name="get_noise_2d" qualifiers="const">
<return type="float" />
<argument index="0" name="x" type="float" />
<argument index="1" name="y" type="float" />
@@ -35,14 +36,14 @@
Returns the 2D noise value at the given position.
</description>
</method>
- <method name="get_noise_2dv">
+ <method name="get_noise_2dv" qualifiers="const">
<return type="float" />
<argument index="0" name="v" type="Vector2" />
<description>
Returns the 2D noise value at the given position.
</description>
</method>
- <method name="get_noise_3d">
+ <method name="get_noise_3d" qualifiers="const">
<return type="float" />
<argument index="0" name="x" type="float" />
<argument index="1" name="y" type="float" />
@@ -51,19 +52,20 @@
Returns the 3D noise value at the given position.
</description>
</method>
- <method name="get_noise_3dv">
+ <method name="get_noise_3dv" qualifiers="const">
<return type="float" />
<argument index="0" name="v" type="Vector3" />
<description>
Returns the 3D noise value at the given position.
</description>
</method>
- <method name="get_seamless_image">
+ <method name="get_seamless_image" qualifiers="const">
<return type="Image" />
<argument index="0" name="width" type="int" />
<argument index="1" name="height" type="int" />
<argument index="2" name="invert" type="bool" default="false" />
- <argument index="3" name="skirt" type="float" default="0.1" />
+ <argument index="3" name="in_3d_space" type="bool" default="false" />
+ <argument index="4" name="skirt" type="float" default="0.1" />
<description>
Returns a seamless 2D [Image] noise image.
</description>
diff --git a/modules/noise/doc_classes/NoiseTexture.xml b/modules/noise/doc_classes/NoiseTexture.xml
index 63630eccde..62a223b387 100644
--- a/modules/noise/doc_classes/NoiseTexture.xml
+++ b/modules/noise/doc_classes/NoiseTexture.xml
@@ -24,9 +24,20 @@
<member name="bump_strength" type="float" setter="set_bump_strength" getter="get_bump_strength" default="8.0">
Strength of the bump maps used in this texture. A higher value will make the bump maps appear larger while a lower value will make them appear softer.
</member>
+ <member name="color_ramp" type="Gradient" setter="set_color_ramp" getter="get_color_ramp">
+ A [Gradient] which is used to map the luminance of each pixel to a color value.
+ </member>
+ <member name="generate_mipmaps" type="bool" setter="set_generate_mipmaps" getter="is_generating_mipmaps" default="true">
+ Determines whether mipmaps are generated for this texture.
+ Enabling this results in less texture aliasing, but the noise texture generation may take longer.
+ Requires (anisotropic) mipmap filtering to be enabled for a material to have an effect.
+ </member>
<member name="height" type="int" setter="set_height" getter="get_height" default="512">
Height of the generated texture.
</member>
+ <member name="in_3d_space" type="bool" setter="set_in_3d_space" getter="is_in_3d_space" default="false">
+ Determines whether the noise image is calculated in 3D space. May result in reduced contrast.
+ </member>
<member name="invert" type="bool" setter="set_invert" getter="get_invert" default="false">
If [code]true[/code], inverts the noise texture. White becomes black, black becomes white.
</member>
diff --git a/modules/noise/editor/noise_editor_plugin.cpp b/modules/noise/editor/noise_editor_plugin.cpp
new file mode 100644
index 0000000000..32c3f0aad4
--- /dev/null
+++ b/modules/noise/editor/noise_editor_plugin.cpp
@@ -0,0 +1,149 @@
+/*************************************************************************/
+/* noise_editor_plugin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "noise_editor_plugin.h"
+
+#ifdef TOOLS_ENABLED
+
+#include "editor/editor_scale.h"
+
+#include "modules/noise/noise.h"
+#include "modules/noise/noise_texture.h"
+
+class NoisePreview : public Control {
+ GDCLASS(NoisePreview, Control)
+
+ static const int PREVIEW_HEIGHT = 150;
+ static const int PADDING_3D_SPACE_SWITCH = 2;
+
+ Ref<Noise> _noise;
+ Size2i _preview_texture_size;
+
+ TextureRect *_texture_rect = nullptr;
+ Button *_3d_space_switch = nullptr;
+
+public:
+ NoisePreview() {
+ set_custom_minimum_size(Size2(0, EDSCALE * PREVIEW_HEIGHT));
+
+ _texture_rect = memnew(TextureRect);
+ _texture_rect->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
+ _texture_rect->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_COVERED);
+ add_child(_texture_rect);
+
+ _3d_space_switch = memnew(Button);
+ _3d_space_switch->set_text(TTR("3D"));
+ _3d_space_switch->set_tooltip(TTR("Toggles whether the noise preview is computed in 3D space."));
+ _3d_space_switch->set_toggle_mode(true);
+ _3d_space_switch->set_offset(SIDE_LEFT, PADDING_3D_SPACE_SWITCH);
+ _3d_space_switch->set_offset(SIDE_TOP, PADDING_3D_SPACE_SWITCH);
+ _3d_space_switch->connect("pressed", callable_mp(this, &NoisePreview::_on_3d_button_pressed));
+ add_child(_3d_space_switch);
+ }
+
+ void set_noise(Ref<Noise> noise) {
+ if (_noise == noise) {
+ return;
+ }
+ _noise = noise;
+ if (_noise.is_valid()) {
+ if (_noise->has_meta("_preview_in_3d_space_")) {
+ _3d_space_switch->set_pressed(true);
+ }
+
+ update_preview();
+ }
+ }
+
+private:
+ void _on_3d_button_pressed() {
+ if (_3d_space_switch->is_pressed()) {
+ _noise->set_meta("_preview_in_3d_space_", true);
+ } else {
+ _noise->remove_meta("_preview_in_3d_space_");
+ }
+ }
+
+ void _notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_RESIZED: {
+ _preview_texture_size = get_size();
+ update_preview();
+ } break;
+ }
+ }
+
+ void update_preview() {
+ if (MIN(_preview_texture_size.width, _preview_texture_size.height) > 0) {
+ Ref<NoiseTexture> tex;
+ tex.instantiate();
+ tex->set_width(_preview_texture_size.width);
+ tex->set_height(_preview_texture_size.height);
+ tex->set_in_3d_space(_3d_space_switch->is_pressed());
+ tex->set_noise(_noise);
+ _texture_rect->set_texture(tex);
+ }
+ }
+};
+
+/////////////////////////////////////////////////////////////////////////////////
+
+class NoiseEditorInspectorPlugin : public EditorInspectorPlugin {
+ GDCLASS(NoiseEditorInspectorPlugin, EditorInspectorPlugin)
+public:
+ bool can_handle(Object *p_object) override {
+ return Object::cast_to<Noise>(p_object) != nullptr;
+ }
+
+ void parse_begin(Object *p_object) override {
+ Noise *noise_ptr = Object::cast_to<Noise>(p_object);
+ if (noise_ptr) {
+ Ref<Noise> noise(noise_ptr);
+
+ NoisePreview *viewer = memnew(NoisePreview);
+ viewer->set_noise(noise);
+ add_custom_control(viewer);
+ }
+ }
+};
+
+/////////////////////////////////////////////////////////////////////////////////
+
+String NoiseEditorPlugin::get_name() const {
+ return Noise::get_class_static();
+}
+
+NoiseEditorPlugin::NoiseEditorPlugin() {
+ Ref<NoiseEditorInspectorPlugin> plugin;
+ plugin.instantiate();
+ add_inspector_plugin(plugin);
+}
+
+#endif // TOOLS_ENABLED
diff --git a/modules/noise/editor/noise_editor_plugin.h b/modules/noise/editor/noise_editor_plugin.h
new file mode 100644
index 0000000000..55a01deb2d
--- /dev/null
+++ b/modules/noise/editor/noise_editor_plugin.h
@@ -0,0 +1,49 @@
+/*************************************************************************/
+/* noise_editor_plugin.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef NOISE_EDITOR_PLUGIN_H
+#define NOISE_EDITOR_PLUGIN_H
+
+#ifdef TOOLS_ENABLED
+
+#include "editor/editor_plugin.h"
+
+class NoiseEditorPlugin : public EditorPlugin {
+ GDCLASS(NoiseEditorPlugin, EditorPlugin)
+
+public:
+ String get_name() const override;
+
+ NoiseEditorPlugin();
+};
+
+#endif // TOOLS_ENABLED
+
+#endif // NOISE_EDITOR_PLUGIN_H
diff --git a/modules/noise/fastnoise_lite.cpp b/modules/noise/fastnoise_lite.cpp
index 9497fe6a7e..a8d38dee62 100644
--- a/modules/noise/fastnoise_lite.cpp
+++ b/modules/noise/fastnoise_lite.cpp
@@ -31,31 +31,29 @@
#include "fastnoise_lite.h"
FastNoiseLite::FastNoiseLite() {
- // Most defaults copied from the library.
- set_noise_type(TYPE_SIMPLEX_SMOOTH);
- set_seed(0);
- set_frequency(0.01);
- set_in_3d_space(false);
-
- set_fractal_type(FRACTAL_FBM);
- set_fractal_octaves(5);
- set_fractal_lacunarity(2.0);
- set_fractal_gain(0.5);
- set_fractal_weighted_strength(0.0);
- set_fractal_ping_pong_strength(2.0);
-
- set_cellular_distance_function(DISTANCE_EUCLIDEAN);
- set_cellular_return_type(RETURN_CELL_VALUE);
- set_cellular_jitter(0.45);
-
- set_domain_warp_enabled(false);
- set_domain_warp_type(DOMAIN_WARP_SIMPLEX);
- set_domain_warp_amplitude(30.0);
- set_domain_warp_frequency(0.05);
- set_domain_warp_fractal_type(DOMAIN_WARP_FRACTAL_PROGRESSIVE);
- set_domain_warp_fractal_octaves(5);
- set_domain_warp_fractal_lacunarity(6);
- set_domain_warp_fractal_gain(0.5);
+ _noise.SetNoiseType((_FastNoiseLite::NoiseType)noise_type);
+ _noise.SetSeed(seed);
+ _noise.SetFrequency(frequency);
+
+ _noise.SetFractalType((_FastNoiseLite::FractalType)fractal_type);
+ _noise.SetFractalOctaves(fractal_octaves);
+ _noise.SetFractalLacunarity(fractal_lacunarity);
+ _noise.SetFractalGain(fractal_gain);
+ _noise.SetFractalWeightedStrength(fractal_weighted_strength);
+ _noise.SetFractalPingPongStrength(fractal_ping_pong_strength);
+
+ _noise.SetCellularDistanceFunction((_FastNoiseLite::CellularDistanceFunction)cellular_distance_function);
+ _noise.SetCellularReturnType((_FastNoiseLite::CellularReturnType)cellular_return_type);
+ _noise.SetCellularJitter(cellular_jitter);
+
+ _domain_warp_noise.SetDomainWarpType((_FastNoiseLite::DomainWarpType)domain_warp_type);
+ _domain_warp_noise.SetSeed(seed);
+ _domain_warp_noise.SetDomainWarpAmp(domain_warp_amplitude);
+ _domain_warp_noise.SetFrequency(domain_warp_frequency);
+ _domain_warp_noise.SetFractalType(_FastNoiseLite::FractalType_None);
+ _domain_warp_noise.SetFractalOctaves(domain_warp_fractal_octaves);
+ _domain_warp_noise.SetFractalLacunarity(domain_warp_fractal_lacunarity);
+ _domain_warp_noise.SetFractalGain(domain_warp_fractal_gain);
}
FastNoiseLite::~FastNoiseLite() {
@@ -77,6 +75,7 @@ FastNoiseLite::NoiseType FastNoiseLite::get_noise_type() const {
void FastNoiseLite::set_seed(int p_seed) {
seed = p_seed;
_noise.SetSeed(p_seed);
+ _domain_warp_noise.SetSeed(p_seed);
emit_changed();
}
@@ -94,14 +93,6 @@ real_t FastNoiseLite::get_frequency() const {
return frequency;
}
-void FastNoiseLite::set_in_3d_space(bool p_enable) {
- in_3d_space = p_enable;
- emit_changed();
-}
-bool FastNoiseLite::is_in_3d_space() const {
- return in_3d_space;
-}
-
void FastNoiseLite::set_offset(Vector3 p_offset) {
offset = p_offset;
emit_changed();
@@ -111,46 +102,6 @@ Vector3 FastNoiseLite::get_offset() const {
return offset;
}
-void FastNoiseLite::set_color_ramp(const Ref<Gradient> &p_gradient) {
- color_ramp = p_gradient;
- if (color_ramp.is_valid()) {
- color_ramp->connect(SNAME("changed"), callable_mp(this, &FastNoiseLite::_changed));
- emit_changed();
- }
-}
-
-Ref<Gradient> FastNoiseLite::get_color_ramp() const {
- return color_ramp;
-}
-
-// Noise functions.
-
-real_t FastNoiseLite::get_noise_1d(real_t p_x) {
- return get_noise_2d(p_x, 0.0);
-}
-
-real_t FastNoiseLite::get_noise_2dv(Vector2 p_v) {
- return get_noise_2d(p_v.x, p_v.y);
-}
-
-real_t FastNoiseLite::get_noise_2d(real_t p_x, real_t p_y) {
- if (domain_warp_enabled) {
- _domain_warp_noise.DomainWarp(p_x, p_y);
- }
- return _noise.GetNoise(p_x + offset.x, p_y + offset.y);
-}
-
-real_t FastNoiseLite::get_noise_3dv(Vector3 p_v) {
- return get_noise_3d(p_v.x, p_v.y, p_v.z);
-}
-
-real_t FastNoiseLite::get_noise_3d(real_t p_x, real_t p_y, real_t p_z) {
- if (domain_warp_enabled) {
- _domain_warp_noise.DomainWarp(p_x, p_y, p_z);
- }
- return _noise.GetNoise(p_x + offset.x, p_y + offset.y, p_z + offset.z);
-}
-
// Fractal.
void FastNoiseLite::set_fractal_type(FractalType p_type) {
@@ -204,12 +155,12 @@ real_t FastNoiseLite::get_fractal_weighted_strength() const {
}
void FastNoiseLite::set_fractal_ping_pong_strength(real_t p_ping_pong_strength) {
- fractal_pinp_pong_strength = p_ping_pong_strength;
+ fractal_ping_pong_strength = p_ping_pong_strength;
_noise.SetFractalPingPongStrength(p_ping_pong_strength);
emit_changed();
}
real_t FastNoiseLite::get_fractal_ping_pong_strength() const {
- return fractal_pinp_pong_strength;
+ return fractal_ping_pong_strength;
}
// Cellular.
@@ -237,7 +188,6 @@ real_t FastNoiseLite::get_cellular_jitter() const {
void FastNoiseLite::set_cellular_return_type(CellularReturnType p_ret) {
cellular_return_type = p_ret;
_noise.SetCellularReturnType((_FastNoiseLite::CellularReturnType)p_ret);
-
emit_changed();
}
@@ -345,68 +295,32 @@ real_t FastNoiseLite::get_domain_warp_fractal_gain() const {
return domain_warp_fractal_gain;
}
-// Textures.
+// Noise interface functions.
-Ref<Image> FastNoiseLite::get_image(int p_width, int p_height, bool p_invert) {
- bool grayscale = color_ramp.is_null();
-
- Vector<uint8_t> data;
- data.resize(p_width * p_height * (grayscale ? 1 : 4));
-
- uint8_t *wd8 = data.ptrw();
+real_t FastNoiseLite::get_noise_1d(real_t p_x) const {
+ return get_noise_2d(p_x, 0.0);
+}
- // Get all values and identify min/max values.
- Vector<real_t> values;
- values.resize(p_width * p_height);
- real_t min_val = 100;
- real_t max_val = -100;
+real_t FastNoiseLite::get_noise_2dv(Vector2 p_v) const {
+ return get_noise_2d(p_v.x, p_v.y);
+}
- for (int y = 0, i = 0; y < p_height; y++) {
- for (int x = 0; x < p_width; x++, i++) {
- values.set(i, is_in_3d_space() ? get_noise_3d(x, y, 0.0) : get_noise_2d(x, y));
- if (values[i] > max_val) {
- max_val = values[i];
- }
- if (values[i] < min_val) {
- min_val = values[i];
- }
- }
+real_t FastNoiseLite::get_noise_2d(real_t p_x, real_t p_y) const {
+ if (domain_warp_enabled) {
+ _domain_warp_noise.DomainWarp(p_x, p_y);
}
+ return _noise.GetNoise(p_x + offset.x, p_y + offset.y);
+}
- // Normalize values and write to texture.
- uint8_t value;
- for (int i = 0, x = 0; i < p_height; i++) {
- for (int j = 0; j < p_width; j++, x++) {
- if (max_val == min_val) {
- value = 0;
- } else {
- value = uint8_t(CLAMP((values[x] - min_val) / (max_val - min_val) * 255.f, 0, 255));
- }
- if (p_invert) {
- value = 255 - value;
- }
- if (grayscale) {
- wd8[x] = value;
- } else {
- float luminance = value / 255.0;
- Color ramp_color = color_ramp->get_color_at_offset(luminance);
- wd8[x * 4 + 0] = uint8_t(CLAMP(ramp_color.r * 255, 0, 255));
- wd8[x * 4 + 1] = uint8_t(CLAMP(ramp_color.g * 255, 0, 255));
- wd8[x * 4 + 2] = uint8_t(CLAMP(ramp_color.b * 255, 0, 255));
- wd8[x * 4 + 3] = uint8_t(CLAMP(ramp_color.a * 255, 0, 255));
- }
- }
- }
- if (grayscale) {
- return memnew(Image(p_width, p_height, false, Image::FORMAT_L8, data));
- } else {
- return memnew(Image(p_width, p_height, false, Image::FORMAT_RGBA8, data));
- }
+real_t FastNoiseLite::get_noise_3dv(Vector3 p_v) const {
+ return get_noise_3d(p_v.x, p_v.y, p_v.z);
}
-Ref<Image> FastNoiseLite::get_seamless_image(int p_width, int p_height, bool p_invert, real_t p_blend_skirt) {
- // Just return parent function. This is here only so Godot will properly document this function.
- return Noise::get_seamless_image(p_width, p_height, p_invert, p_blend_skirt);
+real_t FastNoiseLite::get_noise_3d(real_t p_x, real_t p_y, real_t p_z) const {
+ if (domain_warp_enabled) {
+ _domain_warp_noise.DomainWarp(p_x, p_y, p_z);
+ }
+ return _noise.GetNoise(p_x + offset.x, p_y + offset.y, p_z + offset.z);
}
void FastNoiseLite::_changed() {
@@ -418,108 +332,103 @@ void FastNoiseLite::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_noise_type", "type"), &FastNoiseLite::set_noise_type);
ClassDB::bind_method(D_METHOD("get_noise_type"), &FastNoiseLite::get_noise_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "noise_type", PROPERTY_HINT_ENUM, "Simplex,Simplex Smooth,Cellular,Perlin,Value Cubic,Value"), "set_noise_type", "get_noise_type");
ClassDB::bind_method(D_METHOD("set_seed", "seed"), &FastNoiseLite::set_seed);
ClassDB::bind_method(D_METHOD("get_seed"), &FastNoiseLite::get_seed);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "seed"), "set_seed", "get_seed");
ClassDB::bind_method(D_METHOD("set_frequency", "freq"), &FastNoiseLite::set_frequency);
ClassDB::bind_method(D_METHOD("get_frequency"), &FastNoiseLite::get_frequency);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frequency", PROPERTY_HINT_RANGE, ".001,1"), "set_frequency", "get_frequency");
-
- ClassDB::bind_method(D_METHOD("set_in_3d_space", "enable"), &FastNoiseLite::set_in_3d_space);
- ClassDB::bind_method(D_METHOD("is_in_3d_space"), &FastNoiseLite::is_in_3d_space);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "in_3d_space"), "set_in_3d_space", "is_in_3d_space");
ClassDB::bind_method(D_METHOD("set_offset", "offset"), &FastNoiseLite::set_offset);
ClassDB::bind_method(D_METHOD("get_offset"), &FastNoiseLite::get_offset);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "offset", PROPERTY_HINT_RANGE, "-999999999,999999999,1"), "set_offset", "get_offset");
-
- ClassDB::bind_method(D_METHOD("set_color_ramp", "gradient"), &FastNoiseLite::set_color_ramp);
- ClassDB::bind_method(D_METHOD("get_color_ramp"), &FastNoiseLite::get_color_ramp);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "color_ramp", PROPERTY_HINT_RESOURCE_TYPE, "Gradient"), "set_color_ramp", "get_color_ramp");
// Fractal.
- ADD_GROUP("Fractal", "fractal_");
ClassDB::bind_method(D_METHOD("set_fractal_type", "type"), &FastNoiseLite::set_fractal_type);
ClassDB::bind_method(D_METHOD("get_fractal_type"), &FastNoiseLite::get_fractal_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "fractal_type", PROPERTY_HINT_ENUM, "None,FBM,Ridged,Ping-Pong"), "set_fractal_type", "get_fractal_type");
ClassDB::bind_method(D_METHOD("set_fractal_octaves", "octave_count"), &FastNoiseLite::set_fractal_octaves);
ClassDB::bind_method(D_METHOD("get_fractal_octaves"), &FastNoiseLite::get_fractal_octaves);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "fractal_octaves", PROPERTY_HINT_RANGE, "1,10,1"), "set_fractal_octaves", "get_fractal_octaves");
ClassDB::bind_method(D_METHOD("set_fractal_lacunarity", "lacunarity"), &FastNoiseLite::set_fractal_lacunarity);
ClassDB::bind_method(D_METHOD("get_fractal_lacunarity"), &FastNoiseLite::get_fractal_lacunarity);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_lacunarity"), "set_fractal_lacunarity", "get_fractal_lacunarity");
ClassDB::bind_method(D_METHOD("set_fractal_gain", "gain"), &FastNoiseLite::set_fractal_gain);
ClassDB::bind_method(D_METHOD("get_fractal_gain"), &FastNoiseLite::get_fractal_gain);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_gain"), "set_fractal_gain", "get_fractal_gain");
ClassDB::bind_method(D_METHOD("set_fractal_weighted_strength", "weighted_strength"), &FastNoiseLite::set_fractal_weighted_strength);
ClassDB::bind_method(D_METHOD("get_fractal_weighted_strength"), &FastNoiseLite::get_fractal_weighted_strength);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_weighted_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_fractal_weighted_strength", "get_fractal_weighted_strength");
ClassDB::bind_method(D_METHOD("set_fractal_ping_pong_strength", "ping_pong_strength"), &FastNoiseLite::set_fractal_ping_pong_strength);
ClassDB::bind_method(D_METHOD("get_fractal_ping_pong_strength"), &FastNoiseLite::get_fractal_ping_pong_strength);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_ping_pong_strength"), "set_fractal_ping_pong_strength", "get_fractal_ping_pong_strength");
// Cellular.
- ADD_GROUP("Cellular", "cellular_");
ClassDB::bind_method(D_METHOD("set_cellular_distance_function", "func"), &FastNoiseLite::set_cellular_distance_function);
ClassDB::bind_method(D_METHOD("get_cellular_distance_function"), &FastNoiseLite::get_cellular_distance_function);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "cellular_distance_function", PROPERTY_HINT_ENUM, "Euclidean,Euclidean Squared,Manhattan,Hybrid"), "set_cellular_distance_function", "get_cellular_distance_function");
ClassDB::bind_method(D_METHOD("set_cellular_jitter", "jitter"), &FastNoiseLite::set_cellular_jitter);
ClassDB::bind_method(D_METHOD("get_cellular_jitter"), &FastNoiseLite::get_cellular_jitter);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cellular_jitter"), "set_cellular_jitter", "get_cellular_jitter");
ClassDB::bind_method(D_METHOD("set_cellular_return_type", "ret"), &FastNoiseLite::set_cellular_return_type);
ClassDB::bind_method(D_METHOD("get_cellular_return_type"), &FastNoiseLite::get_cellular_return_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "cellular_return_type", PROPERTY_HINT_ENUM, "Cell Value,Distance,Distance2,Distance2Add,Distance2Sub,Distance2Mul,Distance2Div"), "set_cellular_return_type", "get_cellular_return_type");
// Domain warp.
- ADD_GROUP("Domain Warp", "domain_warp_");
-
ClassDB::bind_method(D_METHOD("set_domain_warp_enabled", "domain_warp_enabled"), &FastNoiseLite::set_domain_warp_enabled);
ClassDB::bind_method(D_METHOD("is_domain_warp_enabled"), &FastNoiseLite::is_domain_warp_enabled);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "domain_warp_enabled"), "set_domain_warp_enabled", "is_domain_warp_enabled");
ClassDB::bind_method(D_METHOD("set_domain_warp_type", "domain_warp_type"), &FastNoiseLite::set_domain_warp_type);
ClassDB::bind_method(D_METHOD("get_domain_warp_type"), &FastNoiseLite::get_domain_warp_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_type", PROPERTY_HINT_ENUM, "Simplex,Simplex Reduced,Basic Grid"), "set_domain_warp_type", "get_domain_warp_type");
ClassDB::bind_method(D_METHOD("set_domain_warp_amplitude", "domain_warp_amplitude"), &FastNoiseLite::set_domain_warp_amplitude);
ClassDB::bind_method(D_METHOD("get_domain_warp_amplitude"), &FastNoiseLite::get_domain_warp_amplitude);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_amplitude"), "set_domain_warp_amplitude", "get_domain_warp_amplitude");
ClassDB::bind_method(D_METHOD("set_domain_warp_frequency", "domain_warp_frequency"), &FastNoiseLite::set_domain_warp_frequency);
ClassDB::bind_method(D_METHOD("get_domain_warp_frequency"), &FastNoiseLite::get_domain_warp_frequency);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_frequency"), "set_domain_warp_frequency", "get_domain_warp_frequency");
ClassDB::bind_method(D_METHOD("set_domain_warp_fractal_type", "domain_warp_fractal_type"), &FastNoiseLite::set_domain_warp_fractal_type);
ClassDB::bind_method(D_METHOD("get_domain_warp_fractal_type"), &FastNoiseLite::get_domain_warp_fractal_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_fractal_type", PROPERTY_HINT_ENUM, "None,Progressive,Independent"), "set_domain_warp_fractal_type", "get_domain_warp_fractal_type");
ClassDB::bind_method(D_METHOD("set_domain_warp_fractal_octaves", "domain_warp_octave_count"), &FastNoiseLite::set_domain_warp_fractal_octaves);
ClassDB::bind_method(D_METHOD("get_domain_warp_fractal_octaves"), &FastNoiseLite::get_domain_warp_fractal_octaves);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_fractal_octaves", PROPERTY_HINT_RANGE, "1,10,1"), "set_domain_warp_fractal_octaves", "get_domain_warp_fractal_octaves");
ClassDB::bind_method(D_METHOD("set_domain_warp_fractal_lacunarity", "domain_warp_lacunarity"), &FastNoiseLite::set_domain_warp_fractal_lacunarity);
ClassDB::bind_method(D_METHOD("get_domain_warp_fractal_lacunarity"), &FastNoiseLite::get_domain_warp_fractal_lacunarity);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_fractal_lacunarity"), "set_domain_warp_fractal_lacunarity", "get_domain_warp_fractal_lacunarity");
ClassDB::bind_method(D_METHOD("set_domain_warp_fractal_gain", "domain_warp_gain"), &FastNoiseLite::set_domain_warp_fractal_gain);
ClassDB::bind_method(D_METHOD("get_domain_warp_fractal_gain"), &FastNoiseLite::get_domain_warp_fractal_gain);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_fractal_gain"), "set_domain_warp_fractal_gain", "get_domain_warp_fractal_gain");
ClassDB::bind_method(D_METHOD("_changed"), &FastNoiseLite::_changed);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "noise_type", PROPERTY_HINT_ENUM, "Simplex,Simplex Smooth,Cellular,Perlin,Value Cubic,Value"), "set_noise_type", "get_noise_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "seed"), "set_seed", "get_seed");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frequency", PROPERTY_HINT_RANGE, ".001,1"), "set_frequency", "get_frequency");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "offset", PROPERTY_HINT_RANGE, "-999999999,999999999,0.01"), "set_offset", "get_offset");
+
+ ADD_GROUP("Fractal", "fractal_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "fractal_type", PROPERTY_HINT_ENUM, "None,FBM,Ridged,Ping-Pong"), "set_fractal_type", "get_fractal_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "fractal_octaves", PROPERTY_HINT_RANGE, "1,10,1"), "set_fractal_octaves", "get_fractal_octaves");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_lacunarity"), "set_fractal_lacunarity", "get_fractal_lacunarity");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_gain"), "set_fractal_gain", "get_fractal_gain");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_weighted_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_fractal_weighted_strength", "get_fractal_weighted_strength");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fractal_ping_pong_strength"), "set_fractal_ping_pong_strength", "get_fractal_ping_pong_strength");
+
+ ADD_GROUP("Cellular", "cellular_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cellular_distance_function", PROPERTY_HINT_ENUM, "Euclidean,Euclidean Squared,Manhattan,Hybrid"), "set_cellular_distance_function", "get_cellular_distance_function");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cellular_jitter"), "set_cellular_jitter", "get_cellular_jitter");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cellular_return_type", PROPERTY_HINT_ENUM, "Cell Value,Distance,Distance2,Distance2Add,Distance2Sub,Distance2Mul,Distance2Div"), "set_cellular_return_type", "get_cellular_return_type");
+
+ ADD_GROUP("Domain Warp", "domain_warp_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "domain_warp_enabled"), "set_domain_warp_enabled", "is_domain_warp_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_type", PROPERTY_HINT_ENUM, "Simplex,Simplex Reduced,Basic Grid"), "set_domain_warp_type", "get_domain_warp_type");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_amplitude"), "set_domain_warp_amplitude", "get_domain_warp_amplitude");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_frequency"), "set_domain_warp_frequency", "get_domain_warp_frequency");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_fractal_type", PROPERTY_HINT_ENUM, "None,Progressive,Independent"), "set_domain_warp_fractal_type", "get_domain_warp_fractal_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "domain_warp_fractal_octaves", PROPERTY_HINT_RANGE, "1,10,1"), "set_domain_warp_fractal_octaves", "get_domain_warp_fractal_octaves");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_fractal_lacunarity"), "set_domain_warp_fractal_lacunarity", "get_domain_warp_fractal_lacunarity");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "domain_warp_fractal_gain"), "set_domain_warp_fractal_gain", "get_domain_warp_fractal_gain");
+
BIND_ENUM_CONSTANT(TYPE_VALUE);
BIND_ENUM_CONSTANT(TYPE_VALUE_CUBIC);
BIND_ENUM_CONSTANT(TYPE_PERLIN);
diff --git a/modules/noise/fastnoise_lite.h b/modules/noise/fastnoise_lite.h
index 4635e26d28..0a4251868b 100644
--- a/modules/noise/fastnoise_lite.h
+++ b/modules/noise/fastnoise_lite.h
@@ -99,36 +99,33 @@ private:
_FastNoiseLite _domain_warp_noise;
Vector3 offset;
- NoiseType noise_type;
- Ref<Gradient> color_ramp;
+ NoiseType noise_type = TYPE_SIMPLEX_SMOOTH;
- int seed;
- real_t frequency;
- bool in_3d_space;
+ int seed = 0;
+ real_t frequency = 0.01;
// Fractal specific.
- FractalType fractal_type;
- int fractal_octaves;
- real_t fractal_lacunarity;
- real_t fractal_gain;
- real_t fractal_weighted_strength;
- real_t fractal_pinp_pong_strength;
+ FractalType fractal_type = FRACTAL_FBM;
+ int fractal_octaves = 5;
+ real_t fractal_lacunarity = 2;
+ real_t fractal_gain = 0.5;
+ real_t fractal_weighted_strength = 0;
+ real_t fractal_ping_pong_strength = 2;
// Cellular specific.
- CellularDistanceFunction cellular_distance_function;
- CellularReturnType cellular_return_type;
- real_t cellular_jitter;
+ CellularDistanceFunction cellular_distance_function = DISTANCE_EUCLIDEAN;
+ CellularReturnType cellular_return_type = RETURN_DISTANCE;
+ real_t cellular_jitter = 0.45;
// Domain warp specific.
- bool domain_warp_enabled;
- DomainWarpType domain_warp_type;
- real_t domain_warp_frequency;
- real_t domain_warp_amplitude;
-
- DomainWarpFractalType domain_warp_fractal_type;
- int domain_warp_fractal_octaves;
- real_t domain_warp_fractal_lacunarity;
- real_t domain_warp_fractal_gain;
+ bool domain_warp_enabled = false;
+ DomainWarpType domain_warp_type = DOMAIN_WARP_SIMPLEX;
+ real_t domain_warp_amplitude = 30.0;
+ real_t domain_warp_frequency = 0.05;
+ DomainWarpFractalType domain_warp_fractal_type = DOMAIN_WARP_FRACTAL_PROGRESSIVE;
+ int domain_warp_fractal_octaves = 5;
+ real_t domain_warp_fractal_lacunarity = 6;
+ real_t domain_warp_fractal_gain = 0.5;
public:
FastNoiseLite();
@@ -145,15 +142,9 @@ public:
void set_frequency(real_t p_freq);
real_t get_frequency() const;
- void set_in_3d_space(bool p_enable);
- bool is_in_3d_space() const;
-
void set_offset(Vector3 p_offset);
Vector3 get_offset() const;
- void set_color_ramp(const Ref<Gradient> &p_gradient);
- Ref<Gradient> get_color_ramp() const;
-
// Fractal specific.
void set_fractal_type(FractalType p_type);
@@ -212,17 +203,13 @@ public:
real_t get_domain_warp_fractal_gain() const;
// Interface methods.
+ real_t get_noise_1d(real_t p_x) const override;
- Ref<Image> get_image(int p_width, int p_height, bool p_invert = false) override;
- Ref<Image> get_seamless_image(int p_width, int p_height, bool p_invert = false, real_t p_blend_skirt = 0.1) override;
-
- real_t get_noise_1d(real_t p_x) override;
-
- real_t get_noise_2dv(Vector2 p_v) override;
- real_t get_noise_2d(real_t p_x, real_t p_y) override;
+ real_t get_noise_2dv(Vector2 p_v) const override;
+ real_t get_noise_2d(real_t p_x, real_t p_y) const override;
- real_t get_noise_3dv(Vector3 p_v) override;
- real_t get_noise_3d(real_t p_x, real_t p_y, real_t p_z) override;
+ real_t get_noise_3dv(Vector3 p_v) const override;
+ real_t get_noise_3d(real_t p_x, real_t p_y, real_t p_z) const override;
void _changed();
};
diff --git a/modules/noise/noise.cpp b/modules/noise/noise.cpp
index 430e8c87cf..ad3df0a016 100644
--- a/modules/noise/noise.cpp
+++ b/modules/noise/noise.cpp
@@ -30,13 +30,13 @@
#include "noise.h"
-Ref<Image> Noise::get_seamless_image(int p_width, int p_height, bool p_invert, real_t p_blend_skirt) {
+Ref<Image> Noise::get_seamless_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space, real_t p_blend_skirt) const {
int skirt_width = p_width * p_blend_skirt;
int skirt_height = p_height * p_blend_skirt;
int src_width = p_width + skirt_width;
int src_height = p_height + skirt_height;
- Ref<Image> src = get_image(src_width, src_height, p_invert);
+ Ref<Image> src = get_image(src_width, src_height, p_invert, p_in_3d_space);
bool grayscale = (src->get_format() == Image::FORMAT_L8);
if (grayscale) {
return _generate_seamless_image<uint8_t>(src, p_width, p_height, p_invert, p_blend_skirt);
@@ -54,6 +54,50 @@ uint8_t Noise::_alpha_blend<uint8_t>(uint8_t p_bg, uint8_t p_fg, int p_alpha) co
return (uint8_t)((alpha * p_fg + inv_alpha * p_bg) >> 8);
}
+Ref<Image> Noise::get_image(int p_width, int p_height, bool p_invert, bool p_in_3d_space) const {
+ Vector<uint8_t> data;
+ data.resize(p_width * p_height);
+
+ uint8_t *wd8 = data.ptrw();
+
+ // Get all values and identify min/max values.
+ Vector<real_t> values;
+ values.resize(p_width * p_height);
+ real_t min_val = 1000;
+ real_t max_val = -1000;
+
+ for (int y = 0, i = 0; y < p_height; y++) {
+ for (int x = 0; x < p_width; x++, i++) {
+ values.set(i, p_in_3d_space ? get_noise_3d(x, y, 0.0) : get_noise_2d(x, y));
+ if (values[i] > max_val) {
+ max_val = values[i];
+ }
+ if (values[i] < min_val) {
+ min_val = values[i];
+ }
+ }
+ }
+
+ // Normalize values and write to texture.
+ uint8_t value;
+ for (int i = 0, x = 0; i < p_height; i++) {
+ for (int j = 0; j < p_width; j++, x++) {
+ if (max_val == min_val) {
+ value = 0;
+ } else {
+ value = uint8_t(CLAMP((values[x] - min_val) / (max_val - min_val) * 255.f, 0, 255));
+ }
+ if (p_invert) {
+ value = 255 - value;
+ }
+
+ wd8[x] = value;
+ }
+ }
+
+ return memnew(Image(p_width, p_height, false, Image::FORMAT_L8, data));
+}
+
void Noise::_bind_methods() {
// Noise functions.
ClassDB::bind_method(D_METHOD("get_noise_1d", "x"), &Noise::get_noise_1d);
@@ -63,6 +107,6 @@ void Noise::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_noise_3dv", "v"), &Noise::get_noise_3dv);
// Textures.
- ClassDB::bind_method(D_METHOD("get_image", "width", "height", "invert"), &Noise::get_image, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_seamless_image", "width", "height", "invert", "skirt"), &Noise::get_seamless_image, DEFVAL(false), DEFVAL(0.1));
+ ClassDB::bind_method(D_METHOD("get_image", "width", "height", "invert", "in_3d_space"), &Noise::get_image, DEFVAL(false), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_seamless_image", "width", "height", "invert", "in_3d_space", "skirt"), &Noise::get_seamless_image, DEFVAL(false), DEFVAL(false), DEFVAL(0.1));
}
diff --git a/modules/noise/noise.h b/modules/noise/noise.h
index 853c24b485..8083334388 100644
--- a/modules/noise/noise.h
+++ b/modules/noise/noise.h
@@ -81,7 +81,7 @@ class Noise : public Resource {
};
template <typename T>
- Ref<Image> _generate_seamless_image(Ref<Image> p_src, int p_width, int p_height, bool p_invert, real_t p_blend_skirt) {
+ Ref<Image> _generate_seamless_image(Ref<Image> p_src, int p_width, int p_height, bool p_invert, real_t p_blend_skirt) const {
/*
To make a seamless image, we swap the quadrants so the edges are perfect matches.
We initially get a 10% larger image so we have an overlap we can use to blend over the seams.
@@ -225,16 +225,16 @@ public:
// Virtual destructor so we can delete any Noise derived object when referenced as a Noise*.
virtual ~Noise() {}
- virtual real_t get_noise_1d(real_t p_x) = 0;
+ virtual real_t get_noise_1d(real_t p_x) const = 0;
- virtual real_t get_noise_2dv(Vector2 p_v) = 0;
- virtual real_t get_noise_2d(real_t p_x, real_t p_y) = 0;
+ virtual real_t get_noise_2dv(Vector2 p_v) const = 0;
+ virtual real_t get_noise_2d(real_t p_x, real_t p_y) const = 0;
- virtual real_t get_noise_3dv(Vector3 p_v) = 0;
- virtual real_t get_noise_3d(real_t p_x, real_t p_y, real_t p_z) = 0;
+ virtual real_t get_noise_3dv(Vector3 p_v) const = 0;
+ virtual real_t get_noise_3d(real_t p_x, real_t p_y, real_t p_z) const = 0;
- virtual Ref<Image> get_image(int p_width, int p_height, bool p_invert = false) = 0;
- virtual Ref<Image> get_seamless_image(int p_width, int p_height, bool p_invert = false, real_t p_blend_skirt = 0.1);
+ virtual Ref<Image> get_image(int p_width, int p_height, bool p_invert = false, bool p_in_3d_space = false) const;
+ virtual Ref<Image> get_seamless_image(int p_width, int p_height, bool p_invert = false, bool p_in_3d_space = false, real_t p_blend_skirt = 0.1) const;
};
#endif // NOISE_H
diff --git a/modules/noise/noise_texture.cpp b/modules/noise/noise_texture.cpp
index 276335797a..e9d16e548c 100644
--- a/modules/noise/noise_texture.cpp
+++ b/modules/noise/noise_texture.cpp
@@ -47,15 +47,22 @@ NoiseTexture::~NoiseTexture() {
}
void NoiseTexture::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_update_texture"), &NoiseTexture::_update_texture);
+ ClassDB::bind_method(D_METHOD("_generate_texture"), &NoiseTexture::_generate_texture);
+ ClassDB::bind_method(D_METHOD("_thread_done", "image"), &NoiseTexture::_thread_done);
+
ClassDB::bind_method(D_METHOD("set_width", "width"), &NoiseTexture::set_width);
ClassDB::bind_method(D_METHOD("set_height", "height"), &NoiseTexture::set_height);
- ClassDB::bind_method(D_METHOD("set_noise", "noise"), &NoiseTexture::set_noise);
- ClassDB::bind_method(D_METHOD("get_noise"), &NoiseTexture::get_noise);
-
ClassDB::bind_method(D_METHOD("set_invert", "invert"), &NoiseTexture::set_invert);
ClassDB::bind_method(D_METHOD("get_invert"), &NoiseTexture::get_invert);
+ ClassDB::bind_method(D_METHOD("set_in_3d_space", "enable"), &NoiseTexture::set_in_3d_space);
+ ClassDB::bind_method(D_METHOD("is_in_3d_space"), &NoiseTexture::is_in_3d_space);
+
+ ClassDB::bind_method(D_METHOD("set_generate_mipmaps", "invert"), &NoiseTexture::set_generate_mipmaps);
+ ClassDB::bind_method(D_METHOD("is_generating_mipmaps"), &NoiseTexture::is_generating_mipmaps);
+
ClassDB::bind_method(D_METHOD("set_seamless", "seamless"), &NoiseTexture::set_seamless);
ClassDB::bind_method(D_METHOD("get_seamless"), &NoiseTexture::get_seamless);
@@ -68,17 +75,22 @@ void NoiseTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bump_strength", "bump_strength"), &NoiseTexture::set_bump_strength);
ClassDB::bind_method(D_METHOD("get_bump_strength"), &NoiseTexture::get_bump_strength);
- ClassDB::bind_method(D_METHOD("_update_texture"), &NoiseTexture::_update_texture);
- ClassDB::bind_method(D_METHOD("_generate_texture"), &NoiseTexture::_generate_texture);
- ClassDB::bind_method(D_METHOD("_thread_done", "image"), &NoiseTexture::_thread_done);
+ ClassDB::bind_method(D_METHOD("set_color_ramp", "gradient"), &NoiseTexture::set_color_ramp);
+ ClassDB::bind_method(D_METHOD("get_color_ramp"), &NoiseTexture::get_color_ramp);
+
+ ClassDB::bind_method(D_METHOD("set_noise", "noise"), &NoiseTexture::set_noise);
+ ClassDB::bind_method(D_METHOD("get_noise"), &NoiseTexture::get_noise);
ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_width", "get_width");
ADD_PROPERTY(PropertyInfo(Variant::INT, "height", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_height", "get_height");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "invert"), "set_invert", "get_invert");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "in_3d_space"), "set_in_3d_space", "is_in_3d_space");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "generate_mipmaps"), "set_generate_mipmaps", "is_generating_mipmaps");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "seamless"), "set_seamless", "get_seamless");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "seamless_blend_skirt", PROPERTY_HINT_RANGE, "0.05,1,0.001"), "set_seamless_blend_skirt", "get_seamless_blend_skirt");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normal_map"), "set_as_normal_map", "is_normal_map");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bump_strength", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater"), "set_bump_strength", "get_bump_strength");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "color_ramp", PROPERTY_HINT_RESOURCE_TYPE, "Gradient"), "set_color_ramp", "get_color_ramp");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "Noise"), "set_noise", "get_noise");
}
@@ -143,18 +155,42 @@ Ref<Image> NoiseTexture::_generate_texture() {
Ref<Image> image;
if (seamless) {
- image = ref_noise->get_seamless_image(size.x, size.y, invert, seamless_blend_skirt);
+ image = ref_noise->get_seamless_image(size.x, size.y, invert, in_3d_space, seamless_blend_skirt);
} else {
- image = ref_noise->get_image(size.x, size.y, invert);
+ image = ref_noise->get_image(size.x, size.y, invert, in_3d_space);
+ }
+ if (color_ramp.is_valid()) {
+ image = _modulate_with_gradient(image, color_ramp);
}
-
if (as_normal_map) {
image->bump_map_to_normal_map(bump_strength);
}
+ if (generate_mipmaps) {
+ image->generate_mipmaps();
+ }
return image;
}
+Ref<Image> NoiseTexture::_modulate_with_gradient(Ref<Image> p_image, Ref<Gradient> p_gradient) {
+ int width = p_image->get_width();
+ int height = p_image->get_height();
+
+ Ref<Image> new_image;
+ new_image.instantiate();
+ new_image->create(width, height, false, Image::FORMAT_RGBA8);
+
+ for (int row = 0; row < height; row++) {
+ for (int col = 0; col < width; col++) {
+ Color pixel_color = p_image->get_pixel(col, row);
+ Color ramp_color = color_ramp->get_color_at_offset(pixel_color.get_luminance());
+ new_image->set_pixel(col, row, ramp_color);
+ }
+ }
+
+ return new_image;
+}
+
void NoiseTexture::_update_texture() {
bool use_thread = true;
if (first_time) {
@@ -227,6 +263,29 @@ bool NoiseTexture::get_invert() const {
return invert;
}
+void NoiseTexture::set_in_3d_space(bool p_enable) {
+ if (p_enable == in_3d_space) {
+ return;
+ }
+ in_3d_space = p_enable;
+ _queue_update();
+}
+bool NoiseTexture::is_in_3d_space() const {
+ return in_3d_space;
+}
+
+void NoiseTexture::set_generate_mipmaps(bool p_enable) {
+ if (p_enable == generate_mipmaps) {
+ return;
+ }
+ generate_mipmaps = p_enable;
+ _queue_update();
+}
+
+bool NoiseTexture::is_generating_mipmaps() const {
+ return generate_mipmaps;
+}
+
void NoiseTexture::set_seamless(bool p_seamless) {
if (p_seamless == seamless) {
return;
@@ -241,6 +300,8 @@ bool NoiseTexture::get_seamless() {
}
void NoiseTexture::set_seamless_blend_skirt(real_t p_blend_skirt) {
+ ERR_FAIL_COND(p_blend_skirt < 0.05 || p_blend_skirt > 1);
+
if (p_blend_skirt == seamless_blend_skirt) {
return;
}
@@ -278,6 +339,24 @@ float NoiseTexture::get_bump_strength() {
return bump_strength;
}
+void NoiseTexture::set_color_ramp(const Ref<Gradient> &p_gradient) {
+ if (p_gradient == color_ramp) {
+ return;
+ }
+ if (color_ramp.is_valid()) {
+ color_ramp->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NoiseTexture::_queue_update));
+ }
+ color_ramp = p_gradient;
+ if (color_ramp.is_valid()) {
+ color_ramp->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NoiseTexture::_queue_update));
+ }
+ _queue_update();
+}
+
+Ref<Gradient> NoiseTexture::get_color_ramp() const {
+ return color_ramp;
+}
+
int NoiseTexture::get_width() const {
return size.x;
}
diff --git a/modules/noise/noise_texture.h b/modules/noise/noise_texture.h
index 2a94df39d4..6c088562a1 100644
--- a/modules/noise/noise_texture.h
+++ b/modules/noise/noise_texture.h
@@ -51,15 +51,18 @@ private:
mutable RID texture;
uint32_t flags = 0;
- Ref<Noise> noise;
+ Size2i size = Size2i(512, 512);
bool invert = false;
- Vector2i size = Vector2i(512, 512);
- Vector2 noise_offset;
+ bool in_3d_space = false;
+ bool generate_mipmaps = true;
bool seamless = false;
real_t seamless_blend_skirt = 0.1;
bool as_normal_map = false;
float bump_strength = 8.0;
+ Ref<Gradient> color_ramp;
+ Ref<Noise> noise;
+
void _thread_done(const Ref<Image> &p_image);
static void _thread_function(void *p_ud);
@@ -68,6 +71,8 @@ private:
void _update_texture();
void _set_texture_image(const Ref<Image> &p_image);
+ Ref<Image> _modulate_with_gradient(Ref<Image> p_image, Ref<Gradient> p_gradient);
+
protected:
static void _bind_methods();
virtual void _validate_property(PropertyInfo &property) const override;
@@ -82,6 +87,12 @@ public:
void set_invert(bool p_invert);
bool get_invert() const;
+ void set_in_3d_space(bool p_enable);
+ bool is_in_3d_space() const;
+
+ void set_generate_mipmaps(bool p_enable);
+ bool is_generating_mipmaps() const;
+
void set_seamless(bool p_seamless);
bool get_seamless();
@@ -94,6 +105,9 @@ public:
void set_bump_strength(float p_bump_strength);
float get_bump_strength();
+ void set_color_ramp(const Ref<Gradient> &p_gradient);
+ Ref<Gradient> get_color_ramp() const;
+
int get_width() const override;
int get_height() const override;
diff --git a/modules/noise/register_types.cpp b/modules/noise/register_types.cpp
index 81bb0317c1..3623da3bb9 100644
--- a/modules/noise/register_types.cpp
+++ b/modules/noise/register_types.cpp
@@ -34,10 +34,19 @@
#include "noise.h"
#include "noise_texture.h"
+#ifdef TOOLS_ENABLED
+#include "editor/editor_plugin.h"
+#include "editor/noise_editor_plugin.h"
+#endif
+
void register_noise_types() {
GDREGISTER_CLASS(NoiseTexture);
GDREGISTER_ABSTRACT_CLASS(Noise);
GDREGISTER_CLASS(FastNoiseLite);
+
+#ifdef TOOLS_ENABLED
+ EditorPlugins::add_by_type<NoiseEditorPlugin>();
+#endif
}
void unregister_noise_types() {
diff --git a/modules/openxr/action_map/openxr_action_map.cpp b/modules/openxr/action_map/openxr_action_map.cpp
index 2ba33419d7..366e131369 100644
--- a/modules/openxr/action_map/openxr_action_map.cpp
+++ b/modules/openxr/action_map/openxr_action_map.cpp
@@ -55,7 +55,14 @@ void OpenXRActionMap::_bind_methods() {
}
void OpenXRActionMap::set_action_sets(Array p_action_sets) {
- action_sets = p_action_sets;
+ action_sets.clear();
+
+ for (int i = 0; i < p_action_sets.size(); i++) {
+ Ref<OpenXRActionSet> action_set = p_action_sets[i];
+ if (action_set.is_valid() && action_sets.find(action_set) == -1) {
+ action_sets.push_back(action_set);
+ }
+ }
}
Array OpenXRActionMap::get_action_sets() const {
@@ -99,7 +106,14 @@ void OpenXRActionMap::remove_action_set(Ref<OpenXRActionSet> p_action_set) {
}
void OpenXRActionMap::set_interaction_profiles(Array p_interaction_profiles) {
- interaction_profiles = p_interaction_profiles;
+ interaction_profiles.clear();
+
+ for (int i = 0; i < p_interaction_profiles.size(); i++) {
+ Ref<OpenXRInteractionProfile> interaction_profile = p_interaction_profiles[i];
+ if (interaction_profile.is_valid() && interaction_profiles.find(interaction_profile) == -1) {
+ interaction_profiles.push_back(interaction_profile);
+ }
+ }
}
Array OpenXRActionMap::get_interaction_profiles() const {
diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp
index ae3617938e..2e9be48f01 100644
--- a/modules/openxr/openxr_api.cpp
+++ b/modules/openxr/openxr_api.cpp
@@ -1096,7 +1096,7 @@ Size2 OpenXRAPI::get_recommended_target_size() {
return target_size;
}
-XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
+XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, const Vector3 &r_angular_velocity) {
XrResult result;
ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE);
@@ -2297,7 +2297,7 @@ Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
}
-XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
+XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, const Vector3 &r_angular_velocity) {
ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
Action *action = action_owner.get_or_null(p_action);
ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.h
index 7baf581a05..57475944c0 100644
--- a/modules/openxr/openxr_api.h
+++ b/modules/openxr/openxr_api.h
@@ -247,7 +247,7 @@ public:
bool can_render() { return instance != XR_NULL_HANDLE && session != XR_NULL_HANDLE && running && view_pose_valid && frame_state.shouldRender; };
Size2 get_recommended_target_size();
- XRPose::TrackingConfidence get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
+ XRPose::TrackingConfidence get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, const Vector3 &r_angular_velocity);
bool get_view_transform(uint32_t p_view, Transform3D &r_transform);
bool get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, CameraMatrix &p_camera_matrix);
bool process();
@@ -285,7 +285,7 @@ public:
bool get_action_bool(RID p_action, RID p_tracker);
float get_action_float(RID p_action, RID p_tracker);
Vector2 get_action_vector2(RID p_action, RID p_tracker);
- XRPose::TrackingConfidence get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
+ XRPose::TrackingConfidence get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, const Vector3 &r_angular_velocity);
bool trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns);
OpenXRAPI();
diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp
index 0ae8219e23..437fbe76ab 100644
--- a/modules/text_server_adv/text_server_adv.cpp
+++ b/modules/text_server_adv/text_server_adv.cpp
@@ -3255,6 +3255,19 @@ void TextServerAdvanced::font_set_global_oversampling(double p_oversampling) {
/* Shaped text buffer interface */
/*************************************************************************/
+int64_t TextServerAdvanced::_convert_pos(const String &p_utf32, const Char16String &p_utf16, int64_t p_pos) const {
+ int64_t limit = p_pos;
+ if (p_utf32.length() != p_utf16.length()) {
+ const UChar *data = p_utf16.ptr();
+ for (int i = 0; i < p_pos; i++) {
+ if (U16_IS_LEAD(data[i])) {
+ limit--;
+ }
+ }
+ }
+ return limit;
+}
+
int64_t TextServerAdvanced::_convert_pos(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const {
int64_t limit = p_pos;
if (p_sd->text.length() != p_sd->utf16.length()) {
@@ -5555,6 +5568,53 @@ String TextServerAdvanced::string_to_lower(const String &p_string, const String
return String::utf16(lower.ptr(), len);
}
+PackedInt32Array TextServerAdvanced::string_get_word_breaks(const String &p_string, const String &p_language) const {
+ // Convert to UTF-16.
+ Char16String utf16 = p_string.utf16();
+
+ Set<int> breaks;
+ UErrorCode err = U_ZERO_ERROR;
+ UBreakIterator *bi = ubrk_open(UBRK_LINE, p_language.ascii().get_data(), (const UChar *)utf16.ptr(), utf16.length(), &err);
+ if (U_FAILURE(err)) {
+ // No data loaded - use fallback.
+ for (int i = 0; i < p_string.length(); i++) {
+ char32_t c = p_string[i];
+ if (is_whitespace(c) || is_linebreak(c)) {
+ breaks.insert(i);
+ }
+ }
+ } else {
+ while (ubrk_next(bi) != UBRK_DONE) {
+ int pos = _convert_pos(p_string, utf16, ubrk_current(bi)) - 1;
+ if (pos != p_string.length() - 1) {
+ breaks.insert(pos);
+ }
+ }
+ }
+ ubrk_close(bi);
+
+ PackedInt32Array ret;
+ for (int i = 0; i < p_string.length(); i++) {
+ char32_t c = p_string[i];
+ if (c == 0xfffc) {
+ continue;
+ }
+ if (u_ispunct(c) && c != 0x005F) {
+ ret.push_back(i);
+ continue;
+ }
+ if (is_underscore(c)) {
+ ret.push_back(i);
+ continue;
+ }
+ if (breaks.has(i)) {
+ ret.push_back(i);
+ continue;
+ }
+ }
+ return ret;
+}
+
TextServerAdvanced::TextServerAdvanced() {
_insert_num_systems_lang();
_insert_feature_sets();
diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h
index fa59566a94..1b4293aa72 100644
--- a/modules/text_server_adv/text_server_adv.h
+++ b/modules/text_server_adv/text_server_adv.h
@@ -393,11 +393,13 @@ class TextServerAdvanced : public TextServerExtension {
mutable RID_PtrOwner<ShapedTextDataAdvanced> shaped_owner;
void _realign(ShapedTextDataAdvanced *p_sd) const;
+ int64_t _convert_pos(const String &p_utf32, const Char16String &p_utf16, int64_t p_pos) const;
int64_t _convert_pos(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const;
int64_t _convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const;
bool _shape_substr(ShapedTextDataAdvanced *p_new_sd, const ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_length) const;
void _shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_end, hb_script_t p_script, hb_direction_t p_direction, Array p_fonts, int64_t p_span, int64_t p_fb_index);
Glyph _shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, const RID &p_font, int64_t p_font_size);
+
_FORCE_INLINE_ void _add_featuers(const Dictionary &p_source, Vector<hb_feature_t> &r_ftrs);
// HarfBuzz bitmap font interface.
@@ -686,6 +688,8 @@ public:
virtual String parse_number(const String &p_string, const String &p_language = "") const override;
virtual String percent_sign(const String &p_language = "") const override;
+ virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const override;
+
virtual String strip_diacritics(const String &p_string) const override;
virtual String string_to_upper(const String &p_string, const String &p_language = "") const override;
diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp
index 1251aaf2b9..d84e9e581a 100644
--- a/modules/text_server_fb/text_server_fb.cpp
+++ b/modules/text_server_fb/text_server_fb.cpp
@@ -3079,7 +3079,7 @@ bool TextServerFallback::shaped_text_update_breaks(const RID &p_shaped) {
if (sd_glyphs[i].count > 0) {
char32_t c = sd->text[sd_glyphs[i].start - sd->start];
if (c_punct_size == 0) {
- if (is_punct(c)) {
+ if (is_punct(c) && c != 0x005F) {
sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION;
}
} else {
@@ -3623,6 +3623,29 @@ String TextServerFallback::string_to_lower(const String &p_string, const String
return lower;
}
+PackedInt32Array TextServerFallback::string_get_word_breaks(const String &p_string, const String &p_language) const {
+ PackedInt32Array ret;
+ for (int i = 0; i < p_string.length(); i++) {
+ char32_t c = p_string[i];
+ if (c == 0xfffc) {
+ continue;
+ }
+ if (is_punct(c) && c != 0x005F) {
+ ret.push_back(i);
+ continue;
+ }
+ if (is_underscore(c)) {
+ ret.push_back(i);
+ continue;
+ }
+ if (is_whitespace(c) || is_linebreak(c)) {
+ ret.push_back(i);
+ continue;
+ }
+ }
+ return ret;
+}
+
TextServerFallback::TextServerFallback() {
_insert_feature_sets();
};
diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h
index d6f61e02f8..c837029623 100644
--- a/modules/text_server_fb/text_server_fb.h
+++ b/modules/text_server_fb/text_server_fb.h
@@ -573,6 +573,8 @@ public:
virtual double shaped_text_get_underline_position(const RID &p_shaped) const override;
virtual double shaped_text_get_underline_thickness(const RID &p_shaped) const override;
+ virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const override;
+
virtual String string_to_upper(const String &p_string, const String &p_language = "") const override;
virtual String string_to_lower(const String &p_string, const String &p_language = "") const override;
diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp
index 1ef571b6ee..58c329f043 100644
--- a/modules/websocket/wsl_client.cpp
+++ b/modules/websocket/wsl_client.cpp
@@ -273,6 +273,7 @@ void WSLClient::poll() {
return; // Not connected.
}
+ _tcp->poll();
switch (_tcp->get_status()) {
case StreamPeerTCP::STATUS_NONE:
// Clean close
@@ -336,7 +337,7 @@ MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
return CONNECTION_CONNECTED;
}
- if (_tcp->is_connected_to_host() || _resolver_id != IP::RESOLVER_INVALID_ID) {
+ if (_tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING || _resolver_id != IP::RESOLVER_INVALID_ID) {
return CONNECTION_CONNECTING;
}
diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp
index 06b0e31801..debfe8e950 100644
--- a/modules/webxr/webxr_interface_js.cpp
+++ b/modules/webxr/webxr_interface_js.cpp
@@ -59,7 +59,7 @@ void _emwebxr_on_session_started(char *p_reference_space_type) {
ERR_FAIL_COND(interface.is_null());
String reference_space_type = String(p_reference_space_type);
- ((WebXRInterfaceJS *)interface.ptr())->_set_reference_space_type(reference_space_type);
+ static_cast<WebXRInterfaceJS *>(interface.ptr())->_set_reference_space_type(reference_space_type);
interface->emit_signal(SNAME("session_started"));
}
@@ -94,7 +94,7 @@ void _emwebxr_on_controller_changed() {
Ref<XRInterface> interface = xr_server->find_interface("WebXR");
ERR_FAIL_COND(interface.is_null());
- ((WebXRInterfaceJS *)interface.ptr())->_on_controller_changed();
+ static_cast<WebXRInterfaceJS *>(interface.ptr())->_on_controller_changed();
}
extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_input_event(char *p_signal_name, int p_input_source) {
diff --git a/platform/android/SCsub b/platform/android/SCsub
index 1a3c158d2e..ad226255bc 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -8,6 +8,7 @@ android_files = [
"file_access_android.cpp",
"audio_driver_opensl.cpp",
"dir_access_jandroid.cpp",
+ "tts_android.cpp",
"thread_jandroid.cpp",
"net_socket_android.cpp",
"java_godot_lib_jni.cpp",
diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp
index e7de287fc6..2eb7056a36 100644
--- a/platform/android/display_server_android.cpp
+++ b/platform/android/display_server_android.cpp
@@ -34,6 +34,7 @@
#include "java_godot_io_wrapper.h"
#include "java_godot_wrapper.h"
#include "os_android.h"
+#include "tts_android.h"
#if defined(VULKAN_ENABLED)
#include "drivers/vulkan/rendering_device_vulkan.h"
@@ -63,6 +64,7 @@ bool DisplayServerAndroid::has_feature(Feature p_feature) const {
case FEATURE_ORIENTATION:
case FEATURE_TOUCHSCREEN:
case FEATURE_VIRTUAL_KEYBOARD:
+ case FEATURE_TEXT_TO_SPEECH:
return true;
default:
return false;
@@ -73,6 +75,34 @@ String DisplayServerAndroid::get_name() const {
return "Android";
}
+bool DisplayServerAndroid::tts_is_speaking() const {
+ return TTS_Android::is_speaking();
+}
+
+bool DisplayServerAndroid::tts_is_paused() const {
+ return TTS_Android::is_paused();
+}
+
+Array DisplayServerAndroid::tts_get_voices() const {
+ return TTS_Android::get_voices();
+}
+
+void DisplayServerAndroid::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ TTS_Android::speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
+}
+
+void DisplayServerAndroid::tts_pause() {
+ TTS_Android::pause();
+}
+
+void DisplayServerAndroid::tts_resume() {
+ TTS_Android::resume();
+}
+
+void DisplayServerAndroid::tts_stop() {
+ TTS_Android::stop();
+}
+
void DisplayServerAndroid::clipboard_set(const String &p_text) {
GodotJavaWrapper *godot_java = OS_Android::get_singleton()->get_godot_java();
ERR_FAIL_COND(!godot_java);
diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h
index 1d268bbcfd..2604214ac0 100644
--- a/platform/android/display_server_android.h
+++ b/platform/android/display_server_android.h
@@ -91,6 +91,15 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+
virtual void clipboard_set(const String &p_text) override;
virtual String clipboard_get() const override;
virtual bool clipboard_has() const override;
diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.java b/platform/android/java/lib/src/org/godotengine/godot/Godot.java
index 6e597163ab..377881be85 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/Godot.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.java
@@ -36,6 +36,7 @@ import static android.content.Context.WINDOW_SERVICE;
import org.godotengine.godot.input.GodotEditText;
import org.godotengine.godot.plugin.GodotPlugin;
import org.godotengine.godot.plugin.GodotPluginRegistry;
+import org.godotengine.godot.tts.GodotTTS;
import org.godotengine.godot.utils.GodotNetUtils;
import org.godotengine.godot.utils.PermissionsUtil;
import org.godotengine.godot.xr.XRMode;
@@ -165,6 +166,7 @@ public class Godot extends Fragment implements SensorEventListener, IDownloaderC
public static GodotIO io;
public static GodotNetUtils netUtils;
+ public static GodotTTS tts;
public interface ResultCallback {
void callback(int requestCode, int resultCode, Intent data);
@@ -458,6 +460,7 @@ public class Godot extends Fragment implements SensorEventListener, IDownloaderC
io = new GodotIO(activity);
GodotLib.io = io;
netUtils = new GodotNetUtils(activity);
+ tts = new GodotTTS(activity);
mSensorManager = (SensorManager)activity.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
@@ -663,14 +666,13 @@ public class Godot extends Fragment implements SensorEventListener, IDownloaderC
}
public String getClipboard() {
- String copiedText = "";
-
- if (mClipboard.hasPrimaryClip()) {
- ClipData.Item item = mClipboard.getPrimaryClip().getItemAt(0);
- copiedText = item.getText().toString();
- }
-
- return copiedText;
+ ClipData clipData = mClipboard.getPrimaryClip();
+ if (clipData == null)
+ return "";
+ CharSequence text = clipData.getItemAt(0).getText();
+ if (text == null)
+ return "";
+ return text.toString();
}
public void setClipboard(String p_text) {
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
index 253a51b83c..1f8f8c82a6 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
@@ -92,6 +92,11 @@ public class GodotLib {
public static native boolean step();
/**
+ * TTS callback.
+ */
+ public static native void ttsCallback(int event, int id, int pos);
+
+ /**
* Forward touch events from the main thread to the GL thread.
*/
public static native void touch(int inputDevice, int event, int pointer, int pointerCount, float[] positions);
diff --git a/platform/android/java/lib/src/org/godotengine/godot/tts/GodotTTS.java b/platform/android/java/lib/src/org/godotengine/godot/tts/GodotTTS.java
new file mode 100644
index 0000000000..2239ddac8e
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/tts/GodotTTS.java
@@ -0,0 +1,298 @@
+/*************************************************************************/
+/* GodotTTS.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.tts;
+
+import org.godotengine.godot.GodotLib;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.speech.tts.TextToSpeech;
+import android.speech.tts.UtteranceProgressListener;
+import android.speech.tts.Voice;
+
+import androidx.annotation.Keep;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Set;
+
+/**
+ * Wrapper for Android Text to Speech API and custom utterance query implementation.
+ * <p>
+ * A [GodotTTS] provides the following features:
+ * <p>
+ * <ul>
+ * <li>Access to the Android Text to Speech API.
+ * <li>Utterance pause / resume functions, unsupported by Android TTS API.
+ * </ul>
+ */
+@Keep
+public class GodotTTS extends UtteranceProgressListener {
+ // Note: These constants must be in sync with DisplayServer::TTSUtteranceEvent enum from "servers/display_server.h".
+ final private static int EVENT_START = 0;
+ final private static int EVENT_END = 1;
+ final private static int EVENT_CANCEL = 2;
+ final private static int EVENT_BOUNDARY = 3;
+
+ final private TextToSpeech synth;
+ final private LinkedList<GodotUtterance> queue;
+ final private Object lock = new Object();
+ private GodotUtterance lastUtterance;
+
+ private boolean speaking;
+ private boolean paused;
+
+ public GodotTTS(Activity p_activity) {
+ synth = new TextToSpeech(p_activity, null);
+ queue = new LinkedList<GodotUtterance>();
+
+ synth.setOnUtteranceProgressListener(this);
+ }
+
+ private void updateTTS() {
+ if (!speaking && queue.size() > 0) {
+ int mode = TextToSpeech.QUEUE_FLUSH;
+ GodotUtterance message = queue.pollFirst();
+
+ Set<Voice> voices = synth.getVoices();
+ for (Voice v : voices) {
+ if (v.getName().equals(message.voice)) {
+ synth.setVoice(v);
+ break;
+ }
+ }
+ synth.setPitch(message.pitch);
+ synth.setSpeechRate(message.rate);
+
+ Bundle params = new Bundle();
+ params.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, message.volume / 100.f);
+
+ lastUtterance = message;
+ lastUtterance.start = 0;
+ lastUtterance.offset = 0;
+ paused = false;
+
+ synth.speak(message.text, mode, params, String.valueOf(message.id));
+ speaking = true;
+ }
+ }
+
+ /**
+ * Called by TTS engine when the TTS service is about to speak the specified range.
+ */
+ @Override
+ public void onRangeStart(String utteranceId, int start, int end, int frame) {
+ synchronized (lock) {
+ if (lastUtterance != null && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ lastUtterance.offset = start;
+ GodotLib.ttsCallback(EVENT_BOUNDARY, lastUtterance.id, start + lastUtterance.start);
+ }
+ }
+ }
+
+ /**
+ * Called by TTS engine when an utterance was canceled in progress.
+ */
+ @Override
+ public void onStop(String utteranceId, boolean interrupted) {
+ synchronized (lock) {
+ if (lastUtterance != null && !paused && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ GodotLib.ttsCallback(EVENT_CANCEL, lastUtterance.id, 0);
+ speaking = false;
+ updateTTS();
+ }
+ }
+ }
+
+ /**
+ * Called by TTS engine when an utterance has begun to be spoken..
+ */
+ @Override
+ public void onStart(String utteranceId) {
+ synchronized (lock) {
+ if (lastUtterance != null && lastUtterance.start == 0 && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ GodotLib.ttsCallback(EVENT_START, lastUtterance.id, 0);
+ }
+ }
+ }
+
+ /**
+ * Called by TTS engine when an utterance was successfully finished.
+ */
+ @Override
+ public void onDone(String utteranceId) {
+ synchronized (lock) {
+ if (lastUtterance != null && !paused && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ GodotLib.ttsCallback(EVENT_END, lastUtterance.id, 0);
+ speaking = false;
+ updateTTS();
+ }
+ }
+ }
+
+ /**
+ * Called by TTS engine when an error has occurred during processing.
+ */
+ @Override
+ public void onError(String utteranceId, int errorCode) {
+ synchronized (lock) {
+ if (lastUtterance != null && !paused && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ GodotLib.ttsCallback(EVENT_CANCEL, lastUtterance.id, 0);
+ speaking = false;
+ updateTTS();
+ }
+ }
+ }
+
+ /**
+ * Called by TTS engine when an error has occurred during processing (pre API level 21 version).
+ */
+ @Override
+ public void onError(String utteranceId) {
+ synchronized (lock) {
+ if (lastUtterance != null && !paused && Integer.parseInt(utteranceId) == lastUtterance.id) {
+ GodotLib.ttsCallback(EVENT_CANCEL, lastUtterance.id, 0);
+ speaking = false;
+ updateTTS();
+ }
+ }
+ }
+
+ /**
+ * Adds an utterance to the queue.
+ */
+ public void speak(String text, String voice, int volume, float pitch, float rate, int utterance_id, boolean interrupt) {
+ synchronized (lock) {
+ GodotUtterance message = new GodotUtterance(text, voice, volume, pitch, rate, utterance_id);
+ queue.addLast(message);
+
+ if (isPaused()) {
+ resumeSpeaking();
+ } else {
+ updateTTS();
+ }
+ }
+ }
+
+ /**
+ * Puts the synthesizer into a paused state.
+ */
+ public void pauseSpeaking() {
+ synchronized (lock) {
+ if (!paused) {
+ paused = true;
+ synth.stop();
+ }
+ }
+ }
+
+ /**
+ * Resumes the synthesizer if it was paused.
+ */
+ public void resumeSpeaking() {
+ synchronized (lock) {
+ if (lastUtterance != null && paused) {
+ int mode = TextToSpeech.QUEUE_FLUSH;
+
+ Set<Voice> voices = synth.getVoices();
+ for (Voice v : voices) {
+ if (v.getName().equals(lastUtterance.voice)) {
+ synth.setVoice(v);
+ break;
+ }
+ }
+ synth.setPitch(lastUtterance.pitch);
+ synth.setSpeechRate(lastUtterance.rate);
+
+ Bundle params = new Bundle();
+ params.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, lastUtterance.volume / 100.f);
+
+ lastUtterance.start = lastUtterance.offset;
+ lastUtterance.offset = 0;
+ paused = false;
+
+ synth.speak(lastUtterance.text.substring(lastUtterance.start), mode, params, String.valueOf(lastUtterance.id));
+ speaking = true;
+ } else {
+ paused = false;
+ }
+ }
+ }
+
+ /**
+ * Stops synthesis in progress and removes all utterances from the queue.
+ */
+ public void stopSpeaking() {
+ synchronized (lock) {
+ for (GodotUtterance u : queue) {
+ GodotLib.ttsCallback(EVENT_CANCEL, u.id, 0);
+ }
+ queue.clear();
+
+ if (lastUtterance != null) {
+ GodotLib.ttsCallback(EVENT_CANCEL, lastUtterance.id, 0);
+ }
+ lastUtterance = null;
+
+ paused = false;
+ speaking = false;
+
+ synth.stop();
+ }
+ }
+
+ /**
+ * Returns voice information.
+ */
+ public String[] getVoices() {
+ Set<Voice> voices = synth.getVoices();
+ String[] list = new String[voices.size()];
+ int i = 0;
+ for (Voice v : voices) {
+ list[i++] = v.getLocale().toString() + ";" + v.getName();
+ }
+ return list;
+ }
+
+ /**
+ * Returns true if the synthesizer is generating speech, or have utterance waiting in the queue.
+ */
+ public boolean isSpeaking() {
+ return speaking;
+ }
+
+ /**
+ * Returns true if the synthesizer is in a paused state.
+ */
+ public boolean isPaused() {
+ return paused;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/tts/GodotUtterance.java b/platform/android/java/lib/src/org/godotengine/godot/tts/GodotUtterance.java
new file mode 100644
index 0000000000..bde37e7315
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/tts/GodotUtterance.java
@@ -0,0 +1,55 @@
+/*************************************************************************/
+/* GodotUtterance.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.tts;
+
+/**
+ * A speech request for GodotTTS.
+ */
+class GodotUtterance {
+ final String text;
+ final String voice;
+ final int volume;
+ final float pitch;
+ final float rate;
+ final int id;
+
+ int offset = -1;
+ int start = 0;
+
+ GodotUtterance(String text, String voice, int volume, float pitch, float rate, int id) {
+ this.text = text;
+ this.voice = voice;
+ this.volume = volume;
+ this.pitch = pitch;
+ this.rate = rate;
+ this.id = id;
+ }
+}
diff --git a/platform/android/java_godot_lib_jni.cpp b/platform/android/java_godot_lib_jni.cpp
index 5e0a9d967b..8ad72b499e 100644
--- a/platform/android/java_godot_lib_jni.cpp
+++ b/platform/android/java_godot_lib_jni.cpp
@@ -49,6 +49,7 @@
#include "os_android.h"
#include "string_android.h"
#include "thread_jandroid.h"
+#include "tts_android.h"
#include <android/input.h>
#include <unistd.h>
@@ -96,6 +97,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *en
DirAccessJAndroid::setup(godot_io_java->get_instance());
NetSocketAndroid::setup(godot_java->get_member_object("netUtils", "Lorg/godotengine/godot/utils/GodotNetUtils;", env));
+ TTS_Android::setup(godot_java->get_member_object("tts", "Lorg/godotengine/godot/tts/GodotTTS;", env));
os_android = new OS_Android(godot_java, godot_io_java, p_use_apk_expansion);
@@ -213,6 +215,10 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jcl
}
}
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ttsCallback(JNIEnv *env, jclass clazz, jint event, jint id, jint pos) {
+ TTS_Android::_java_utterance_callback(event, id, pos);
+}
+
JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jclass clazz) {
if (step.get() == -1) {
return true;
diff --git a/platform/android/java_godot_lib_jni.h b/platform/android/java_godot_lib_jni.h
index e686ee5c09..4f2195942c 100644
--- a/platform/android/java_godot_lib_jni.h
+++ b/platform/android/java_godot_lib_jni.h
@@ -43,6 +43,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jc
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jobject p_surface, jint p_width, jint p_height);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface);
JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jclass clazz);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ttsCallback(JNIEnv *env, jclass clazz, jint event, jint id, jint pos);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jclass clazz);
void touch_preprocessing(JNIEnv *env, jclass clazz, jint input_device, jint ev, jint pointer, jint pointer_count, jfloatArray positions, jint buttons_mask = 0, jfloat vertical_factor = 0, jfloat horizontal_factor = 0);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch__IIII_3F(JNIEnv *env, jclass clazz, jint input_device, jint ev, jint pointer, jint pointer_count, jfloatArray positions);
diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp
index 54124c22d0..fc46005b41 100644
--- a/platform/android/os_android.cpp
+++ b/platform/android/os_android.cpp
@@ -139,7 +139,7 @@ void OS_Android::finalize() {
}
OS_Android *OS_Android::get_singleton() {
- return (OS_Android *)OS::get_singleton();
+ return static_cast<OS_Android *>(OS::get_singleton());
}
GodotJavaWrapper *OS_Android::get_godot_java() {
diff --git a/platform/android/tts_android.cpp b/platform/android/tts_android.cpp
new file mode 100644
index 0000000000..528878f14e
--- /dev/null
+++ b/platform/android/tts_android.cpp
@@ -0,0 +1,189 @@
+/*************************************************************************/
+/* tts_android.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tts_android.h"
+
+#include "java_godot_wrapper.h"
+#include "os_android.h"
+#include "string_android.h"
+#include "thread_jandroid.h"
+
+jobject TTS_Android::tts = 0;
+jclass TTS_Android::cls = 0;
+
+jmethodID TTS_Android::_is_speaking = 0;
+jmethodID TTS_Android::_is_paused = 0;
+jmethodID TTS_Android::_get_voices = 0;
+jmethodID TTS_Android::_speak = 0;
+jmethodID TTS_Android::_pause_speaking = 0;
+jmethodID TTS_Android::_resume_speaking = 0;
+jmethodID TTS_Android::_stop_speaking = 0;
+
+Map<int, Char16String> TTS_Android::ids;
+
+void TTS_Android::setup(jobject p_tts) {
+ JNIEnv *env = get_jni_env();
+
+ tts = env->NewGlobalRef(p_tts);
+
+ jclass c = env->GetObjectClass(tts);
+ cls = (jclass)env->NewGlobalRef(c);
+
+ _is_speaking = env->GetMethodID(cls, "isSpeaking", "()Z");
+ _is_paused = env->GetMethodID(cls, "isPaused", "()Z");
+ _get_voices = env->GetMethodID(cls, "getVoices", "()[Ljava/lang/String;");
+ _speak = env->GetMethodID(cls, "speak", "(Ljava/lang/String;Ljava/lang/String;IFFIZ)V");
+ _pause_speaking = env->GetMethodID(cls, "pauseSpeaking", "()V");
+ _resume_speaking = env->GetMethodID(cls, "resumeSpeaking", "()V");
+ _stop_speaking = env->GetMethodID(cls, "stopSpeaking", "()V");
+}
+
+void TTS_Android::_java_utterance_callback(int p_event, int p_id, int p_pos) {
+ if (ids.has(p_id)) {
+ int pos = 0;
+ if ((DisplayServer::TTSUtteranceEvent)p_event == DisplayServer::TTS_UTTERANCE_BOUNDARY) {
+ // Convert position from UTF-16 to UTF-32.
+ const Char16String &string = ids[p_id];
+ for (int i = 0; i < MIN(p_pos, string.length()); i++) {
+ char16_t c = string[i];
+ if ((c & 0xfffffc00) == 0xd800) {
+ i++;
+ }
+ pos++;
+ }
+ } else if ((DisplayServer::TTSUtteranceEvent)p_event != DisplayServer::TTS_UTTERANCE_STARTED) {
+ ids.erase(p_id);
+ }
+ DisplayServer::get_singleton()->tts_post_utterance_event((DisplayServer::TTSUtteranceEvent)p_event, p_id, pos);
+ }
+}
+
+bool TTS_Android::is_speaking() {
+ if (_is_speaking) {
+ JNIEnv *env = get_jni_env();
+
+ ERR_FAIL_COND_V(env == nullptr, false);
+ return env->CallBooleanMethod(tts, _is_speaking);
+ } else {
+ return false;
+ }
+}
+
+bool TTS_Android::is_paused() {
+ if (_is_paused) {
+ JNIEnv *env = get_jni_env();
+
+ ERR_FAIL_COND_V(env == nullptr, false);
+ return env->CallBooleanMethod(tts, _is_paused);
+ } else {
+ return false;
+ }
+}
+
+Array TTS_Android::get_voices() {
+ Array list;
+ if (_get_voices) {
+ JNIEnv *env = get_jni_env();
+ ERR_FAIL_COND_V(env == nullptr, list);
+
+ jobject voices_object = env->CallObjectMethod(tts, _get_voices);
+ jobjectArray *arr = reinterpret_cast<jobjectArray *>(&voices_object);
+
+ jsize len = env->GetArrayLength(*arr);
+ for (int i = 0; i < len; i++) {
+ jstring jStr = (jstring)env->GetObjectArrayElement(*arr, i);
+ String str = jstring_to_string(jStr, env);
+ Vector<String> tokens = str.split(";", true, 2);
+ if (tokens.size() == 2) {
+ Dictionary voice_d;
+ voice_d["name"] = tokens[1];
+ voice_d["id"] = tokens[1];
+ voice_d["language"] = tokens[0];
+ list.push_back(voice_d);
+ }
+ env->DeleteLocalRef(jStr);
+ }
+ }
+ return list;
+}
+
+void TTS_Android::speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ if (p_interrupt) {
+ stop();
+ }
+
+ if (p_text.is_empty()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
+ return;
+ }
+
+ ids[p_utterance_id] = p_text.utf16();
+
+ if (_speak) {
+ JNIEnv *env = get_jni_env();
+ ERR_FAIL_COND(env == nullptr);
+
+ jstring jStrT = env->NewStringUTF(p_text.utf8().get_data());
+ jstring jStrV = env->NewStringUTF(p_voice.utf8().get_data());
+ env->CallVoidMethod(tts, _speak, jStrT, jStrV, CLAMP(p_volume, 0, 100), CLAMP(p_pitch, 0.f, 2.f), CLAMP(p_rate, 0.1f, 10.f), p_utterance_id, p_interrupt);
+ }
+}
+
+void TTS_Android::pause() {
+ if (_pause_speaking) {
+ JNIEnv *env = get_jni_env();
+
+ ERR_FAIL_COND(env == nullptr);
+ env->CallVoidMethod(tts, _pause_speaking);
+ }
+}
+
+void TTS_Android::resume() {
+ if (_resume_speaking) {
+ JNIEnv *env = get_jni_env();
+
+ ERR_FAIL_COND(env == nullptr);
+ env->CallVoidMethod(tts, _resume_speaking);
+ }
+}
+
+void TTS_Android::stop() {
+ for (Map<int, Char16String>::Element *E = ids.front(); E; E = E->next()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, E->key());
+ }
+ ids.clear();
+
+ if (_stop_speaking) {
+ JNIEnv *env = get_jni_env();
+
+ ERR_FAIL_COND(env == nullptr);
+ env->CallVoidMethod(tts, _stop_speaking);
+ }
+}
diff --git a/platform/android/tts_android.h b/platform/android/tts_android.h
new file mode 100644
index 0000000000..efeed94856
--- /dev/null
+++ b/platform/android/tts_android.h
@@ -0,0 +1,67 @@
+/*************************************************************************/
+/* tts_android.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TTS_ANDROID_H
+#define TTS_ANDROID_H
+
+#include "core/string/ustring.h"
+#include "core/variant/array.h"
+#include "servers/display_server.h"
+
+#include <jni.h>
+
+class TTS_Android {
+ static jobject tts;
+ static jclass cls;
+
+ static jmethodID _is_speaking;
+ static jmethodID _is_paused;
+ static jmethodID _get_voices;
+ static jmethodID _speak;
+ static jmethodID _pause_speaking;
+ static jmethodID _resume_speaking;
+ static jmethodID _stop_speaking;
+
+ static Map<int, Char16String> ids;
+
+public:
+ static void setup(jobject p_tts);
+ static void _java_utterance_callback(int p_event, int p_id, int p_pos);
+
+ static bool is_speaking();
+ static bool is_paused();
+ static Array get_voices();
+ static void speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt);
+ static void pause();
+ static void resume();
+ static void stop();
+};
+
+#endif // TTS_ANDROID_H
diff --git a/platform/iphone/SCsub b/platform/iphone/SCsub
index 58b574a72f..5e10bf5646 100644
--- a/platform/iphone/SCsub
+++ b/platform/iphone/SCsub
@@ -13,6 +13,7 @@ iphone_lib = [
"display_server_iphone.mm",
"joypad_iphone.mm",
"godot_view.mm",
+ "tts_ios.mm",
"display_layer.mm",
"godot_app_delegate.m",
"godot_view_renderer.mm",
diff --git a/platform/iphone/display_server_iphone.h b/platform/iphone/display_server_iphone.h
index 7441550f67..6ae190b81a 100644
--- a/platform/iphone/display_server_iphone.h
+++ b/platform/iphone/display_server_iphone.h
@@ -58,6 +58,8 @@ class DisplayServerIPhone : public DisplayServer {
RenderingDeviceVulkan *rendering_device_vulkan = nullptr;
#endif
+ id tts = nullptr;
+
DisplayServer::ScreenOrientation screen_orientation;
ObjectID window_attached_instance_id;
@@ -123,6 +125,15 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+
virtual int get_screen_count() const override;
virtual Point2i screen_get_position(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual Size2i screen_get_size(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
diff --git a/platform/iphone/display_server_iphone.mm b/platform/iphone/display_server_iphone.mm
index a0f8daf5a0..ec58ab195a 100644
--- a/platform/iphone/display_server_iphone.mm
+++ b/platform/iphone/display_server_iphone.mm
@@ -38,6 +38,7 @@
#include "ios.h"
#import "keyboard_input_view.h"
#include "os_iphone.h"
+#include "tts_ios.h"
#import "view_controller.h"
#import <Foundation/Foundation.h>
@@ -52,6 +53,9 @@ DisplayServerIPhone *DisplayServerIPhone::get_singleton() {
DisplayServerIPhone::DisplayServerIPhone(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
rendering_driver = p_rendering_driver;
+ // Init TTS
+ tts = [[TTS_IOS alloc] init];
+
#if defined(GLES3_ENABLED)
// FIXME: Add support for both OpenGL and Vulkan when OpenGL is implemented
// again,
@@ -310,6 +314,7 @@ bool DisplayServerIPhone::has_feature(Feature p_feature) const {
case FEATURE_ORIENTATION:
case FEATURE_TOUCHSCREEN:
case FEATURE_VIRTUAL_KEYBOARD:
+ case FEATURE_TEXT_TO_SPEECH:
return true;
default:
return false;
@@ -320,6 +325,41 @@ String DisplayServerIPhone::get_name() const {
return "iPhone";
}
+bool DisplayServerIPhone::tts_is_speaking() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return [tts isSpeaking];
+}
+
+bool DisplayServerIPhone::tts_is_paused() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return [tts isPaused];
+}
+
+Array DisplayServerIPhone::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, Array());
+ return [tts getVoices];
+}
+
+void DisplayServerIPhone::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ ERR_FAIL_COND(!tts);
+ [tts speak:p_text voice:p_voice volume:p_volume pitch:p_pitch rate:p_rate utterance_id:p_utterance_id interrupt:p_interrupt];
+}
+
+void DisplayServerIPhone::tts_pause() {
+ ERR_FAIL_COND(!tts);
+ [tts pauseSpeaking];
+}
+
+void DisplayServerIPhone::tts_resume() {
+ ERR_FAIL_COND(!tts);
+ [tts resumeSpeaking];
+}
+
+void DisplayServerIPhone::tts_stop() {
+ ERR_FAIL_COND(!tts);
+ [tts stopSpeaking];
+}
+
int DisplayServerIPhone::get_screen_count() const {
return 1;
}
diff --git a/platform/iphone/ios.h b/platform/iphone/ios.h
index 03e663b05c..0607d7b395 100644
--- a/platform/iphone/ios.h
+++ b/platform/iphone/ios.h
@@ -32,15 +32,26 @@
#define IOS_H
#include "core/object/class_db.h"
+#import <CoreHaptics/CoreHaptics.h>
class iOS : public Object {
GDCLASS(iOS, Object);
static void _bind_methods();
+private:
+ CHHapticEngine *haptic_engine API_AVAILABLE(ios(13)) = nullptr;
+
+ CHHapticEngine *get_haptic_engine_instance() API_AVAILABLE(ios(13));
+ void start_haptic_engine();
+ void stop_haptic_engine();
+
public:
static void alert(const char *p_alert, const char *p_title);
+ bool supports_haptic_engine();
+ void vibrate_haptic_engine(float p_duration_seconds);
+
String get_model() const;
String get_rate_url(int p_app_id) const;
diff --git a/platform/iphone/ios.mm b/platform/iphone/ios.mm
index ad1ea70c10..cca28cc055 100644
--- a/platform/iphone/ios.mm
+++ b/platform/iphone/ios.mm
@@ -32,11 +32,110 @@
#import "app_delegate.h"
#import "view_controller.h"
+
+#import <CoreHaptics/CoreHaptics.h>
#import <UIKit/UIKit.h>
#include <sys/sysctl.h>
void iOS::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_rate_url", "app_id"), &iOS::get_rate_url);
+ ClassDB::bind_method(D_METHOD("supports_haptic_engine"), &iOS::supports_haptic_engine);
+ ClassDB::bind_method(D_METHOD("start_haptic_engine"), &iOS::start_haptic_engine);
+ ClassDB::bind_method(D_METHOD("stop_haptic_engine"), &iOS::stop_haptic_engine);
+};
+
+bool iOS::supports_haptic_engine() {
+ if (@available(iOS 13, *)) {
+ id<CHHapticDeviceCapability> capabilities = [CHHapticEngine capabilitiesForHardware];
+ return capabilities.supportsHaptics;
+ }
+
+ return false;
+}
+
+CHHapticEngine *iOS::get_haptic_engine_instance() API_AVAILABLE(ios(13)) {
+ if (haptic_engine == nullptr) {
+ NSError *error = nullptr;
+ haptic_engine = [[CHHapticEngine alloc] initAndReturnError:&error];
+
+ if (!error) {
+ [haptic_engine setAutoShutdownEnabled:true];
+ } else {
+ haptic_engine = nullptr;
+ NSLog(@"Could not initialize haptic engine: %@", error);
+ }
+ }
+
+ return haptic_engine;
+}
+
+void iOS::vibrate_haptic_engine(float p_duration_seconds) API_AVAILABLE(ios(13)) {
+ if (@available(iOS 13, *)) { // We need the @available check every time to make the compiler happy...
+ if (supports_haptic_engine()) {
+ CHHapticEngine *haptic_engine = get_haptic_engine_instance();
+ if (haptic_engine) {
+ NSDictionary *hapticDict = @{
+ CHHapticPatternKeyPattern : @[
+ @{CHHapticPatternKeyEvent : @{
+ CHHapticPatternKeyEventType : CHHapticEventTypeHapticTransient,
+ CHHapticPatternKeyTime : @(CHHapticTimeImmediate),
+ CHHapticPatternKeyEventDuration : @(p_duration_seconds)
+ },
+ },
+ ],
+ };
+
+ NSError *error;
+ CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithDictionary:hapticDict error:&error];
+
+ [[haptic_engine createPlayerWithPattern:pattern error:&error] startAtTime:0 error:&error];
+
+ NSLog(@"Could not vibrate using haptic engine: %@", error);
+ }
+
+ return;
+ }
+ }
+
+ NSLog(@"Haptic engine is not supported in this version of iOS");
+}
+
+void iOS::start_haptic_engine() {
+ if (@available(iOS 13, *)) {
+ if (supports_haptic_engine()) {
+ CHHapticEngine *haptic_engine = get_haptic_engine_instance();
+ if (haptic_engine) {
+ [haptic_engine startWithCompletionHandler:^(NSError *returnedError) {
+ if (returnedError) {
+ NSLog(@"Could not start haptic engine: %@", returnedError);
+ }
+ }];
+ }
+
+ return;
+ }
+ }
+
+ NSLog(@"Haptic engine is not supported in this version of iOS");
+}
+
+void iOS::stop_haptic_engine() {
+ if (@available(iOS 13, *)) {
+ if (supports_haptic_engine()) {
+ CHHapticEngine *haptic_engine = get_haptic_engine_instance();
+ if (haptic_engine) {
+ [haptic_engine stopWithCompletionHandler:^(NSError *returnedError) {
+ if (returnedError) {
+ NSLog(@"Could not stop haptic engine: %@", returnedError);
+ }
+ }];
+ }
+
+ return;
+ }
+ }
+
+ NSLog(@"Haptic engine is not supported in this version of iOS");
}
void iOS::alert(const char *p_alert, const char *p_title) {
diff --git a/platform/iphone/os_iphone.mm b/platform/iphone/os_iphone.mm
index ea1bc0ef64..f7974c4b3d 100644
--- a/platform/iphone/os_iphone.mm
+++ b/platform/iphone/os_iphone.mm
@@ -298,8 +298,12 @@ String OSIPhone::get_processor_name() const {
}
void OSIPhone::vibrate_handheld(int p_duration_ms) {
- // iOS does not support duration for vibration
- AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
+ if (ios->supports_haptic_engine()) {
+ ios->vibrate_haptic_engine((float)p_duration_ms / 1000.f);
+ } else {
+ // iOS <13 does not support duration for vibration
+ AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
+ }
}
bool OSIPhone::_check_internal_feature_support(const String &p_feature) {
diff --git a/platform/iphone/tts_ios.h b/platform/iphone/tts_ios.h
new file mode 100644
index 0000000000..c7defeb98f
--- /dev/null
+++ b/platform/iphone/tts_ios.h
@@ -0,0 +1,59 @@
+/*************************************************************************/
+/* tts_ios.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TTS_IOS_H
+#define TTS_IOS_H
+
+#include <AVFAudio/AVSpeechSynthesis.h>
+
+#include "core/string/ustring.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/variant/array.h"
+#include "servers/display_server.h"
+
+@interface TTS_IOS : NSObject <AVSpeechSynthesizerDelegate> {
+ bool speaking;
+ Map<id, int> ids;
+
+ AVSpeechSynthesizer *av_synth;
+ List<DisplayServer::TTSUtterance> queue;
+}
+
+- (void)pauseSpeaking;
+- (void)resumeSpeaking;
+- (void)stopSpeaking;
+- (bool)isSpeaking;
+- (bool)isPaused;
+- (void)speak:(const String &)text voice:(const String &)voice volume:(int)volume pitch:(float)pitch rate:(float)rate utterance_id:(int)utterance_id interrupt:(bool)interrupt;
+- (Array)getVoices;
+@end
+
+#endif // TTS_IOS_H
diff --git a/platform/iphone/tts_ios.mm b/platform/iphone/tts_ios.mm
new file mode 100644
index 0000000000..a079d02add
--- /dev/null
+++ b/platform/iphone/tts_ios.mm
@@ -0,0 +1,164 @@
+/*************************************************************************/
+/* tts_ios.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tts_ios.h"
+
+@implementation TTS_IOS
+
+- (id)init {
+ self = [super init];
+ self->speaking = false;
+ self->av_synth = [[AVSpeechSynthesizer alloc] init];
+ [self->av_synth setDelegate:self];
+ print_verbose("Text-to-Speech: AVSpeechSynthesizer initialized.");
+ return self;
+}
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance {
+ NSString *string = [utterance speechString];
+
+ // Convert from UTF-16 to UTF-32 position.
+ int pos = 0;
+ for (NSUInteger i = 0; i < MIN(characterRange.location, string.length); i++) {
+ unichar c = [string characterAtIndex:i];
+ if ((c & 0xfffffc00) == 0xd800) {
+ i++;
+ }
+ pos++;
+ }
+
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, ids[utterance], pos);
+}
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didCancelSpeechUtterance:(AVSpeechUtterance *)utterance {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[utterance]);
+ ids.erase(utterance);
+ speaking = false;
+ [self update];
+}
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, ids[utterance]);
+ ids.erase(utterance);
+ speaking = false;
+ [self update];
+}
+
+- (void)update {
+ if (!speaking && queue.size() > 0) {
+ DisplayServer::TTSUtterance &message = queue.front()->get();
+
+ AVSpeechUtterance *new_utterance = [[AVSpeechUtterance alloc] initWithString:[NSString stringWithUTF8String:message.text.utf8().get_data()]];
+ [new_utterance setVoice:[AVSpeechSynthesisVoice voiceWithIdentifier:[NSString stringWithUTF8String:message.voice.utf8().get_data()]]];
+ if (message.rate > 1.f) {
+ [new_utterance setRate:Math::range_lerp(message.rate, 1.f, 10.f, AVSpeechUtteranceDefaultSpeechRate, AVSpeechUtteranceMaximumSpeechRate)];
+ } else if (message.rate < 1.f) {
+ [new_utterance setRate:Math::range_lerp(message.rate, 0.1f, 1.f, AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceDefaultSpeechRate)];
+ }
+ [new_utterance setPitchMultiplier:message.pitch];
+ [new_utterance setVolume:(Math::range_lerp(message.volume, 0.f, 100.f, 0.f, 1.f))];
+
+ ids[new_utterance] = message.id;
+ [av_synth speakUtterance:new_utterance];
+
+ queue.pop_front();
+
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, message.id);
+ speaking = true;
+ }
+}
+
+- (void)pauseSpeaking {
+ [av_synth pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
+}
+
+- (void)resumeSpeaking {
+ [av_synth continueSpeaking];
+}
+
+- (void)stopSpeaking {
+ for (DisplayServer::TTSUtterance &message : queue) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
+ }
+ queue.clear();
+ [av_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
+ speaking = false;
+}
+
+- (bool)isSpeaking {
+ return speaking || (queue.size() > 0);
+}
+
+- (bool)isPaused {
+ return [av_synth isPaused];
+}
+
+- (void)speak:(const String &)text voice:(const String &)voice volume:(int)volume pitch:(float)pitch rate:(float)rate utterance_id:(int)utterance_id interrupt:(bool)interrupt {
+ if (interrupt) {
+ [self stopSpeaking];
+ }
+
+ if (text.is_empty()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, utterance_id);
+ return;
+ }
+
+ DisplayServer::TTSUtterance message;
+ message.text = text;
+ message.voice = voice;
+ message.volume = CLAMP(volume, 0, 100);
+ message.pitch = CLAMP(pitch, 0.f, 2.f);
+ message.rate = CLAMP(rate, 0.1f, 10.f);
+ message.id = utterance_id;
+ queue.push_back(message);
+
+ if ([self isPaused]) {
+ [self resumeSpeaking];
+ } else {
+ [self update];
+ }
+}
+
+- (Array)getVoices {
+ Array list;
+ for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
+ NSString *voiceIdentifierString = [voice identifier];
+ NSString *voiceLocaleIdentifier = [voice language];
+ NSString *voiceName = [voice name];
+ Dictionary voice_d;
+ voice_d["name"] = String::utf8([voiceName UTF8String]);
+ voice_d["id"] = String::utf8([voiceIdentifierString UTF8String]);
+ voice_d["language"] = String::utf8([voiceLocaleIdentifier UTF8String]);
+ list.push_back(voice_d);
+ }
+ return list;
+}
+
+@end
diff --git a/platform/javascript/display_server_javascript.cpp b/platform/javascript/display_server_javascript.cpp
index a38040922d..cc77c8fcd5 100644
--- a/platform/javascript/display_server_javascript.cpp
+++ b/platform/javascript/display_server_javascript.cpp
@@ -274,6 +274,90 @@ const char *DisplayServerJavaScript::godot2dom_cursor(DisplayServer::CursorShape
}
}
+bool DisplayServerJavaScript::tts_is_speaking() const {
+ return godot_js_tts_is_speaking();
+}
+
+bool DisplayServerJavaScript::tts_is_paused() const {
+ return godot_js_tts_is_paused();
+}
+
+void DisplayServerJavaScript::update_voices_callback(int p_size, const char **p_voice) {
+ get_singleton()->voices.clear();
+ for (int i = 0; i < p_size; i++) {
+ Vector<String> tokens = String::utf8(p_voice[i]).split(";", true, 2);
+ if (tokens.size() == 2) {
+ Dictionary voice_d;
+ voice_d["name"] = tokens[1];
+ voice_d["id"] = tokens[1];
+ voice_d["language"] = tokens[0];
+ get_singleton()->voices.push_back(voice_d);
+ }
+ }
+}
+
+Array DisplayServerJavaScript::tts_get_voices() const {
+ godot_js_tts_get_voices(update_voices_callback);
+ return voices;
+}
+
+void DisplayServerJavaScript::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ if (p_interrupt) {
+ tts_stop();
+ }
+
+ if (p_text.is_empty()) {
+ tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
+ return;
+ }
+
+ CharString string = p_text.utf8();
+ utterance_ids[p_utterance_id] = string;
+
+ godot_js_tts_speak(string.get_data(), p_voice.utf8().get_data(), CLAMP(p_volume, 0, 100), CLAMP(p_pitch, 0.f, 2.f), CLAMP(p_rate, 0.1f, 10.f), p_utterance_id, DisplayServerJavaScript::_js_utterance_callback);
+}
+
+void DisplayServerJavaScript::tts_pause() {
+ godot_js_tts_pause();
+}
+
+void DisplayServerJavaScript::tts_resume() {
+ godot_js_tts_resume();
+}
+
+void DisplayServerJavaScript::tts_stop() {
+ for (Map<int, CharString>::Element *E = utterance_ids.front(); E; E = E->next()) {
+ tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, E->key());
+ }
+ utterance_ids.clear();
+ godot_js_tts_stop();
+}
+
+void DisplayServerJavaScript::_js_utterance_callback(int p_event, int p_id, int p_pos) {
+ DisplayServerJavaScript *ds = (DisplayServerJavaScript *)DisplayServer::get_singleton();
+ if (ds->utterance_ids.has(p_id)) {
+ int pos = 0;
+ if ((TTSUtteranceEvent)p_event == DisplayServer::TTS_UTTERANCE_BOUNDARY) {
+ // Convert position from UTF-8 to UTF-32.
+ const CharString &string = ds->utterance_ids[p_id];
+ for (int i = 0; i < MIN(p_pos, string.length()); i++) {
+ uint8_t c = string[i];
+ if ((c & 0xe0) == 0xc0) {
+ i += 1;
+ } else if ((c & 0xf0) == 0xe0) {
+ i += 2;
+ } else if ((c & 0xf8) == 0xf0) {
+ i += 3;
+ }
+ pos++;
+ }
+ } else if ((TTSUtteranceEvent)p_event != DisplayServer::TTS_UTTERANCE_STARTED) {
+ ds->utterance_ids.erase(p_id);
+ }
+ ds->tts_post_utterance_event((TTSUtteranceEvent)p_event, p_id, pos);
+ }
+}
+
void DisplayServerJavaScript::cursor_set_shape(CursorShape p_shape) {
ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
if (cursor_shape == p_shape) {
@@ -755,6 +839,8 @@ bool DisplayServerJavaScript::has_feature(Feature p_feature) const {
//case FEATURE_ORIENTATION:
case FEATURE_VIRTUAL_KEYBOARD:
return godot_js_display_vk_available() != 0;
+ case FEATURE_TEXT_TO_SPEECH:
+ return godot_js_display_tts_available() != 0;
default:
return false;
}
diff --git a/platform/javascript/display_server_javascript.h b/platform/javascript/display_server_javascript.h
index b50956d91c..bbd0206087 100644
--- a/platform/javascript/display_server_javascript.h
+++ b/platform/javascript/display_server_javascript.h
@@ -55,6 +55,8 @@ private:
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webgl_ctx = 0;
#endif
+ Map<int, CharString> utterance_ids;
+
WindowMode window_mode = WINDOW_MODE_WINDOWED;
ObjectID window_attached_instance_id = {};
@@ -66,6 +68,8 @@ private:
String clipboard;
Point2 touches[32];
+ Array voices;
+
char canvas_id[256] = { 0 };
bool cursor_inside_canvas = true;
CursorShape cursor_shape = CURSOR_ARROW;
@@ -89,6 +93,7 @@ private:
static void vk_input_text_callback(const char *p_text, int p_cursor);
static void gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid);
void process_joypads();
+ static void _js_utterance_callback(int p_event, int p_id, int p_pos);
static Vector<String> get_rendering_drivers_func();
static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
@@ -97,6 +102,7 @@ private:
static void request_quit_callback();
static void window_blur_callback();
+ static void update_voices_callback(int p_size, const char **p_voice);
static void update_clipboard_callback(const char *p_text);
static void send_window_event_callback(int p_notification);
static void drop_files_js_callback(char **p_filev, int p_filec);
@@ -115,6 +121,16 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
+ // tts
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+
// cursor
virtual void cursor_set_shape(CursorShape p_shape) override;
virtual CursorShape cursor_get_shape() const override;
diff --git a/platform/javascript/godot_js.h b/platform/javascript/godot_js.h
index 2cb5c3025c..1a383c9799 100644
--- a/platform/javascript/godot_js.h
+++ b/platform/javascript/godot_js.h
@@ -67,6 +67,15 @@ extern int godot_js_input_gamepad_sample_get(int p_idx, float r_btns[16], int32_
extern void godot_js_input_paste_cb(void (*p_callback)(const char *p_text));
extern void godot_js_input_drop_files_cb(void (*p_callback)(char **p_filev, int p_filec));
+// TTS
+extern int godot_js_tts_is_speaking();
+extern int godot_js_tts_is_paused();
+extern int godot_js_tts_get_voices(void (*p_callback)(int p_size, const char **p_voices));
+extern void godot_js_tts_speak(const char *p_text, const char *p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, void (*p_callback)(int p_event, int p_id, int p_pos));
+extern void godot_js_tts_pause();
+extern void godot_js_tts_resume();
+extern void godot_js_tts_stop();
+
// Display
extern int godot_js_display_screen_dpi_get();
extern double godot_js_display_pixel_ratio_get();
@@ -109,6 +118,7 @@ extern void godot_js_display_notification_cb(void (*p_callback)(int p_notificati
// Display Virtual Keyboard
extern int godot_js_display_vk_available();
+extern int godot_js_display_tts_available();
extern void godot_js_display_vk_cb(void (*p_input)(const char *p_text, int p_cursor));
extern void godot_js_display_vk_show(const char *p_text, int p_multiline, int p_start, int p_end);
extern void godot_js_display_vk_hide();
diff --git a/platform/javascript/javascript_singleton.cpp b/platform/javascript/javascript_singleton.cpp
index c9c4d6e1b9..8dc7aba5f8 100644
--- a/platform/javascript/javascript_singleton.cpp
+++ b/platform/javascript/javascript_singleton.cpp
@@ -207,7 +207,7 @@ int JavaScriptObjectImpl::_variant2js(const void **p_args, int p_pos, godot_js_w
break;
case Variant::INT: {
const int64_t tmp = v->operator int64_t();
- if (tmp >= 1 << 31) {
+ if (tmp >= 1LL << 31) {
r_val->r = (double)tmp;
return Variant::FLOAT;
}
diff --git a/platform/javascript/js/libs/library_godot_display.js b/platform/javascript/js/libs/library_godot_display.js
index 2bdf4e56ad..54d48643db 100644
--- a/platform/javascript/js/libs/library_godot_display.js
+++ b/platform/javascript/js/libs/library_godot_display.js
@@ -330,6 +330,91 @@ const GodotDisplay = {
return 0;
},
+ godot_js_tts_is_speaking__sig: 'i',
+ godot_js_tts_is_speaking: function () {
+ return window.speechSynthesis.speaking;
+ },
+
+ godot_js_tts_is_paused__sig: 'i',
+ godot_js_tts_is_paused: function () {
+ return window.speechSynthesis.paused;
+ },
+
+ godot_js_tts_get_voices__sig: 'vi',
+ godot_js_tts_get_voices: function (p_callback) {
+ const func = GodotRuntime.get_func(p_callback);
+ try {
+ const arr = [];
+ const voices = window.speechSynthesis.getVoices();
+ for (let i = 0; i < voices.length; i++) {
+ arr.push(`${voices[i].lang};${voices[i].name}`);
+ }
+ const c_ptr = GodotRuntime.allocStringArray(arr);
+ func(arr.length, c_ptr);
+ GodotRuntime.freeStringArray(c_ptr, arr.length);
+ } catch (e) {
+ // Fail graciously.
+ }
+ },
+
+ godot_js_tts_speak__sig: 'viiiffii',
+ godot_js_tts_speak: function (p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_callback) {
+ const func = GodotRuntime.get_func(p_callback);
+
+ function listener_end(evt) {
+ evt.currentTarget.cb(1 /*TTS_UTTERANCE_ENDED*/, evt.currentTarget.id, 0);
+ }
+
+ function listener_start(evt) {
+ evt.currentTarget.cb(0 /*TTS_UTTERANCE_STARTED*/, evt.currentTarget.id, 0);
+ }
+
+ function listener_error(evt) {
+ evt.currentTarget.cb(2 /*TTS_UTTERANCE_CANCELED*/, evt.currentTarget.id, 0);
+ }
+
+ function listener_bound(evt) {
+ evt.currentTarget.cb(3 /*TTS_UTTERANCE_BOUNDARY*/, evt.currentTarget.id, evt.charIndex);
+ }
+
+ const utterance = new SpeechSynthesisUtterance(GodotRuntime.parseString(p_text));
+ utterance.rate = p_rate;
+ utterance.pitch = p_pitch;
+ utterance.volume = p_volume / 100.0;
+ utterance.addEventListener('end', listener_end);
+ utterance.addEventListener('start', listener_start);
+ utterance.addEventListener('error', listener_error);
+ utterance.addEventListener('boundary', listener_bound);
+ utterance.id = p_utterance_id;
+ utterance.cb = func;
+ const voice = GodotRuntime.parseString(p_voice);
+ const voices = window.speechSynthesis.getVoices();
+ for (let i = 0; i < voices.length; i++) {
+ if (voices[i].name === voice) {
+ utterance.voice = voices[i];
+ break;
+ }
+ }
+ window.speechSynthesis.resume();
+ window.speechSynthesis.speak(utterance);
+ },
+
+ godot_js_tts_pause__sig: 'v',
+ godot_js_tts_pause: function () {
+ window.speechSynthesis.pause();
+ },
+
+ godot_js_tts_resume__sig: 'v',
+ godot_js_tts_resume: function () {
+ window.speechSynthesis.resume();
+ },
+
+ godot_js_tts_stop__sig: 'v',
+ godot_js_tts_stop: function () {
+ window.speechSynthesis.cancel();
+ window.speechSynthesis.resume();
+ },
+
godot_js_display_alert__sig: 'vi',
godot_js_display_alert: function (p_text) {
window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
@@ -625,6 +710,11 @@ const GodotDisplay = {
return GodotDisplayVK.available();
},
+ godot_js_display_tts_available__sig: 'i',
+ godot_js_display_tts_available: function () {
+ return 'speechSynthesis' in window;
+ },
+
godot_js_display_vk_cb__sig: 'vi',
godot_js_display_vk_cb: function (p_input_cb) {
const input_cb = GodotRuntime.get_func(p_input_cb);
diff --git a/platform/linuxbsd/SCsub b/platform/linuxbsd/SCsub
index cec8706fbc..09a432eae2 100644
--- a/platform/linuxbsd/SCsub
+++ b/platform/linuxbsd/SCsub
@@ -20,6 +20,9 @@ if "x11" in env and env["x11"]:
"key_mapping_x11.cpp",
]
+if "speechd" in env and env["speechd"]:
+ common_linuxbsd.append(["speechd-so_wrap.c", "tts_linux.cpp"])
+
if "vulkan" in env and env["vulkan"]:
common_linuxbsd.append("vulkan_context_x11.cpp")
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index 39f9b99108..19cf341c85 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -75,6 +75,7 @@ def get_opts():
BoolVariable("use_msan", "Use LLVM compiler memory sanitizer (MSAN)", False),
BoolVariable("pulseaudio", "Detect and use PulseAudio", True),
BoolVariable("dbus", "Detect and use D-Bus to handle screensaver", True),
+ BoolVariable("speechd", "Detect and use Speech Dispatcher for Text-to-Speech support", True),
BoolVariable("udev", "Use udev for gamepad connection callbacks", True),
BoolVariable("x11", "Enable X11 display", True),
BoolVariable("debug_symbols", "Add debugging symbols to release/release_debug builds", True),
@@ -319,29 +320,41 @@ def configure(env):
if os.system("pkg-config --exists alsa") == 0: # 0 means found
env["alsa"] = True
env.Append(CPPDEFINES=["ALSA_ENABLED", "ALSAMIDI_ENABLED"])
+ env.ParseConfig("pkg-config alsa --cflags") # Only cflags, we dlopen the library.
else:
print("Warning: ALSA libraries not found. Disabling the ALSA audio driver.")
if env["pulseaudio"]:
if os.system("pkg-config --exists libpulse") == 0: # 0 means found
env.Append(CPPDEFINES=["PULSEAUDIO_ENABLED"])
- env.ParseConfig("pkg-config --cflags libpulse")
+ env.ParseConfig("pkg-config libpulse --cflags") # Only cflags, we dlopen the library.
else:
+ env["pulseaudio"] = False
print("Warning: PulseAudio development libraries not found. Disabling the PulseAudio audio driver.")
if env["dbus"]:
if os.system("pkg-config --exists dbus-1") == 0: # 0 means found
env.Append(CPPDEFINES=["DBUS_ENABLED"])
- env.ParseConfig("pkg-config --cflags --libs dbus-1")
+ env.ParseConfig("pkg-config dbus-1 --cflags --libs")
else:
print("Warning: D-Bus development libraries not found. Disabling screensaver prevention.")
+ if env["speechd"]:
+ if os.system("pkg-config --exists speech-dispatcher") == 0: # 0 means found
+ env.Append(CPPDEFINES=["SPEECHD_ENABLED"])
+ env.ParseConfig("pkg-config speech-dispatcher --cflags") # Only cflags, we dlopen the library.
+ else:
+ env["speechd"] = False
+ print("Warning: Speech Dispatcher development libraries not found. Disabling Text-to-Speech support.")
+
if platform.system() == "Linux":
env.Append(CPPDEFINES=["JOYDEV_ENABLED"])
if env["udev"]:
if os.system("pkg-config --exists libudev") == 0: # 0 means found
env.Append(CPPDEFINES=["UDEV_ENABLED"])
+ env.ParseConfig("pkg-config libudev --cflags") # Only cflags, we dlopen the library.
else:
+ env["udev"] = False
print("Warning: libudev development libraries not found. Disabling controller hotplugging support.")
else:
env["udev"] = False # Linux specific
@@ -366,11 +379,11 @@ def configure(env):
if not env["use_volk"]:
env.ParseConfig("pkg-config vulkan --cflags --libs")
if not env["builtin_glslang"]:
- # No pkgconfig file for glslang so far
+ # No pkgconfig file so far, hardcode expected lib name.
env.Append(LIBS=["glslang", "SPIRV"])
env.Append(CPPDEFINES=["GLES3_ENABLED"])
- env.Append(LIBS=["GL"])
+ env.ParseConfig("pkg-config gl --cflags --libs")
env.Append(LIBS=["pthread"])
diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp
index 7da30ac363..027f8562eb 100644
--- a/platform/linuxbsd/display_server_x11.cpp
+++ b/platform/linuxbsd/display_server_x11.cpp
@@ -139,6 +139,7 @@ bool DisplayServerX11::has_feature(Feature p_feature) const {
case FEATURE_KEEP_SCREEN_ON:
#endif
case FEATURE_CLIPBOARD_PRIMARY:
+ case FEATURE_TEXT_TO_SPEECH:
return true;
default: {
}
@@ -307,6 +308,45 @@ void DisplayServerX11::_flush_mouse_motion() {
xi.relative_motion.y = 0;
}
+#ifdef SPEECHD_ENABLED
+
+bool DisplayServerX11::tts_is_speaking() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return tts->is_speaking();
+}
+
+bool DisplayServerX11::tts_is_paused() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return tts->is_paused();
+}
+
+Array DisplayServerX11::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, Array());
+ return tts->get_voices();
+}
+
+void DisplayServerX11::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ ERR_FAIL_COND(!tts);
+ tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
+}
+
+void DisplayServerX11::tts_pause() {
+ ERR_FAIL_COND(!tts);
+ tts->pause();
+}
+
+void DisplayServerX11::tts_resume() {
+ ERR_FAIL_COND(!tts);
+ tts->resume();
+}
+
+void DisplayServerX11::tts_stop() {
+ ERR_FAIL_COND(!tts);
+ tts->stop();
+}
+
+#endif
+
void DisplayServerX11::mouse_set_mode(MouseMode p_mode) {
_THREAD_SAFE_METHOD_
@@ -670,17 +710,17 @@ void DisplayServerX11::_clipboard_transfer_ownership(Atom p_source, Window x11_w
int DisplayServerX11::get_screen_count() const {
_THREAD_SAFE_METHOD_
+ int count = 0;
// Using Xinerama Extension
int event_base, error_base;
- const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
- if (!ext_okay) {
- return 0;
+ if (XineramaQueryExtension(x11_display, &event_base, &error_base)) {
+ XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
+ XFree(xsi);
+ } else {
+ count = XScreenCount(x11_display);
}
- int count;
- XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
- XFree(xsi);
return count;
}
@@ -712,6 +752,19 @@ Rect2i DisplayServerX11::_screen_get_rect(int p_screen) const {
if (xsi) {
XFree(xsi);
}
+ } else {
+ int count = XScreenCount(x11_display);
+ if (p_screen < count) {
+ Window root = XRootWindow(x11_display, p_screen);
+ XWindowAttributes xwa;
+ XGetWindowAttributes(x11_display, root, &xwa);
+ rect.position.x = xwa.x;
+ rect.position.y = xwa.y;
+ rect.size.width = xwa.width;
+ rect.size.height = xwa.height;
+ } else {
+ ERR_PRINT("Invalid screen index: " + itos(p_screen) + "(count: " + itos(count) + ").");
+ }
}
return rect;
@@ -2130,7 +2183,7 @@ bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) co
unsigned char *data = nullptr;
if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
if (data && (format == 32) && (len >= 5)) {
- borderless = !((Hints *)data)->decorations;
+ borderless = !(reinterpret_cast<Hints *>(data)->decorations);
}
if (data) {
XFree(data);
@@ -2162,7 +2215,7 @@ void DisplayServerX11::window_request_attention(WindowID p_window) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
+ const WindowData &wd = windows[p_window];
// Using EWMH -- Extended Window Manager Hints
//
// Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
@@ -2188,7 +2241,7 @@ void DisplayServerX11::window_move_to_foreground(WindowID p_window) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
+ const WindowData &wd = windows[p_window];
XEvent xev;
Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
@@ -2534,10 +2587,9 @@ DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display,
unsigned long bytes_after = 0;
unsigned char *ret = nullptr;
- int read_bytes = 1024;
-
// Keep trying to read the property until there are no bytes unread.
if (p_property != None) {
+ int read_bytes = 1024;
do {
if (ret != nullptr) {
XFree(ret);
@@ -2557,7 +2609,7 @@ DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display,
return p;
}
-static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) {
+static Atom pick_target_from_list(Display *p_display, const Atom *p_list, int p_count) {
static const char *target_type = "text/uri-list";
for (int i = 0; i < p_count; i++) {
@@ -4621,6 +4673,11 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode
xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
+#ifdef SPEECHD_ENABLED
+ // Init TTS
+ tts = memnew(TTS_Linux);
+#endif
+
//!!!!!!!!!!!!!!!!!!!!!!!!!!
//TODO - do Vulkan and OpenGL support checks, driver selection and fallback
rendering_driver = p_rendering_driver;
@@ -4973,6 +5030,10 @@ DisplayServerX11::~DisplayServerX11() {
memfree(xmbstring);
}
+#ifdef SPEECHD_ENABLED
+ memdelete(tts);
+#endif
+
#ifdef DBUS_ENABLED
memdelete(screensaver);
#endif
diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h
index cd673d94d9..3d49886b94 100644
--- a/platform/linuxbsd/display_server_x11.h
+++ b/platform/linuxbsd/display_server_x11.h
@@ -46,6 +46,10 @@
#include "servers/rendering/renderer_compositor.h"
#include "servers/rendering_server.h"
+#if defined(SPEECHD_ENABLED)
+#include "tts_linux.h"
+#endif
+
#if defined(GLES3_ENABLED)
#include "gl_manager_x11.h"
#endif
@@ -112,6 +116,10 @@ class DisplayServerX11 : public DisplayServer {
bool keep_screen_on = false;
#endif
+#ifdef SPEECHD_ENABLED
+ TTS_Linux *tts = nullptr;
+#endif
+
struct WindowData {
Window x11_window;
::XIC xic;
@@ -298,6 +306,17 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
+#ifdef SPEECHD_ENABLED
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+#endif
+
virtual void mouse_set_mode(MouseMode p_mode) override;
virtual MouseMode mouse_get_mode() const override;
diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp
index bf142f8804..b73d4dc626 100644
--- a/platform/linuxbsd/os_linuxbsd.cpp
+++ b/platform/linuxbsd/os_linuxbsd.cpp
@@ -242,6 +242,91 @@ bool OS_LinuxBSD::_check_internal_feature_support(const String &p_feature) {
return p_feature == "pc";
}
+uint64_t OS_LinuxBSD::get_embedded_pck_offset() const {
+ Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
+ if (f.is_null()) {
+ return 0;
+ }
+
+ // Read and check ELF magic number.
+ {
+ uint32_t magic = f->get_32();
+ if (magic != 0x464c457f) { // 0x7F + "ELF"
+ return 0;
+ }
+ }
+
+ // Read program architecture bits from class field.
+ int bits = f->get_8() * 32;
+
+ // Get info about the section header table.
+ int64_t section_table_pos;
+ int64_t section_header_size;
+ if (bits == 32) {
+ section_header_size = 40;
+ f->seek(0x20);
+ section_table_pos = f->get_32();
+ f->seek(0x30);
+ } else { // 64
+ section_header_size = 64;
+ f->seek(0x28);
+ section_table_pos = f->get_64();
+ f->seek(0x3c);
+ }
+ int num_sections = f->get_16();
+ int string_section_idx = f->get_16();
+
+ // Load the strings table.
+ uint8_t *strings;
+ {
+ // Jump to the strings section header.
+ f->seek(section_table_pos + string_section_idx * section_header_size);
+
+ // Read strings data size and offset.
+ int64_t string_data_pos;
+ int64_t string_data_size;
+ if (bits == 32) {
+ f->seek(f->get_position() + 0x10);
+ string_data_pos = f->get_32();
+ string_data_size = f->get_32();
+ } else { // 64
+ f->seek(f->get_position() + 0x18);
+ string_data_pos = f->get_64();
+ string_data_size = f->get_64();
+ }
+
+ // Read strings data.
+ f->seek(string_data_pos);
+ strings = (uint8_t *)memalloc(string_data_size);
+ if (!strings) {
+ return 0;
+ }
+ f->get_buffer(strings, string_data_size);
+ }
+
+ // Search for the "pck" section.
+ int64_t off = 0;
+ for (int i = 0; i < num_sections; ++i) {
+ int64_t section_header_pos = section_table_pos + i * section_header_size;
+ f->seek(section_header_pos);
+
+ uint32_t name_offset = f->get_32();
+ if (strcmp((char *)strings + name_offset, "pck") == 0) {
+ if (bits == 32) {
+ f->seek(section_header_pos + 0x10);
+ off = f->get_32();
+ } else { // 64
+ f->seek(section_header_pos + 0x18);
+ off = f->get_64();
+ }
+ break;
+ }
+ }
+ memfree(strings);
+
+ return off;
+}
+
String OS_LinuxBSD::get_config_path() const {
if (has_environment("XDG_CONFIG_HOME")) {
if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h
index 7b912ddee3..3f97b86eae 100644
--- a/platform/linuxbsd/os_linuxbsd.h
+++ b/platform/linuxbsd/os_linuxbsd.h
@@ -78,6 +78,8 @@ public:
virtual MainLoop *get_main_loop() const override;
+ virtual uint64_t get_embedded_pck_offset() const override;
+
virtual String get_config_path() const override;
virtual String get_data_path() const override;
virtual String get_cache_path() const override;
diff --git a/platform/linuxbsd/speechd-so_wrap.c b/platform/linuxbsd/speechd-so_wrap.c
new file mode 100644
index 0000000000..749474e181
--- /dev/null
+++ b/platform/linuxbsd/speechd-so_wrap.c
@@ -0,0 +1,881 @@
+// This file is generated. Do not edit!
+// see https://github.com/hpvb/dynload-wrapper for details
+// generated by ./dynload-wrapper/generate-wrapper.py 0.3 on 2022-04-28 14:34:21
+// flags: ./dynload-wrapper/generate-wrapper.py --sys-include <libspeechd.h> --include /usr/include/speech-dispatcher/libspeechd.h --soname libspeechd.so.2 --init-name speechd --omit-prefix spd_get_client_list --output-header speechd-so_wrap.h --output-implementation speechd-so_wrap.c
+//
+#include <stdint.h>
+
+#define SPDConnectionAddress__free SPDConnectionAddress__free_dylibloader_orig_speechd
+#define spd_get_default_address spd_get_default_address_dylibloader_orig_speechd
+#define spd_open spd_open_dylibloader_orig_speechd
+#define spd_open2 spd_open2_dylibloader_orig_speechd
+#define spd_close spd_close_dylibloader_orig_speechd
+#define spd_say spd_say_dylibloader_orig_speechd
+#define spd_sayf spd_sayf_dylibloader_orig_speechd
+#define spd_stop spd_stop_dylibloader_orig_speechd
+#define spd_stop_all spd_stop_all_dylibloader_orig_speechd
+#define spd_stop_uid spd_stop_uid_dylibloader_orig_speechd
+#define spd_cancel spd_cancel_dylibloader_orig_speechd
+#define spd_cancel_all spd_cancel_all_dylibloader_orig_speechd
+#define spd_cancel_uid spd_cancel_uid_dylibloader_orig_speechd
+#define spd_pause spd_pause_dylibloader_orig_speechd
+#define spd_pause_all spd_pause_all_dylibloader_orig_speechd
+#define spd_pause_uid spd_pause_uid_dylibloader_orig_speechd
+#define spd_resume spd_resume_dylibloader_orig_speechd
+#define spd_resume_all spd_resume_all_dylibloader_orig_speechd
+#define spd_resume_uid spd_resume_uid_dylibloader_orig_speechd
+#define spd_key spd_key_dylibloader_orig_speechd
+#define spd_char spd_char_dylibloader_orig_speechd
+#define spd_wchar spd_wchar_dylibloader_orig_speechd
+#define spd_sound_icon spd_sound_icon_dylibloader_orig_speechd
+#define spd_set_voice_type spd_set_voice_type_dylibloader_orig_speechd
+#define spd_set_voice_type_all spd_set_voice_type_all_dylibloader_orig_speechd
+#define spd_set_voice_type_uid spd_set_voice_type_uid_dylibloader_orig_speechd
+#define spd_get_voice_type spd_get_voice_type_dylibloader_orig_speechd
+#define spd_set_synthesis_voice spd_set_synthesis_voice_dylibloader_orig_speechd
+#define spd_set_synthesis_voice_all spd_set_synthesis_voice_all_dylibloader_orig_speechd
+#define spd_set_synthesis_voice_uid spd_set_synthesis_voice_uid_dylibloader_orig_speechd
+#define spd_set_data_mode spd_set_data_mode_dylibloader_orig_speechd
+#define spd_set_notification_on spd_set_notification_on_dylibloader_orig_speechd
+#define spd_set_notification_off spd_set_notification_off_dylibloader_orig_speechd
+#define spd_set_notification spd_set_notification_dylibloader_orig_speechd
+#define spd_set_voice_rate spd_set_voice_rate_dylibloader_orig_speechd
+#define spd_set_voice_rate_all spd_set_voice_rate_all_dylibloader_orig_speechd
+#define spd_set_voice_rate_uid spd_set_voice_rate_uid_dylibloader_orig_speechd
+#define spd_get_voice_rate spd_get_voice_rate_dylibloader_orig_speechd
+#define spd_set_voice_pitch spd_set_voice_pitch_dylibloader_orig_speechd
+#define spd_set_voice_pitch_all spd_set_voice_pitch_all_dylibloader_orig_speechd
+#define spd_set_voice_pitch_uid spd_set_voice_pitch_uid_dylibloader_orig_speechd
+#define spd_get_voice_pitch spd_get_voice_pitch_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range spd_set_voice_pitch_range_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range_all spd_set_voice_pitch_range_all_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range_uid spd_set_voice_pitch_range_uid_dylibloader_orig_speechd
+#define spd_set_volume spd_set_volume_dylibloader_orig_speechd
+#define spd_set_volume_all spd_set_volume_all_dylibloader_orig_speechd
+#define spd_set_volume_uid spd_set_volume_uid_dylibloader_orig_speechd
+#define spd_get_volume spd_get_volume_dylibloader_orig_speechd
+#define spd_set_punctuation spd_set_punctuation_dylibloader_orig_speechd
+#define spd_set_punctuation_all spd_set_punctuation_all_dylibloader_orig_speechd
+#define spd_set_punctuation_uid spd_set_punctuation_uid_dylibloader_orig_speechd
+#define spd_set_capital_letters spd_set_capital_letters_dylibloader_orig_speechd
+#define spd_set_capital_letters_all spd_set_capital_letters_all_dylibloader_orig_speechd
+#define spd_set_capital_letters_uid spd_set_capital_letters_uid_dylibloader_orig_speechd
+#define spd_set_spelling spd_set_spelling_dylibloader_orig_speechd
+#define spd_set_spelling_all spd_set_spelling_all_dylibloader_orig_speechd
+#define spd_set_spelling_uid spd_set_spelling_uid_dylibloader_orig_speechd
+#define spd_set_language spd_set_language_dylibloader_orig_speechd
+#define spd_set_language_all spd_set_language_all_dylibloader_orig_speechd
+#define spd_set_language_uid spd_set_language_uid_dylibloader_orig_speechd
+#define spd_get_language spd_get_language_dylibloader_orig_speechd
+#define spd_set_output_module spd_set_output_module_dylibloader_orig_speechd
+#define spd_set_output_module_all spd_set_output_module_all_dylibloader_orig_speechd
+#define spd_set_output_module_uid spd_set_output_module_uid_dylibloader_orig_speechd
+#define spd_get_message_list_fd spd_get_message_list_fd_dylibloader_orig_speechd
+#define spd_list_modules spd_list_modules_dylibloader_orig_speechd
+#define free_spd_modules free_spd_modules_dylibloader_orig_speechd
+#define spd_get_output_module spd_get_output_module_dylibloader_orig_speechd
+#define spd_list_voices spd_list_voices_dylibloader_orig_speechd
+#define spd_list_synthesis_voices spd_list_synthesis_voices_dylibloader_orig_speechd
+#define free_spd_voices free_spd_voices_dylibloader_orig_speechd
+#define spd_execute_command_with_list_reply spd_execute_command_with_list_reply_dylibloader_orig_speechd
+#define spd_execute_command spd_execute_command_dylibloader_orig_speechd
+#define spd_execute_command_with_reply spd_execute_command_with_reply_dylibloader_orig_speechd
+#define spd_execute_command_wo_mutex spd_execute_command_wo_mutex_dylibloader_orig_speechd
+#define spd_send_data spd_send_data_dylibloader_orig_speechd
+#define spd_send_data_wo_mutex spd_send_data_wo_mutex_dylibloader_orig_speechd
+#include <libspeechd.h>
+#undef SPDConnectionAddress__free
+#undef spd_get_default_address
+#undef spd_open
+#undef spd_open2
+#undef spd_close
+#undef spd_say
+#undef spd_sayf
+#undef spd_stop
+#undef spd_stop_all
+#undef spd_stop_uid
+#undef spd_cancel
+#undef spd_cancel_all
+#undef spd_cancel_uid
+#undef spd_pause
+#undef spd_pause_all
+#undef spd_pause_uid
+#undef spd_resume
+#undef spd_resume_all
+#undef spd_resume_uid
+#undef spd_key
+#undef spd_char
+#undef spd_wchar
+#undef spd_sound_icon
+#undef spd_set_voice_type
+#undef spd_set_voice_type_all
+#undef spd_set_voice_type_uid
+#undef spd_get_voice_type
+#undef spd_set_synthesis_voice
+#undef spd_set_synthesis_voice_all
+#undef spd_set_synthesis_voice_uid
+#undef spd_set_data_mode
+#undef spd_set_notification_on
+#undef spd_set_notification_off
+#undef spd_set_notification
+#undef spd_set_voice_rate
+#undef spd_set_voice_rate_all
+#undef spd_set_voice_rate_uid
+#undef spd_get_voice_rate
+#undef spd_set_voice_pitch
+#undef spd_set_voice_pitch_all
+#undef spd_set_voice_pitch_uid
+#undef spd_get_voice_pitch
+#undef spd_set_voice_pitch_range
+#undef spd_set_voice_pitch_range_all
+#undef spd_set_voice_pitch_range_uid
+#undef spd_set_volume
+#undef spd_set_volume_all
+#undef spd_set_volume_uid
+#undef spd_get_volume
+#undef spd_set_punctuation
+#undef spd_set_punctuation_all
+#undef spd_set_punctuation_uid
+#undef spd_set_capital_letters
+#undef spd_set_capital_letters_all
+#undef spd_set_capital_letters_uid
+#undef spd_set_spelling
+#undef spd_set_spelling_all
+#undef spd_set_spelling_uid
+#undef spd_set_language
+#undef spd_set_language_all
+#undef spd_set_language_uid
+#undef spd_get_language
+#undef spd_set_output_module
+#undef spd_set_output_module_all
+#undef spd_set_output_module_uid
+#undef spd_get_message_list_fd
+#undef spd_list_modules
+#undef free_spd_modules
+#undef spd_get_output_module
+#undef spd_list_voices
+#undef spd_list_synthesis_voices
+#undef free_spd_voices
+#undef spd_execute_command_with_list_reply
+#undef spd_execute_command
+#undef spd_execute_command_with_reply
+#undef spd_execute_command_wo_mutex
+#undef spd_send_data
+#undef spd_send_data_wo_mutex
+#include <dlfcn.h>
+#include <stdio.h>
+void (*SPDConnectionAddress__free_dylibloader_wrapper_speechd)( SPDConnectionAddress*);
+SPDConnectionAddress* (*spd_get_default_address_dylibloader_wrapper_speechd)( char**);
+SPDConnection* (*spd_open_dylibloader_wrapper_speechd)(const char*,const char*,const char*, SPDConnectionMode);
+SPDConnection* (*spd_open2_dylibloader_wrapper_speechd)(const char*,const char*,const char*, SPDConnectionMode, SPDConnectionAddress*, int, char**);
+void (*spd_close_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_say_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+int (*spd_sayf_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*,...);
+int (*spd_stop_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_stop_all_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_stop_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+int (*spd_cancel_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_cancel_all_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_cancel_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+int (*spd_pause_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_pause_all_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_pause_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+int (*spd_resume_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_resume_all_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_resume_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+int (*spd_key_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+int (*spd_char_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+int (*spd_wchar_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority, wchar_t);
+int (*spd_sound_icon_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+int (*spd_set_voice_type_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType);
+int (*spd_set_voice_type_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType);
+int (*spd_set_voice_type_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType, unsigned int);
+SPDVoiceType (*spd_get_voice_type_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_set_synthesis_voice_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_synthesis_voice_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_synthesis_voice_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+int (*spd_set_data_mode_dylibloader_wrapper_speechd)( SPDConnection*, SPDDataMode);
+int (*spd_set_notification_on_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification);
+int (*spd_set_notification_off_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification);
+int (*spd_set_notification_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification,const char*);
+int (*spd_set_voice_rate_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_rate_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_rate_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+int (*spd_get_voice_rate_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_set_voice_pitch_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_pitch_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_pitch_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+int (*spd_get_voice_pitch_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_set_voice_pitch_range_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_pitch_range_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_voice_pitch_range_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+int (*spd_set_volume_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_volume_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+int (*spd_set_volume_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+int (*spd_get_volume_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_set_punctuation_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation);
+int (*spd_set_punctuation_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation);
+int (*spd_set_punctuation_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation, unsigned int);
+int (*spd_set_capital_letters_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters);
+int (*spd_set_capital_letters_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters);
+int (*spd_set_capital_letters_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters, unsigned int);
+int (*spd_set_spelling_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling);
+int (*spd_set_spelling_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling);
+int (*spd_set_spelling_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling, unsigned int);
+int (*spd_set_language_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_language_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_language_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+char* (*spd_get_language_dylibloader_wrapper_speechd)( SPDConnection*);
+int (*spd_set_output_module_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_output_module_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+int (*spd_set_output_module_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+int (*spd_get_message_list_fd_dylibloader_wrapper_speechd)( SPDConnection*, int, int*, char**);
+char** (*spd_list_modules_dylibloader_wrapper_speechd)( SPDConnection*);
+void (*free_spd_modules_dylibloader_wrapper_speechd)( char**);
+char* (*spd_get_output_module_dylibloader_wrapper_speechd)( SPDConnection*);
+char** (*spd_list_voices_dylibloader_wrapper_speechd)( SPDConnection*);
+SPDVoice** (*spd_list_synthesis_voices_dylibloader_wrapper_speechd)( SPDConnection*);
+void (*free_spd_voices_dylibloader_wrapper_speechd)( SPDVoice**);
+char** (*spd_execute_command_with_list_reply_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+int (*spd_execute_command_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+int (*spd_execute_command_with_reply_dylibloader_wrapper_speechd)( SPDConnection*, char*, char**);
+int (*spd_execute_command_wo_mutex_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+char* (*spd_send_data_dylibloader_wrapper_speechd)( SPDConnection*,const char*, int);
+char* (*spd_send_data_wo_mutex_dylibloader_wrapper_speechd)( SPDConnection*,const char*, int);
+int initialize_speechd(int verbose) {
+ void *handle;
+ char *error;
+ handle = dlopen("libspeechd.so.2", RTLD_LAZY);
+ if (!handle) {
+ if (verbose) {
+ fprintf(stderr, "%s\n", dlerror());
+ }
+ return(1);
+ }
+ dlerror();
+// SPDConnectionAddress__free
+ *(void **) (&SPDConnectionAddress__free_dylibloader_wrapper_speechd) = dlsym(handle, "SPDConnectionAddress__free");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_default_address
+ *(void **) (&spd_get_default_address_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_default_address");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_open
+ *(void **) (&spd_open_dylibloader_wrapper_speechd) = dlsym(handle, "spd_open");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_open2
+ *(void **) (&spd_open2_dylibloader_wrapper_speechd) = dlsym(handle, "spd_open2");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_close
+ *(void **) (&spd_close_dylibloader_wrapper_speechd) = dlsym(handle, "spd_close");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_say
+ *(void **) (&spd_say_dylibloader_wrapper_speechd) = dlsym(handle, "spd_say");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_sayf
+ *(void **) (&spd_sayf_dylibloader_wrapper_speechd) = dlsym(handle, "spd_sayf");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_stop
+ *(void **) (&spd_stop_dylibloader_wrapper_speechd) = dlsym(handle, "spd_stop");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_stop_all
+ *(void **) (&spd_stop_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_stop_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_stop_uid
+ *(void **) (&spd_stop_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_stop_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_cancel
+ *(void **) (&spd_cancel_dylibloader_wrapper_speechd) = dlsym(handle, "spd_cancel");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_cancel_all
+ *(void **) (&spd_cancel_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_cancel_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_cancel_uid
+ *(void **) (&spd_cancel_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_cancel_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_pause
+ *(void **) (&spd_pause_dylibloader_wrapper_speechd) = dlsym(handle, "spd_pause");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_pause_all
+ *(void **) (&spd_pause_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_pause_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_pause_uid
+ *(void **) (&spd_pause_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_pause_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_resume
+ *(void **) (&spd_resume_dylibloader_wrapper_speechd) = dlsym(handle, "spd_resume");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_resume_all
+ *(void **) (&spd_resume_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_resume_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_resume_uid
+ *(void **) (&spd_resume_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_resume_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_key
+ *(void **) (&spd_key_dylibloader_wrapper_speechd) = dlsym(handle, "spd_key");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_char
+ *(void **) (&spd_char_dylibloader_wrapper_speechd) = dlsym(handle, "spd_char");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_wchar
+ *(void **) (&spd_wchar_dylibloader_wrapper_speechd) = dlsym(handle, "spd_wchar");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_sound_icon
+ *(void **) (&spd_sound_icon_dylibloader_wrapper_speechd) = dlsym(handle, "spd_sound_icon");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_type
+ *(void **) (&spd_set_voice_type_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_type");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_type_all
+ *(void **) (&spd_set_voice_type_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_type_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_type_uid
+ *(void **) (&spd_set_voice_type_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_type_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_voice_type
+ *(void **) (&spd_get_voice_type_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_voice_type");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_synthesis_voice
+ *(void **) (&spd_set_synthesis_voice_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_synthesis_voice");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_synthesis_voice_all
+ *(void **) (&spd_set_synthesis_voice_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_synthesis_voice_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_synthesis_voice_uid
+ *(void **) (&spd_set_synthesis_voice_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_synthesis_voice_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_data_mode
+ *(void **) (&spd_set_data_mode_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_data_mode");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_notification_on
+ *(void **) (&spd_set_notification_on_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_notification_on");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_notification_off
+ *(void **) (&spd_set_notification_off_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_notification_off");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_notification
+ *(void **) (&spd_set_notification_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_notification");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_rate
+ *(void **) (&spd_set_voice_rate_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_rate");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_rate_all
+ *(void **) (&spd_set_voice_rate_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_rate_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_rate_uid
+ *(void **) (&spd_set_voice_rate_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_rate_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_voice_rate
+ *(void **) (&spd_get_voice_rate_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_voice_rate");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch
+ *(void **) (&spd_set_voice_pitch_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch_all
+ *(void **) (&spd_set_voice_pitch_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch_uid
+ *(void **) (&spd_set_voice_pitch_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_voice_pitch
+ *(void **) (&spd_get_voice_pitch_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_voice_pitch");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch_range
+ *(void **) (&spd_set_voice_pitch_range_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch_range");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch_range_all
+ *(void **) (&spd_set_voice_pitch_range_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch_range_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_voice_pitch_range_uid
+ *(void **) (&spd_set_voice_pitch_range_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_voice_pitch_range_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_volume
+ *(void **) (&spd_set_volume_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_volume");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_volume_all
+ *(void **) (&spd_set_volume_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_volume_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_volume_uid
+ *(void **) (&spd_set_volume_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_volume_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_volume
+ *(void **) (&spd_get_volume_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_volume");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_punctuation
+ *(void **) (&spd_set_punctuation_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_punctuation");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_punctuation_all
+ *(void **) (&spd_set_punctuation_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_punctuation_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_punctuation_uid
+ *(void **) (&spd_set_punctuation_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_punctuation_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_capital_letters
+ *(void **) (&spd_set_capital_letters_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_capital_letters");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_capital_letters_all
+ *(void **) (&spd_set_capital_letters_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_capital_letters_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_capital_letters_uid
+ *(void **) (&spd_set_capital_letters_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_capital_letters_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_spelling
+ *(void **) (&spd_set_spelling_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_spelling");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_spelling_all
+ *(void **) (&spd_set_spelling_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_spelling_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_spelling_uid
+ *(void **) (&spd_set_spelling_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_spelling_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_language
+ *(void **) (&spd_set_language_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_language");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_language_all
+ *(void **) (&spd_set_language_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_language_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_language_uid
+ *(void **) (&spd_set_language_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_language_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_language
+ *(void **) (&spd_get_language_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_language");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_output_module
+ *(void **) (&spd_set_output_module_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_output_module");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_output_module_all
+ *(void **) (&spd_set_output_module_all_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_output_module_all");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_set_output_module_uid
+ *(void **) (&spd_set_output_module_uid_dylibloader_wrapper_speechd) = dlsym(handle, "spd_set_output_module_uid");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_message_list_fd
+ *(void **) (&spd_get_message_list_fd_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_message_list_fd");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_list_modules
+ *(void **) (&spd_list_modules_dylibloader_wrapper_speechd) = dlsym(handle, "spd_list_modules");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// free_spd_modules
+ *(void **) (&free_spd_modules_dylibloader_wrapper_speechd) = dlsym(handle, "free_spd_modules");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_get_output_module
+ *(void **) (&spd_get_output_module_dylibloader_wrapper_speechd) = dlsym(handle, "spd_get_output_module");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_list_voices
+ *(void **) (&spd_list_voices_dylibloader_wrapper_speechd) = dlsym(handle, "spd_list_voices");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_list_synthesis_voices
+ *(void **) (&spd_list_synthesis_voices_dylibloader_wrapper_speechd) = dlsym(handle, "spd_list_synthesis_voices");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// free_spd_voices
+ *(void **) (&free_spd_voices_dylibloader_wrapper_speechd) = dlsym(handle, "free_spd_voices");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_execute_command_with_list_reply
+ *(void **) (&spd_execute_command_with_list_reply_dylibloader_wrapper_speechd) = dlsym(handle, "spd_execute_command_with_list_reply");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_execute_command
+ *(void **) (&spd_execute_command_dylibloader_wrapper_speechd) = dlsym(handle, "spd_execute_command");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_execute_command_with_reply
+ *(void **) (&spd_execute_command_with_reply_dylibloader_wrapper_speechd) = dlsym(handle, "spd_execute_command_with_reply");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_execute_command_wo_mutex
+ *(void **) (&spd_execute_command_wo_mutex_dylibloader_wrapper_speechd) = dlsym(handle, "spd_execute_command_wo_mutex");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_send_data
+ *(void **) (&spd_send_data_dylibloader_wrapper_speechd) = dlsym(handle, "spd_send_data");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+// spd_send_data_wo_mutex
+ *(void **) (&spd_send_data_wo_mutex_dylibloader_wrapper_speechd) = dlsym(handle, "spd_send_data_wo_mutex");
+ if (verbose) {
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ }
+ }
+return 0;
+}
diff --git a/platform/linuxbsd/speechd-so_wrap.h b/platform/linuxbsd/speechd-so_wrap.h
new file mode 100644
index 0000000000..8e1c053348
--- /dev/null
+++ b/platform/linuxbsd/speechd-so_wrap.h
@@ -0,0 +1,330 @@
+#ifndef DYLIBLOAD_WRAPPER_SPEECHD
+#define DYLIBLOAD_WRAPPER_SPEECHD
+// This file is generated. Do not edit!
+// see https://github.com/hpvb/dynload-wrapper for details
+// generated by ./dynload-wrapper/generate-wrapper.py 0.3 on 2022-04-28 14:34:21
+// flags: ./dynload-wrapper/generate-wrapper.py --sys-include <libspeechd.h> --include /usr/include/speech-dispatcher/libspeechd.h --soname libspeechd.so.2 --init-name speechd --omit-prefix spd_get_client_list --output-header speechd-so_wrap.h --output-implementation speechd-so_wrap.c
+//
+#include <stdint.h>
+
+#define SPDConnectionAddress__free SPDConnectionAddress__free_dylibloader_orig_speechd
+#define spd_get_default_address spd_get_default_address_dylibloader_orig_speechd
+#define spd_open spd_open_dylibloader_orig_speechd
+#define spd_open2 spd_open2_dylibloader_orig_speechd
+#define spd_close spd_close_dylibloader_orig_speechd
+#define spd_say spd_say_dylibloader_orig_speechd
+#define spd_sayf spd_sayf_dylibloader_orig_speechd
+#define spd_stop spd_stop_dylibloader_orig_speechd
+#define spd_stop_all spd_stop_all_dylibloader_orig_speechd
+#define spd_stop_uid spd_stop_uid_dylibloader_orig_speechd
+#define spd_cancel spd_cancel_dylibloader_orig_speechd
+#define spd_cancel_all spd_cancel_all_dylibloader_orig_speechd
+#define spd_cancel_uid spd_cancel_uid_dylibloader_orig_speechd
+#define spd_pause spd_pause_dylibloader_orig_speechd
+#define spd_pause_all spd_pause_all_dylibloader_orig_speechd
+#define spd_pause_uid spd_pause_uid_dylibloader_orig_speechd
+#define spd_resume spd_resume_dylibloader_orig_speechd
+#define spd_resume_all spd_resume_all_dylibloader_orig_speechd
+#define spd_resume_uid spd_resume_uid_dylibloader_orig_speechd
+#define spd_key spd_key_dylibloader_orig_speechd
+#define spd_char spd_char_dylibloader_orig_speechd
+#define spd_wchar spd_wchar_dylibloader_orig_speechd
+#define spd_sound_icon spd_sound_icon_dylibloader_orig_speechd
+#define spd_set_voice_type spd_set_voice_type_dylibloader_orig_speechd
+#define spd_set_voice_type_all spd_set_voice_type_all_dylibloader_orig_speechd
+#define spd_set_voice_type_uid spd_set_voice_type_uid_dylibloader_orig_speechd
+#define spd_get_voice_type spd_get_voice_type_dylibloader_orig_speechd
+#define spd_set_synthesis_voice spd_set_synthesis_voice_dylibloader_orig_speechd
+#define spd_set_synthesis_voice_all spd_set_synthesis_voice_all_dylibloader_orig_speechd
+#define spd_set_synthesis_voice_uid spd_set_synthesis_voice_uid_dylibloader_orig_speechd
+#define spd_set_data_mode spd_set_data_mode_dylibloader_orig_speechd
+#define spd_set_notification_on spd_set_notification_on_dylibloader_orig_speechd
+#define spd_set_notification_off spd_set_notification_off_dylibloader_orig_speechd
+#define spd_set_notification spd_set_notification_dylibloader_orig_speechd
+#define spd_set_voice_rate spd_set_voice_rate_dylibloader_orig_speechd
+#define spd_set_voice_rate_all spd_set_voice_rate_all_dylibloader_orig_speechd
+#define spd_set_voice_rate_uid spd_set_voice_rate_uid_dylibloader_orig_speechd
+#define spd_get_voice_rate spd_get_voice_rate_dylibloader_orig_speechd
+#define spd_set_voice_pitch spd_set_voice_pitch_dylibloader_orig_speechd
+#define spd_set_voice_pitch_all spd_set_voice_pitch_all_dylibloader_orig_speechd
+#define spd_set_voice_pitch_uid spd_set_voice_pitch_uid_dylibloader_orig_speechd
+#define spd_get_voice_pitch spd_get_voice_pitch_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range spd_set_voice_pitch_range_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range_all spd_set_voice_pitch_range_all_dylibloader_orig_speechd
+#define spd_set_voice_pitch_range_uid spd_set_voice_pitch_range_uid_dylibloader_orig_speechd
+#define spd_set_volume spd_set_volume_dylibloader_orig_speechd
+#define spd_set_volume_all spd_set_volume_all_dylibloader_orig_speechd
+#define spd_set_volume_uid spd_set_volume_uid_dylibloader_orig_speechd
+#define spd_get_volume spd_get_volume_dylibloader_orig_speechd
+#define spd_set_punctuation spd_set_punctuation_dylibloader_orig_speechd
+#define spd_set_punctuation_all spd_set_punctuation_all_dylibloader_orig_speechd
+#define spd_set_punctuation_uid spd_set_punctuation_uid_dylibloader_orig_speechd
+#define spd_set_capital_letters spd_set_capital_letters_dylibloader_orig_speechd
+#define spd_set_capital_letters_all spd_set_capital_letters_all_dylibloader_orig_speechd
+#define spd_set_capital_letters_uid spd_set_capital_letters_uid_dylibloader_orig_speechd
+#define spd_set_spelling spd_set_spelling_dylibloader_orig_speechd
+#define spd_set_spelling_all spd_set_spelling_all_dylibloader_orig_speechd
+#define spd_set_spelling_uid spd_set_spelling_uid_dylibloader_orig_speechd
+#define spd_set_language spd_set_language_dylibloader_orig_speechd
+#define spd_set_language_all spd_set_language_all_dylibloader_orig_speechd
+#define spd_set_language_uid spd_set_language_uid_dylibloader_orig_speechd
+#define spd_get_language spd_get_language_dylibloader_orig_speechd
+#define spd_set_output_module spd_set_output_module_dylibloader_orig_speechd
+#define spd_set_output_module_all spd_set_output_module_all_dylibloader_orig_speechd
+#define spd_set_output_module_uid spd_set_output_module_uid_dylibloader_orig_speechd
+#define spd_get_message_list_fd spd_get_message_list_fd_dylibloader_orig_speechd
+#define spd_list_modules spd_list_modules_dylibloader_orig_speechd
+#define free_spd_modules free_spd_modules_dylibloader_orig_speechd
+#define spd_get_output_module spd_get_output_module_dylibloader_orig_speechd
+#define spd_list_voices spd_list_voices_dylibloader_orig_speechd
+#define spd_list_synthesis_voices spd_list_synthesis_voices_dylibloader_orig_speechd
+#define free_spd_voices free_spd_voices_dylibloader_orig_speechd
+#define spd_execute_command_with_list_reply spd_execute_command_with_list_reply_dylibloader_orig_speechd
+#define spd_execute_command spd_execute_command_dylibloader_orig_speechd
+#define spd_execute_command_with_reply spd_execute_command_with_reply_dylibloader_orig_speechd
+#define spd_execute_command_wo_mutex spd_execute_command_wo_mutex_dylibloader_orig_speechd
+#define spd_send_data spd_send_data_dylibloader_orig_speechd
+#define spd_send_data_wo_mutex spd_send_data_wo_mutex_dylibloader_orig_speechd
+#include <libspeechd.h>
+#undef SPDConnectionAddress__free
+#undef spd_get_default_address
+#undef spd_open
+#undef spd_open2
+#undef spd_close
+#undef spd_say
+#undef spd_sayf
+#undef spd_stop
+#undef spd_stop_all
+#undef spd_stop_uid
+#undef spd_cancel
+#undef spd_cancel_all
+#undef spd_cancel_uid
+#undef spd_pause
+#undef spd_pause_all
+#undef spd_pause_uid
+#undef spd_resume
+#undef spd_resume_all
+#undef spd_resume_uid
+#undef spd_key
+#undef spd_char
+#undef spd_wchar
+#undef spd_sound_icon
+#undef spd_set_voice_type
+#undef spd_set_voice_type_all
+#undef spd_set_voice_type_uid
+#undef spd_get_voice_type
+#undef spd_set_synthesis_voice
+#undef spd_set_synthesis_voice_all
+#undef spd_set_synthesis_voice_uid
+#undef spd_set_data_mode
+#undef spd_set_notification_on
+#undef spd_set_notification_off
+#undef spd_set_notification
+#undef spd_set_voice_rate
+#undef spd_set_voice_rate_all
+#undef spd_set_voice_rate_uid
+#undef spd_get_voice_rate
+#undef spd_set_voice_pitch
+#undef spd_set_voice_pitch_all
+#undef spd_set_voice_pitch_uid
+#undef spd_get_voice_pitch
+#undef spd_set_voice_pitch_range
+#undef spd_set_voice_pitch_range_all
+#undef spd_set_voice_pitch_range_uid
+#undef spd_set_volume
+#undef spd_set_volume_all
+#undef spd_set_volume_uid
+#undef spd_get_volume
+#undef spd_set_punctuation
+#undef spd_set_punctuation_all
+#undef spd_set_punctuation_uid
+#undef spd_set_capital_letters
+#undef spd_set_capital_letters_all
+#undef spd_set_capital_letters_uid
+#undef spd_set_spelling
+#undef spd_set_spelling_all
+#undef spd_set_spelling_uid
+#undef spd_set_language
+#undef spd_set_language_all
+#undef spd_set_language_uid
+#undef spd_get_language
+#undef spd_set_output_module
+#undef spd_set_output_module_all
+#undef spd_set_output_module_uid
+#undef spd_get_message_list_fd
+#undef spd_list_modules
+#undef free_spd_modules
+#undef spd_get_output_module
+#undef spd_list_voices
+#undef spd_list_synthesis_voices
+#undef free_spd_voices
+#undef spd_execute_command_with_list_reply
+#undef spd_execute_command
+#undef spd_execute_command_with_reply
+#undef spd_execute_command_wo_mutex
+#undef spd_send_data
+#undef spd_send_data_wo_mutex
+#ifdef __cplusplus
+extern "C" {
+#endif
+#define SPDConnectionAddress__free SPDConnectionAddress__free_dylibloader_wrapper_speechd
+#define spd_get_default_address spd_get_default_address_dylibloader_wrapper_speechd
+#define spd_open spd_open_dylibloader_wrapper_speechd
+#define spd_open2 spd_open2_dylibloader_wrapper_speechd
+#define spd_close spd_close_dylibloader_wrapper_speechd
+#define spd_say spd_say_dylibloader_wrapper_speechd
+#define spd_sayf spd_sayf_dylibloader_wrapper_speechd
+#define spd_stop spd_stop_dylibloader_wrapper_speechd
+#define spd_stop_all spd_stop_all_dylibloader_wrapper_speechd
+#define spd_stop_uid spd_stop_uid_dylibloader_wrapper_speechd
+#define spd_cancel spd_cancel_dylibloader_wrapper_speechd
+#define spd_cancel_all spd_cancel_all_dylibloader_wrapper_speechd
+#define spd_cancel_uid spd_cancel_uid_dylibloader_wrapper_speechd
+#define spd_pause spd_pause_dylibloader_wrapper_speechd
+#define spd_pause_all spd_pause_all_dylibloader_wrapper_speechd
+#define spd_pause_uid spd_pause_uid_dylibloader_wrapper_speechd
+#define spd_resume spd_resume_dylibloader_wrapper_speechd
+#define spd_resume_all spd_resume_all_dylibloader_wrapper_speechd
+#define spd_resume_uid spd_resume_uid_dylibloader_wrapper_speechd
+#define spd_key spd_key_dylibloader_wrapper_speechd
+#define spd_char spd_char_dylibloader_wrapper_speechd
+#define spd_wchar spd_wchar_dylibloader_wrapper_speechd
+#define spd_sound_icon spd_sound_icon_dylibloader_wrapper_speechd
+#define spd_set_voice_type spd_set_voice_type_dylibloader_wrapper_speechd
+#define spd_set_voice_type_all spd_set_voice_type_all_dylibloader_wrapper_speechd
+#define spd_set_voice_type_uid spd_set_voice_type_uid_dylibloader_wrapper_speechd
+#define spd_get_voice_type spd_get_voice_type_dylibloader_wrapper_speechd
+#define spd_set_synthesis_voice spd_set_synthesis_voice_dylibloader_wrapper_speechd
+#define spd_set_synthesis_voice_all spd_set_synthesis_voice_all_dylibloader_wrapper_speechd
+#define spd_set_synthesis_voice_uid spd_set_synthesis_voice_uid_dylibloader_wrapper_speechd
+#define spd_set_data_mode spd_set_data_mode_dylibloader_wrapper_speechd
+#define spd_set_notification_on spd_set_notification_on_dylibloader_wrapper_speechd
+#define spd_set_notification_off spd_set_notification_off_dylibloader_wrapper_speechd
+#define spd_set_notification spd_set_notification_dylibloader_wrapper_speechd
+#define spd_set_voice_rate spd_set_voice_rate_dylibloader_wrapper_speechd
+#define spd_set_voice_rate_all spd_set_voice_rate_all_dylibloader_wrapper_speechd
+#define spd_set_voice_rate_uid spd_set_voice_rate_uid_dylibloader_wrapper_speechd
+#define spd_get_voice_rate spd_get_voice_rate_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch spd_set_voice_pitch_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch_all spd_set_voice_pitch_all_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch_uid spd_set_voice_pitch_uid_dylibloader_wrapper_speechd
+#define spd_get_voice_pitch spd_get_voice_pitch_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch_range spd_set_voice_pitch_range_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch_range_all spd_set_voice_pitch_range_all_dylibloader_wrapper_speechd
+#define spd_set_voice_pitch_range_uid spd_set_voice_pitch_range_uid_dylibloader_wrapper_speechd
+#define spd_set_volume spd_set_volume_dylibloader_wrapper_speechd
+#define spd_set_volume_all spd_set_volume_all_dylibloader_wrapper_speechd
+#define spd_set_volume_uid spd_set_volume_uid_dylibloader_wrapper_speechd
+#define spd_get_volume spd_get_volume_dylibloader_wrapper_speechd
+#define spd_set_punctuation spd_set_punctuation_dylibloader_wrapper_speechd
+#define spd_set_punctuation_all spd_set_punctuation_all_dylibloader_wrapper_speechd
+#define spd_set_punctuation_uid spd_set_punctuation_uid_dylibloader_wrapper_speechd
+#define spd_set_capital_letters spd_set_capital_letters_dylibloader_wrapper_speechd
+#define spd_set_capital_letters_all spd_set_capital_letters_all_dylibloader_wrapper_speechd
+#define spd_set_capital_letters_uid spd_set_capital_letters_uid_dylibloader_wrapper_speechd
+#define spd_set_spelling spd_set_spelling_dylibloader_wrapper_speechd
+#define spd_set_spelling_all spd_set_spelling_all_dylibloader_wrapper_speechd
+#define spd_set_spelling_uid spd_set_spelling_uid_dylibloader_wrapper_speechd
+#define spd_set_language spd_set_language_dylibloader_wrapper_speechd
+#define spd_set_language_all spd_set_language_all_dylibloader_wrapper_speechd
+#define spd_set_language_uid spd_set_language_uid_dylibloader_wrapper_speechd
+#define spd_get_language spd_get_language_dylibloader_wrapper_speechd
+#define spd_set_output_module spd_set_output_module_dylibloader_wrapper_speechd
+#define spd_set_output_module_all spd_set_output_module_all_dylibloader_wrapper_speechd
+#define spd_set_output_module_uid spd_set_output_module_uid_dylibloader_wrapper_speechd
+#define spd_get_message_list_fd spd_get_message_list_fd_dylibloader_wrapper_speechd
+#define spd_list_modules spd_list_modules_dylibloader_wrapper_speechd
+#define free_spd_modules free_spd_modules_dylibloader_wrapper_speechd
+#define spd_get_output_module spd_get_output_module_dylibloader_wrapper_speechd
+#define spd_list_voices spd_list_voices_dylibloader_wrapper_speechd
+#define spd_list_synthesis_voices spd_list_synthesis_voices_dylibloader_wrapper_speechd
+#define free_spd_voices free_spd_voices_dylibloader_wrapper_speechd
+#define spd_execute_command_with_list_reply spd_execute_command_with_list_reply_dylibloader_wrapper_speechd
+#define spd_execute_command spd_execute_command_dylibloader_wrapper_speechd
+#define spd_execute_command_with_reply spd_execute_command_with_reply_dylibloader_wrapper_speechd
+#define spd_execute_command_wo_mutex spd_execute_command_wo_mutex_dylibloader_wrapper_speechd
+#define spd_send_data spd_send_data_dylibloader_wrapper_speechd
+#define spd_send_data_wo_mutex spd_send_data_wo_mutex_dylibloader_wrapper_speechd
+extern void (*SPDConnectionAddress__free_dylibloader_wrapper_speechd)( SPDConnectionAddress*);
+extern SPDConnectionAddress* (*spd_get_default_address_dylibloader_wrapper_speechd)( char**);
+extern SPDConnection* (*spd_open_dylibloader_wrapper_speechd)(const char*,const char*,const char*, SPDConnectionMode);
+extern SPDConnection* (*spd_open2_dylibloader_wrapper_speechd)(const char*,const char*,const char*, SPDConnectionMode, SPDConnectionAddress*, int, char**);
+extern void (*spd_close_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_say_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+extern int (*spd_sayf_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*,...);
+extern int (*spd_stop_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_stop_all_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_stop_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+extern int (*spd_cancel_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_cancel_all_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_cancel_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+extern int (*spd_pause_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_pause_all_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_pause_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+extern int (*spd_resume_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_resume_all_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_resume_uid_dylibloader_wrapper_speechd)( SPDConnection*, int);
+extern int (*spd_key_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+extern int (*spd_char_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+extern int (*spd_wchar_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority, wchar_t);
+extern int (*spd_sound_icon_dylibloader_wrapper_speechd)( SPDConnection*, SPDPriority,const char*);
+extern int (*spd_set_voice_type_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType);
+extern int (*spd_set_voice_type_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType);
+extern int (*spd_set_voice_type_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDVoiceType, unsigned int);
+extern SPDVoiceType (*spd_get_voice_type_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_set_synthesis_voice_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_synthesis_voice_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_synthesis_voice_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+extern int (*spd_set_data_mode_dylibloader_wrapper_speechd)( SPDConnection*, SPDDataMode);
+extern int (*spd_set_notification_on_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification);
+extern int (*spd_set_notification_off_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification);
+extern int (*spd_set_notification_dylibloader_wrapper_speechd)( SPDConnection*, SPDNotification,const char*);
+extern int (*spd_set_voice_rate_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_rate_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_rate_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+extern int (*spd_get_voice_rate_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_set_voice_pitch_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_pitch_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_pitch_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+extern int (*spd_get_voice_pitch_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_set_voice_pitch_range_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_pitch_range_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_voice_pitch_range_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+extern int (*spd_set_volume_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_volume_all_dylibloader_wrapper_speechd)( SPDConnection*, signed int);
+extern int (*spd_set_volume_uid_dylibloader_wrapper_speechd)( SPDConnection*, signed int, unsigned int);
+extern int (*spd_get_volume_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_set_punctuation_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation);
+extern int (*spd_set_punctuation_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation);
+extern int (*spd_set_punctuation_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDPunctuation, unsigned int);
+extern int (*spd_set_capital_letters_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters);
+extern int (*spd_set_capital_letters_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters);
+extern int (*spd_set_capital_letters_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDCapitalLetters, unsigned int);
+extern int (*spd_set_spelling_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling);
+extern int (*spd_set_spelling_all_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling);
+extern int (*spd_set_spelling_uid_dylibloader_wrapper_speechd)( SPDConnection*, SPDSpelling, unsigned int);
+extern int (*spd_set_language_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_language_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_language_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+extern char* (*spd_get_language_dylibloader_wrapper_speechd)( SPDConnection*);
+extern int (*spd_set_output_module_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_output_module_all_dylibloader_wrapper_speechd)( SPDConnection*,const char*);
+extern int (*spd_set_output_module_uid_dylibloader_wrapper_speechd)( SPDConnection*,const char*, unsigned int);
+extern int (*spd_get_message_list_fd_dylibloader_wrapper_speechd)( SPDConnection*, int, int*, char**);
+extern char** (*spd_list_modules_dylibloader_wrapper_speechd)( SPDConnection*);
+extern void (*free_spd_modules_dylibloader_wrapper_speechd)( char**);
+extern char* (*spd_get_output_module_dylibloader_wrapper_speechd)( SPDConnection*);
+extern char** (*spd_list_voices_dylibloader_wrapper_speechd)( SPDConnection*);
+extern SPDVoice** (*spd_list_synthesis_voices_dylibloader_wrapper_speechd)( SPDConnection*);
+extern void (*free_spd_voices_dylibloader_wrapper_speechd)( SPDVoice**);
+extern char** (*spd_execute_command_with_list_reply_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+extern int (*spd_execute_command_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+extern int (*spd_execute_command_with_reply_dylibloader_wrapper_speechd)( SPDConnection*, char*, char**);
+extern int (*spd_execute_command_wo_mutex_dylibloader_wrapper_speechd)( SPDConnection*, char*);
+extern char* (*spd_send_data_dylibloader_wrapper_speechd)( SPDConnection*,const char*, int);
+extern char* (*spd_send_data_wo_mutex_dylibloader_wrapper_speechd)( SPDConnection*,const char*, int);
+int initialize_speechd(int verbose);
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/platform/linuxbsd/tts_linux.cpp b/platform/linuxbsd/tts_linux.cpp
new file mode 100644
index 0000000000..aea1183d3d
--- /dev/null
+++ b/platform/linuxbsd/tts_linux.cpp
@@ -0,0 +1,261 @@
+/*************************************************************************/
+/* tts_linux.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tts_linux.h"
+
+#include "core/config/project_settings.h"
+#include "servers/text_server.h"
+
+TTS_Linux *TTS_Linux::singleton = nullptr;
+
+void TTS_Linux::speech_init_thread_func(void *p_userdata) {
+ TTS_Linux *tts = (TTS_Linux *)p_userdata;
+ if (tts) {
+ MutexLock thread_safe_method(tts->_thread_safe_);
+#ifdef DEBUG_ENABLED
+ int dylibloader_verbose = 1;
+#else
+ int dylibloader_verbose = 0;
+#endif
+ if (initialize_speechd(dylibloader_verbose) == 0) {
+ CharString class_str;
+ String config_name = GLOBAL_GET("application/config/name");
+ if (config_name.length() == 0) {
+ class_str = "Godot_Engine";
+ } else {
+ class_str = config_name.utf8();
+ }
+ tts->synth = spd_open(class_str, "Godot_Engine_Speech_API", "Godot_Engine", SPD_MODE_THREADED);
+ if (tts->synth) {
+ tts->synth->callback_end = &speech_event_callback;
+ tts->synth->callback_cancel = &speech_event_callback;
+ tts->synth->callback_im = &speech_event_index_mark;
+ spd_set_notification_on(tts->synth, SPD_END);
+ spd_set_notification_on(tts->synth, SPD_CANCEL);
+
+ print_verbose("Text-to-Speech: Speech Dispatcher initialized.");
+ } else {
+ print_verbose("Text-to-Speech: Cannot initialize Speech Dispatcher synthesizer!");
+ }
+ } else {
+ print_verbose("Text-to-Speech: Cannot load Speech Dispatcher library!");
+ }
+ }
+}
+
+void TTS_Linux::speech_event_index_mark(size_t p_msg_id, size_t p_client_id, SPDNotificationType p_type, char *p_index_mark) {
+ TTS_Linux *tts = TTS_Linux::get_singleton();
+ if (tts && tts->ids.has(p_msg_id)) {
+ MutexLock thread_safe_method(tts->_thread_safe_);
+ // Get word offset from the index mark injected to the text stream.
+ String mark = String::utf8(p_index_mark);
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, tts->ids[p_msg_id], mark.to_int());
+ }
+}
+
+void TTS_Linux::speech_event_callback(size_t p_msg_id, size_t p_client_id, SPDNotificationType p_type) {
+ TTS_Linux *tts = TTS_Linux::get_singleton();
+ if (tts) {
+ MutexLock thread_safe_method(tts->_thread_safe_);
+ List<DisplayServer::TTSUtterance> &queue = tts->queue;
+ if (!tts->paused && tts->ids.has(p_msg_id)) {
+ if (p_type == SPD_EVENT_END) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, tts->ids[p_msg_id]);
+ tts->ids.erase(p_msg_id);
+ tts->last_msg_id = -1;
+ tts->speaking = false;
+ } else if (p_type == SPD_EVENT_CANCEL) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, tts->ids[p_msg_id]);
+ tts->ids.erase(p_msg_id);
+ tts->last_msg_id = -1;
+ tts->speaking = false;
+ }
+ }
+ if (!tts->speaking && queue.size() > 0) {
+ DisplayServer::TTSUtterance &message = queue.front()->get();
+
+ // Inject index mark after each word.
+ String text;
+ String language;
+ SPDVoice **voices = spd_list_synthesis_voices(tts->synth);
+ if (voices != nullptr) {
+ SPDVoice **voices_ptr = voices;
+ while (*voices_ptr != nullptr) {
+ if (String::utf8((*voices_ptr)->name) == message.voice) {
+ language = String::utf8((*voices_ptr)->language);
+ break;
+ }
+ voices_ptr++;
+ }
+ free_spd_voices(voices);
+ }
+ PackedInt32Array breaks = TS->string_get_word_breaks(message.text, language);
+ int prev = 0;
+ for (int i = 0; i < breaks.size(); i++) {
+ text += message.text.substr(prev, breaks[i] - prev);
+ text += "<mark name=\"" + String::num_int64(breaks[i], 10) + "\"/>";
+ prev = breaks[i];
+ }
+ text += message.text.substr(prev, -1);
+
+ spd_set_synthesis_voice(tts->synth, message.voice.utf8().get_data());
+ spd_set_volume(tts->synth, message.volume * 2 - 100);
+ spd_set_voice_pitch(tts->synth, (message.pitch - 1) * 100);
+ float rate = 0;
+ if (message.rate > 1.f) {
+ rate = log10(MIN(message.rate, 2.5f)) / log10(2.5f) * 100;
+ } else if (message.rate < 1.f) {
+ rate = log10(MAX(message.rate, 0.5f)) / log10(0.5f) * -100;
+ }
+ spd_set_voice_rate(tts->synth, rate);
+ spd_set_data_mode(tts->synth, SPD_DATA_SSML);
+ tts->last_msg_id = spd_say(tts->synth, SPD_TEXT, text.utf8().get_data());
+ tts->ids[tts->last_msg_id] = message.id;
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, message.id);
+
+ queue.pop_front();
+ tts->speaking = true;
+ }
+ }
+}
+
+bool TTS_Linux::is_speaking() const {
+ return speaking;
+}
+
+bool TTS_Linux::is_paused() const {
+ return paused;
+}
+
+Array TTS_Linux::get_voices() const {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND_V(!synth, Array());
+ Array list;
+ SPDVoice **voices = spd_list_synthesis_voices(synth);
+ if (voices != nullptr) {
+ SPDVoice **voices_ptr = voices;
+ while (*voices_ptr != nullptr) {
+ Dictionary voice_d;
+ voice_d["name"] = String::utf8((*voices_ptr)->name);
+ voice_d["id"] = String::utf8((*voices_ptr)->name);
+ voice_d["language"] = String::utf8((*voices_ptr)->language) + "_" + String::utf8((*voices_ptr)->variant);
+ list.push_back(voice_d);
+
+ voices_ptr++;
+ }
+ free_spd_voices(voices);
+ }
+ return list;
+}
+
+void TTS_Linux::speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!synth);
+ if (p_interrupt) {
+ stop();
+ }
+
+ if (p_text.is_empty()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
+ return;
+ }
+
+ DisplayServer::TTSUtterance message;
+ message.text = p_text;
+ message.voice = p_voice;
+ message.volume = CLAMP(p_volume, 0, 100);
+ message.pitch = CLAMP(p_pitch, 0.f, 2.f);
+ message.rate = CLAMP(p_rate, 0.1f, 10.f);
+ message.id = p_utterance_id;
+ queue.push_back(message);
+
+ if (is_paused()) {
+ resume();
+ } else {
+ speech_event_callback(0, 0, SPD_EVENT_BEGIN);
+ }
+}
+
+void TTS_Linux::pause() {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!synth);
+ if (spd_pause(synth) == 0) {
+ paused = true;
+ }
+}
+
+void TTS_Linux::resume() {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!synth);
+ spd_resume(synth);
+ paused = false;
+}
+
+void TTS_Linux::stop() {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!synth);
+ for (DisplayServer::TTSUtterance &message : queue) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
+ }
+ if ((last_msg_id != -1) && ids.has(last_msg_id)) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[last_msg_id]);
+ }
+ queue.clear();
+ ids.clear();
+ last_msg_id = -1;
+ spd_cancel(synth);
+ spd_resume(synth);
+ speaking = false;
+ paused = false;
+}
+
+TTS_Linux *TTS_Linux::get_singleton() {
+ return singleton;
+}
+
+TTS_Linux::TTS_Linux() {
+ singleton = this;
+ // Speech Dispatcher init can be slow, it might wait for helper process to start on background, so run it in the thread.
+ init_thread.start(speech_init_thread_func, this);
+}
+
+TTS_Linux::~TTS_Linux() {
+ init_thread.wait_to_finish();
+ if (synth) {
+ spd_close(synth);
+ }
+
+ singleton = nullptr;
+}
diff --git a/platform/linuxbsd/tts_linux.h b/platform/linuxbsd/tts_linux.h
new file mode 100644
index 0000000000..4d39af8970
--- /dev/null
+++ b/platform/linuxbsd/tts_linux.h
@@ -0,0 +1,78 @@
+/*************************************************************************/
+/* tts_linux.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TTS_LINUX_H
+#define TTS_LINUX_H
+
+#include "core/os/thread.h"
+#include "core/os/thread_safe.h"
+#include "core/string/ustring.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/variant/array.h"
+#include "servers/display_server.h"
+
+#include "speechd-so_wrap.h"
+
+class TTS_Linux {
+ _THREAD_SAFE_CLASS_
+
+ List<DisplayServer::TTSUtterance> queue;
+ SPDConnection *synth = nullptr;
+ bool speaking = false;
+ bool paused = false;
+ int last_msg_id = -1;
+ Map<int, int> ids;
+
+ Thread init_thread;
+
+ static void speech_init_thread_func(void *p_userdata);
+ static void speech_event_callback(size_t p_msg_id, size_t p_client_id, SPDNotificationType p_type);
+ static void speech_event_index_mark(size_t p_msg_id, size_t p_client_id, SPDNotificationType p_type, char *p_index_mark);
+
+ static TTS_Linux *singleton;
+
+public:
+ static TTS_Linux *get_singleton();
+
+ bool is_speaking() const;
+ bool is_paused() const;
+ Array get_voices() const;
+
+ void speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false);
+ void pause();
+ void resume();
+ void stop();
+
+ TTS_Linux();
+ ~TTS_Linux();
+};
+
+#endif // TTS_LINUX_H
diff --git a/platform/osx/SCsub b/platform/osx/SCsub
index d72a75af04..3a4c95613d 100644
--- a/platform/osx/SCsub
+++ b/platform/osx/SCsub
@@ -18,6 +18,7 @@ files = [
"key_mapping_osx.mm",
"godot_main_osx.mm",
"dir_access_osx.mm",
+ "tts_osx.mm",
"joypad_osx.cpp",
"vulkan_context_osx.mm",
"gl_manager_osx_legacy.mm",
diff --git a/platform/osx/display_server_osx.h b/platform/osx/display_server_osx.h
index fa3091ff81..fcb3a62bec 100644
--- a/platform/osx/display_server_osx.h
+++ b/platform/osx/display_server_osx.h
@@ -137,6 +137,8 @@ private:
Vector<KeyEvent> key_event_buffer;
int key_event_pos = 0;
+ id tts = nullptr;
+
Point2i im_selection;
String im_text;
@@ -264,6 +266,15 @@ public:
virtual void global_menu_remove_item(const String &p_menu_root, int p_idx) override;
virtual void global_menu_clear(const String &p_menu_root) override;
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+
virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) override;
virtual Error dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) override;
diff --git a/platform/osx/display_server_osx.mm b/platform/osx/display_server_osx.mm
index d209c90d87..17a44a3fbd 100644
--- a/platform/osx/display_server_osx.mm
+++ b/platform/osx/display_server_osx.mm
@@ -37,6 +37,8 @@
#include "key_mapping_osx.h"
#include "os_osx.h"
+#include "tts_osx.h"
+
#include "core/io/marshalls.h"
#include "core/math/geometry_2d.h"
#include "core/os/keyboard.h"
@@ -702,6 +704,7 @@ bool DisplayServerOSX::has_feature(Feature p_feature) const {
case FEATURE_NATIVE_ICON:
//case FEATURE_KEEP_SCREEN_ON:
case FEATURE_SWAP_BUFFERS:
+ case FEATURE_TEXT_TO_SPEECH:
return true;
default: {
}
@@ -1458,6 +1461,41 @@ void DisplayServerOSX::global_menu_clear(const String &p_menu_root) {
}
}
+bool DisplayServerOSX::tts_is_speaking() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return [tts isSpeaking];
+}
+
+bool DisplayServerOSX::tts_is_paused() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return [tts isPaused];
+}
+
+Array DisplayServerOSX::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, Array());
+ return [tts getVoices];
+}
+
+void DisplayServerOSX::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ ERR_FAIL_COND(!tts);
+ [tts speak:p_text voice:p_voice volume:p_volume pitch:p_pitch rate:p_rate utterance_id:p_utterance_id interrupt:p_interrupt];
+}
+
+void DisplayServerOSX::tts_pause() {
+ ERR_FAIL_COND(!tts);
+ [tts pauseSpeaking];
+}
+
+void DisplayServerOSX::tts_resume() {
+ ERR_FAIL_COND(!tts);
+ [tts resumeSpeaking];
+}
+
+void DisplayServerOSX::tts_stop() {
+ ERR_FAIL_COND(!tts);
+ [tts stopSpeaking];
+}
+
Error DisplayServerOSX::dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) {
_THREAD_SAFE_METHOD_
@@ -3121,6 +3159,9 @@ DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode
// Register to be notified on displays arrangement changes.
CGDisplayRegisterReconfigurationCallback(_displays_arrangement_changed, nullptr);
+ // Init TTS
+ tts = [[TTS_OSX alloc] init];
+
NSMenuItem *menu_item;
NSString *title;
diff --git a/platform/osx/tts_osx.h b/platform/osx/tts_osx.h
new file mode 100644
index 0000000000..2cf6d21c18
--- /dev/null
+++ b/platform/osx/tts_osx.h
@@ -0,0 +1,66 @@
+/*************************************************************************/
+/* tts_osx.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TTS_OSX_H
+#define TTS_OSX_H
+
+#include "core/string/ustring.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/variant/array.h"
+#include "servers/display_server.h"
+
+#include <AVFAudio/AVSpeechSynthesis.h>
+#include <AppKit/AppKit.h>
+
+@interface TTS_OSX : NSObject <AVSpeechSynthesizerDelegate> {
+ // AVSpeechSynthesizer
+ bool speaking;
+ Map<id, int> ids;
+
+ // NSSpeechSynthesizer
+ bool paused;
+ bool have_utterance;
+ int last_utterance;
+
+ id synth; // NSSpeechSynthesizer or AVSpeechSynthesizer
+ List<DisplayServer::TTSUtterance> queue;
+}
+
+- (void)pauseSpeaking;
+- (void)resumeSpeaking;
+- (void)stopSpeaking;
+- (bool)isSpeaking;
+- (bool)isPaused;
+- (void)speak:(const String &)text voice:(const String &)voice volume:(int)volume pitch:(float)pitch rate:(float)rate utterance_id:(int)utterance_id interrupt:(bool)interrupt;
+- (Array)getVoices;
+@end
+
+#endif // TTS_OSX_H
diff --git a/platform/osx/tts_osx.mm b/platform/osx/tts_osx.mm
new file mode 100644
index 0000000000..e6a5236cd9
--- /dev/null
+++ b/platform/osx/tts_osx.mm
@@ -0,0 +1,266 @@
+/*************************************************************************/
+/* tts_osx.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tts_osx.h"
+
+@implementation TTS_OSX
+
+- (id)init {
+ self = [super init];
+ self->speaking = false;
+ self->have_utterance = false;
+ self->last_utterance = -1;
+ self->paused = false;
+ if (@available(macOS 10.14, *)) {
+ self->synth = [[AVSpeechSynthesizer alloc] init];
+ [self->synth setDelegate:self];
+ print_verbose("Text-to-Speech: AVSpeechSynthesizer initialized.");
+ } else {
+ self->synth = [[NSSpeechSynthesizer alloc] init];
+ [self->synth setDelegate:self];
+ print_verbose("Text-to-Speech: NSSpeechSynthesizer initialized.");
+ }
+ return self;
+}
+
+// AVSpeechSynthesizer callback (macOS 10.14+)
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
+ NSString *string = [utterance speechString];
+
+ // Convert from UTF-16 to UTF-32 position.
+ int pos = 0;
+ for (NSUInteger i = 0; i < MIN(characterRange.location, string.length); i++) {
+ unichar c = [string characterAtIndex:i];
+ if ((c & 0xfffffc00) == 0xd800) {
+ i++;
+ }
+ pos++;
+ }
+
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, ids[utterance], pos);
+}
+
+// AVSpeechSynthesizer callback (macOS 10.14+)
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didCancelSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[utterance]);
+ ids.erase(utterance);
+ speaking = false;
+ [self update];
+}
+
+// AVSpeechSynthesizer callback (macOS 10.14+)
+
+- (void)speechSynthesizer:(AVSpeechSynthesizer *)av_synth didFinishSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(macosx(10.14)) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, ids[utterance]);
+ ids.erase(utterance);
+ speaking = false;
+ [self update];
+}
+
+// NSSpeechSynthesizer callback (macOS 10.4+)
+
+- (void)speechSynthesizer:(NSSpeechSynthesizer *)ns_synth willSpeakWord:(NSRange)characterRange ofString:(NSString *)string {
+ if (!paused && have_utterance) {
+ // Convert from UTF-16 to UTF-32 position.
+ int pos = 0;
+ for (NSUInteger i = 0; i < MIN(characterRange.location, string.length); i++) {
+ unichar c = [string characterAtIndex:i];
+ if ((c & 0xfffffc00) == 0xd800) {
+ i++;
+ }
+ pos++;
+ }
+
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, last_utterance, pos);
+ }
+}
+
+- (void)speechSynthesizer:(NSSpeechSynthesizer *)ns_synth didFinishSpeaking:(BOOL)success {
+ if (!paused && have_utterance) {
+ if (success) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, last_utterance);
+ } else {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, last_utterance);
+ }
+ have_utterance = false;
+ }
+ speaking = false;
+ [self update];
+}
+
+- (void)update {
+ if (!speaking && queue.size() > 0) {
+ DisplayServer::TTSUtterance &message = queue.front()->get();
+
+ if (@available(macOS 10.14, *)) {
+ AVSpeechSynthesizer *av_synth = synth;
+ AVSpeechUtterance *new_utterance = [[AVSpeechUtterance alloc] initWithString:[NSString stringWithUTF8String:message.text.utf8().get_data()]];
+ [new_utterance setVoice:[AVSpeechSynthesisVoice voiceWithIdentifier:[NSString stringWithUTF8String:message.voice.utf8().get_data()]]];
+ if (message.rate > 1.f) {
+ [new_utterance setRate:Math::range_lerp(message.rate, 1.f, 10.f, AVSpeechUtteranceDefaultSpeechRate, AVSpeechUtteranceMaximumSpeechRate)];
+ } else if (message.rate < 1.f) {
+ [new_utterance setRate:Math::range_lerp(message.rate, 0.1f, 1.f, AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceDefaultSpeechRate)];
+ }
+ [new_utterance setPitchMultiplier:message.pitch];
+ [new_utterance setVolume:(Math::range_lerp(message.volume, 0.f, 100.f, 0.f, 1.f))];
+
+ ids[new_utterance] = message.id;
+ [av_synth speakUtterance:new_utterance];
+ } else {
+ NSSpeechSynthesizer *ns_synth = synth;
+ [ns_synth setObject:nil forProperty:NSSpeechResetProperty error:nil];
+ [ns_synth setVoice:[NSString stringWithUTF8String:message.voice.utf8().get_data()]];
+ int base_pitch = [[ns_synth objectForProperty:NSSpeechPitchBaseProperty error:nil] intValue];
+ [ns_synth setObject:[NSNumber numberWithInt:(base_pitch * (message.pitch / 2.f + 0.5f))] forProperty:NSSpeechPitchBaseProperty error:nullptr];
+ [ns_synth setVolume:(Math::range_lerp(message.volume, 0.f, 100.f, 0.f, 1.f))];
+ [ns_synth setRate:(message.rate * 200)];
+
+ last_utterance = message.id;
+ have_utterance = true;
+ [ns_synth startSpeakingString:[NSString stringWithUTF8String:message.text.utf8().get_data()]];
+ }
+ queue.pop_front();
+
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, message.id);
+ speaking = true;
+ }
+}
+
+- (void)pauseSpeaking {
+ if (@available(macOS 10.14, *)) {
+ AVSpeechSynthesizer *av_synth = synth;
+ [av_synth pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
+ } else {
+ NSSpeechSynthesizer *ns_synth = synth;
+ [ns_synth pauseSpeakingAtBoundary:NSSpeechImmediateBoundary];
+ }
+ paused = true;
+}
+
+- (void)resumeSpeaking {
+ if (@available(macOS 10.14, *)) {
+ AVSpeechSynthesizer *av_synth = synth;
+ [av_synth continueSpeaking];
+ } else {
+ NSSpeechSynthesizer *ns_synth = synth;
+ [ns_synth continueSpeaking];
+ }
+ paused = false;
+}
+
+- (void)stopSpeaking {
+ for (DisplayServer::TTSUtterance &message : queue) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
+ }
+ queue.clear();
+ if (@available(macOS 10.14, *)) {
+ AVSpeechSynthesizer *av_synth = synth;
+ [av_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
+ } else {
+ NSSpeechSynthesizer *ns_synth = synth;
+ if (have_utterance) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, last_utterance);
+ }
+ [ns_synth stopSpeaking];
+ }
+ have_utterance = false;
+ speaking = false;
+ paused = false;
+}
+
+- (bool)isSpeaking {
+ return speaking || (queue.size() > 0);
+}
+
+- (bool)isPaused {
+ if (@available(macOS 10.14, *)) {
+ AVSpeechSynthesizer *av_synth = synth;
+ return [av_synth isPaused];
+ } else {
+ return paused;
+ }
+}
+
+- (void)speak:(const String &)text voice:(const String &)voice volume:(int)volume pitch:(float)pitch rate:(float)rate utterance_id:(int)utterance_id interrupt:(bool)interrupt {
+ if (interrupt) {
+ [self stopSpeaking];
+ }
+
+ if (text.is_empty()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, utterance_id);
+ return;
+ }
+
+ DisplayServer::TTSUtterance message;
+ message.text = text;
+ message.voice = voice;
+ message.volume = CLAMP(volume, 0, 100);
+ message.pitch = CLAMP(pitch, 0.f, 2.f);
+ message.rate = CLAMP(rate, 0.1f, 10.f);
+ message.id = utterance_id;
+ queue.push_back(message);
+
+ if ([self isPaused]) {
+ [self resumeSpeaking];
+ } else {
+ [self update];
+ }
+}
+
+- (Array)getVoices {
+ Array list;
+ if (@available(macOS 10.14, *)) {
+ for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
+ NSString *voiceIdentifierString = [voice identifier];
+ NSString *voiceLocaleIdentifier = [voice language];
+ NSString *voiceName = [voice name];
+ Dictionary voice_d;
+ voice_d["name"] = String::utf8([voiceName UTF8String]);
+ voice_d["id"] = String::utf8([voiceIdentifierString UTF8String]);
+ voice_d["language"] = String::utf8([voiceLocaleIdentifier UTF8String]);
+ list.push_back(voice_d);
+ }
+ } else {
+ for (NSString *voiceIdentifierString in [NSSpeechSynthesizer availableVoices]) {
+ NSString *voiceLocaleIdentifier = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceLocaleIdentifier];
+ NSString *voiceName = [[NSSpeechSynthesizer attributesForVoice:voiceIdentifierString] objectForKey:NSVoiceName];
+ Dictionary voice_d;
+ voice_d["name"] = String([voiceName UTF8String]);
+ voice_d["id"] = String([voiceIdentifierString UTF8String]);
+ voice_d["language"] = String([voiceLocaleIdentifier UTF8String]);
+ list.push_back(voice_d);
+ }
+ }
+ return list;
+}
+
+@end
diff --git a/platform/windows/SCsub b/platform/windows/SCsub
index 76234c3065..7e412b140f 100644
--- a/platform/windows/SCsub
+++ b/platform/windows/SCsub
@@ -13,6 +13,7 @@ common_win = [
"display_server_windows.cpp",
"key_mapping_windows.cpp",
"joypad_windows.cpp",
+ "tts_windows.cpp",
"windows_terminal_logger.cpp",
"vulkan_context_win.cpp",
"gl_manager_windows.cpp",
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index 249a0d2e79..0b18fb74fb 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -252,6 +252,7 @@ def configure_msvc(env, manual_msvc_config):
"kernel32",
"ole32",
"oleaut32",
+ "sapi",
"user32",
"gdi32",
"IPHLPAPI",
@@ -426,6 +427,7 @@ def configure_mingw(env):
"ws2_32",
"kernel32",
"oleaut32",
+ "sapi",
"dinput8",
"dxguid",
"ksuser",
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index 31bad0f053..0412eb2d9c 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -84,6 +84,7 @@ bool DisplayServerWindows::has_feature(Feature p_feature) const {
case FEATURE_NATIVE_ICON:
case FEATURE_SWAP_BUFFERS:
case FEATURE_KEEP_SCREEN_ON:
+ case FEATURE_TEXT_TO_SPEECH:
return true;
default:
return false;
@@ -133,6 +134,41 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
}
}
+bool DisplayServerWindows::tts_is_speaking() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return tts->is_speaking();
+}
+
+bool DisplayServerWindows::tts_is_paused() const {
+ ERR_FAIL_COND_V(!tts, false);
+ return tts->is_paused();
+}
+
+Array DisplayServerWindows::tts_get_voices() const {
+ ERR_FAIL_COND_V(!tts, Array());
+ return tts->get_voices();
+}
+
+void DisplayServerWindows::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ ERR_FAIL_COND(!tts);
+ tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
+}
+
+void DisplayServerWindows::tts_pause() {
+ ERR_FAIL_COND(!tts);
+ tts->pause();
+}
+
+void DisplayServerWindows::tts_resume() {
+ ERR_FAIL_COND(!tts);
+ tts->resume();
+}
+
+void DisplayServerWindows::tts_stop() {
+ ERR_FAIL_COND(!tts);
+ tts->stop();
+}
+
void DisplayServerWindows::mouse_set_mode(MouseMode p_mode) {
_THREAD_SAFE_METHOD_
@@ -3497,6 +3533,9 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
rendering_driver = p_rendering_driver;
+ // Init TTS
+ tts = memnew(TTS_Windows);
+
// Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
if (wintab_lib) {
@@ -3739,4 +3778,8 @@ DisplayServerWindows::~DisplayServerWindows() {
gl_manager = nullptr;
}
#endif
+ if (tts) {
+ memdelete(tts);
+ }
+ CoUninitialize();
}
diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h
index fcf4b5a728..80faf71bd4 100644
--- a/platform/windows/display_server_windows.h
+++ b/platform/windows/display_server_windows.h
@@ -46,6 +46,7 @@
#include "servers/rendering/renderer_compositor.h"
#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
#include "servers/rendering_server.h"
+#include "tts_windows.h"
#ifdef XAUDIO2_ENABLED
#include "drivers/xaudio2/audio_driver_xaudio2.h"
@@ -320,6 +321,8 @@ class DisplayServerWindows : public DisplayServer {
String rendering_driver;
bool app_focused = false;
+ TTS_Windows *tts = nullptr;
+
struct WindowData {
HWND hWnd;
//layered window
@@ -454,6 +457,15 @@ public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
+ virtual bool tts_is_speaking() const override;
+ virtual bool tts_is_paused() const override;
+ virtual Array tts_get_voices() const override;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false) override;
+ virtual void tts_pause() override;
+ virtual void tts_resume() override;
+ virtual void tts_stop() override;
+
virtual void mouse_set_mode(MouseMode p_mode) override;
virtual MouseMode mouse_get_mode() const override;
diff --git a/platform/windows/export/export_plugin.cpp b/platform/windows/export/export_plugin.cpp
index 917a0af90b..b4d8ce64b2 100644
--- a/platform/windows/export/export_plugin.cpp
+++ b/platform/windows/export/export_plugin.cpp
@@ -54,16 +54,23 @@ Error EditorExportPlatformWindows::_export_debug_script(const Ref<EditorExportPr
}
Error EditorExportPlatformWindows::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
- Error err = EditorExportPlatformPC::export_project(p_preset, p_debug, p_path, p_flags);
-
- if (err != OK) {
- return err;
+ String pck_path = p_path;
+ if (p_preset->get("binary_format/embed_pck")) {
+ pck_path = p_path.get_basename() + ".tmp";
+ }
+ Error err = EditorExportPlatformPC::prepare_template(p_preset, p_debug, pck_path, p_flags);
+ if (p_preset->get("application/modify_resources") && err == OK) {
+ err = _rcedit_add_data(p_preset, pck_path);
+ }
+ if (err == OK) {
+ err = EditorExportPlatformPC::export_project_data(p_preset, p_debug, pck_path, p_flags);
}
-
- _rcedit_add_data(p_preset, p_path);
-
if (p_preset->get("codesign/enable") && err == OK) {
- err = _code_sign(p_preset, p_path);
+ err = _code_sign(p_preset, pck_path);
+ }
+ if (p_preset->get("binary_format/embed_pck") && err == OK) {
+ Ref<DirAccess> tmp_dir = DirAccess::create_for_path(p_path.get_base_dir());
+ err = tmp_dir->rename(pck_path, p_path);
}
String app_name;
@@ -117,6 +124,7 @@ void EditorExportPlatformWindows::get_export_options(List<ExportOption> *r_optio
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "codesign/description"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "codesign/custom_options"), PackedStringArray()));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "application/modify_resources"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_FILE, "*.ico"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_version", PROPERTY_HINT_PLACEHOLDER_TEXT, "1.0.0.0"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/product_version", PROPERTY_HINT_PLACEHOLDER_TEXT, "1.0.0.0"), ""));
@@ -127,17 +135,16 @@ void EditorExportPlatformWindows::get_export_options(List<ExportOption> *r_optio
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/trademarks"), ""));
}
-void EditorExportPlatformWindows::_rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
+Error EditorExportPlatformWindows::_rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
String rcedit_path = EditorSettings::get_singleton()->get("export/windows/rcedit");
- if (rcedit_path.is_empty()) {
- WARN_PRINT("The rcedit tool is not configured in the Editor Settings (Export > Windows > Rcedit). No custom icon or app information data will be embedded in the exported executable.");
- return;
+ if (rcedit_path != String() && !FileAccess::exists(rcedit_path)) {
+ ERR_PRINT("Could not find rcedit executable at " + rcedit_path + ", aborting.");
+ return ERR_FILE_NOT_FOUND;
}
- if (!FileAccess::exists(rcedit_path)) {
- ERR_PRINT("Could not find rcedit executable at " + rcedit_path + ", no icon or app information data will be included.");
- return;
+ if (rcedit_path == String()) {
+ rcedit_path = "rcedit"; // try to run rcedit from PATH
}
#ifndef WINDOWS_ENABLED
@@ -145,8 +152,8 @@ void EditorExportPlatformWindows::_rcedit_add_data(const Ref<EditorExportPreset>
String wine_path = EditorSettings::get_singleton()->get("export/windows/wine");
if (!wine_path.is_empty() && !FileAccess::exists(wine_path)) {
- ERR_PRINT("Could not find wine executable at " + wine_path + ", no icon or app information data will be included.");
- return;
+ ERR_PRINT("Could not find wine executable at " + wine_path + ", aborting.");
+ return ERR_FILE_NOT_FOUND;
}
if (wine_path.is_empty()) {
@@ -204,13 +211,22 @@ void EditorExportPlatformWindows::_rcedit_add_data(const Ref<EditorExportPreset>
args.push_back(trademarks);
}
-#ifdef WINDOWS_ENABLED
- OS::get_singleton()->execute(rcedit_path, args);
-#else
+#ifndef WINDOWS_ENABLED
// On non-Windows we need WINE to run rcedit
args.push_front(rcedit_path);
- OS::get_singleton()->execute(wine_path, args);
+ rcedit_path = wine_path;
#endif
+
+ String str;
+ Error err = OS::get_singleton()->execute(rcedit_path, args, &str, nullptr, true);
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Could not start rcedit executable, configure rcedit path in the Editor Settings (Export > Windows > Rcedit).");
+ print_line("rcedit (" + p_path + "): " + str);
+
+ if (str.find("Fatal error") != -1) {
+ return FAILED;
+ }
+
+ return OK;
}
Error EditorExportPlatformWindows::_code_sign(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
@@ -347,7 +363,7 @@ Error EditorExportPlatformWindows::_code_sign(const Ref<EditorExportPreset> &p_p
String str;
Error err = OS::get_singleton()->execute(signtool_path, args, &str, nullptr, true);
- ERR_FAIL_COND_V(err != OK, err);
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Could not start signtool executable, configure signtool path in the Editor Settings (Export > Windows > Signtool).");
print_line("codesign (" + p_path + "): " + str);
#ifndef WINDOWS_ENABLED
@@ -376,7 +392,7 @@ bool EditorExportPlatformWindows::can_export(const Ref<EditorExportPreset> &p_pr
bool valid = EditorExportPlatformPC::can_export(p_preset, err, r_missing_templates);
String rcedit_path = EditorSettings::get_singleton()->get("export/windows/rcedit");
- if (rcedit_path.is_empty()) {
+ if (p_preset->get("application/modify_resources") && rcedit_path.is_empty()) {
err += TTR("The rcedit tool must be configured in the Editor Settings (Export > Windows > Rcedit) to change the icon or app information data.") + "\n";
}
@@ -417,6 +433,10 @@ bool EditorExportPlatformWindows::can_export(const Ref<EditorExportPreset> &p_pr
Error EditorExportPlatformWindows::fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) const {
// Patch the header of the "pck" section in the PE file so that it corresponds to the embedded data
+ if (p_embedded_size + p_embedded_start >= 0x100000000) { // Check for total executable size
+ ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Windows executables cannot be >= 4 GiB.");
+ }
+
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ_WRITE);
if (f.is_null()) {
return ERR_CANT_OPEN;
diff --git a/platform/windows/export/export_plugin.h b/platform/windows/export/export_plugin.h
index 39d1cf4c77..c33c7f1f63 100644
--- a/platform/windows/export/export_plugin.h
+++ b/platform/windows/export/export_plugin.h
@@ -38,7 +38,7 @@
#include "platform/windows/logo.gen.h"
class EditorExportPlatformWindows : public EditorExportPlatformPC {
- void _rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path);
+ Error _rcedit_add_data(const Ref<EditorExportPreset> &p_preset, const String &p_path);
Error _code_sign(const Ref<EditorExportPreset> &p_preset, const String &p_path);
Error _export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path);
diff --git a/platform/windows/godot_windows.cpp b/platform/windows/godot_windows.cpp
index ad4e3ae77c..8de3ef294a 100644
--- a/platform/windows/godot_windows.cpp
+++ b/platform/windows/godot_windows.cpp
@@ -39,7 +39,18 @@
#ifndef TOOLS_ENABLED
#if defined _MSC_VER
#pragma section("pck", read)
-__declspec(allocate("pck")) static const char dummy[8] = { 0 };
+__declspec(allocate("pck")) static char dummy[8] = { 0 };
+
+// Dummy function to prevent LTO from discarding "pck" section.
+extern "C" char *__cdecl pck_section_dummy_call() {
+ return &dummy[0];
+};
+#if defined _AMD64_
+#pragma comment(linker, "/include:pck_section_dummy_call")
+#elif defined _X86_
+#pragma comment(linker, "/include:_pck_section_dummy_call")
+#endif
+
#elif defined __GNUC__
static const char dummy[8] __attribute__((section("pck"), used)) = { 0 };
#endif
@@ -140,11 +151,6 @@ int widechar_main(int argc, wchar_t **argv) {
setlocale(LC_CTYPE, "");
-#ifndef TOOLS_ENABLED
- // Workaround to prevent LTCG (MSVC LTO) from removing "pck" section
- const char *dummy_guard = dummy;
-#endif
-
char **argv_utf8 = new char *[argc];
for (int i = 0; i < argc; ++i) {
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index b4669e452a..8755bc65dc 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -686,6 +686,58 @@ MainLoop *OS_Windows::get_main_loop() const {
return main_loop;
}
+uint64_t OS_Windows::get_embedded_pck_offset() const {
+ Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
+ if (f.is_null()) {
+ return 0;
+ }
+
+ // Process header.
+ {
+ f->seek(0x3c);
+ uint32_t pe_pos = f->get_32();
+
+ f->seek(pe_pos);
+ uint32_t magic = f->get_32();
+ if (magic != 0x00004550) {
+ return 0;
+ }
+ }
+
+ int num_sections;
+ {
+ int64_t header_pos = f->get_position();
+
+ f->seek(header_pos + 2);
+ num_sections = f->get_16();
+ f->seek(header_pos + 16);
+ uint16_t opt_header_size = f->get_16();
+
+ // Skip rest of header + optional header to go to the section headers.
+ f->seek(f->get_position() + 2 + opt_header_size);
+ }
+ int64_t section_table_pos = f->get_position();
+
+ // Search for the "pck" section.
+ int64_t off = 0;
+ for (int i = 0; i < num_sections; ++i) {
+ int64_t section_header_pos = section_table_pos + i * 40;
+ f->seek(section_header_pos);
+
+ uint8_t section_name[9];
+ f->get_buffer(section_name, 8);
+ section_name[8] = '\0';
+
+ if (strcmp((char *)section_name, "pck") == 0) {
+ f->seek(section_header_pos + 20);
+ off = f->get_32();
+ break;
+ }
+ }
+
+ return off;
+}
+
String OS_Windows::get_config_path() const {
// The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
if (has_environment("XDG_CONFIG_HOME")) {
diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h
index adeecf37c5..370cb77fde 100644
--- a/platform/windows/os_windows.h
+++ b/platform/windows/os_windows.h
@@ -144,6 +144,8 @@ public:
virtual int get_processor_count() const override;
virtual String get_processor_name() const override;
+ virtual uint64_t get_embedded_pck_offset() const override;
+
virtual String get_config_path() const override;
virtual String get_data_path() const override;
virtual String get_cache_path() const override;
diff --git a/platform/windows/tts_windows.cpp b/platform/windows/tts_windows.cpp
new file mode 100644
index 0000000000..05249934ba
--- /dev/null
+++ b/platform/windows/tts_windows.cpp
@@ -0,0 +1,269 @@
+/*************************************************************************/
+/* tts_windows.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tts_windows.h"
+
+TTS_Windows *TTS_Windows::singleton = nullptr;
+
+void __stdcall TTS_Windows::speech_event_callback(WPARAM wParam, LPARAM lParam) {
+ TTS_Windows *tts = TTS_Windows::get_singleton();
+ SPEVENT event;
+ while (tts->synth->GetEvents(1, &event, NULL) == S_OK) {
+ if (tts->ids.has(event.ulStreamNum)) {
+ if (event.eEventId == SPEI_START_INPUT_STREAM) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, tts->ids[event.ulStreamNum].id);
+ } else if (event.eEventId == SPEI_END_INPUT_STREAM) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, tts->ids[event.ulStreamNum].id);
+ tts->ids.erase(event.ulStreamNum);
+ tts->_update_tts();
+ } else if (event.eEventId == SPEI_WORD_BOUNDARY) {
+ const Char16String &string = tts->ids[event.ulStreamNum].string;
+ int pos = 0;
+ for (int i = 0; i < MIN(event.lParam, string.length()); i++) {
+ char16_t c = string[i];
+ if ((c & 0xfffffc00) == 0xd800) {
+ i++;
+ }
+ pos++;
+ }
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, tts->ids[event.ulStreamNum].id, pos - tts->ids[event.ulStreamNum].offset);
+ }
+ }
+ }
+}
+
+void TTS_Windows::_update_tts() {
+ if (!is_speaking() && !paused && queue.size() > 0) {
+ DisplayServer::TTSUtterance &message = queue.front()->get();
+
+ String text;
+ DWORD flags = SPF_ASYNC | SPF_PURGEBEFORESPEAK | SPF_IS_XML;
+ String pitch_tag = String("<pitch absmiddle=\"") + String::num_int64(message.pitch * 10 - 10, 10) + String("\">");
+ text = pitch_tag + message.text + String("</pitch>");
+
+ IEnumSpObjectTokens *cpEnum;
+ ISpObjectToken *cpVoiceToken;
+ ULONG ulCount = 0;
+ ULONG stream_number = 0;
+ ISpObjectTokenCategory *cpCategory;
+ HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
+ if (SUCCEEDED(hr)) {
+ hr = cpCategory->SetId(SPCAT_VOICES, false);
+ if (SUCCEEDED(hr)) {
+ hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
+ if (SUCCEEDED(hr)) {
+ hr = cpEnum->GetCount(&ulCount);
+ while (SUCCEEDED(hr) && ulCount--) {
+ wchar_t *w_id = 0L;
+ hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
+ cpVoiceToken->GetId(&w_id);
+ if (String::utf16((const char16_t *)w_id) == message.voice) {
+ synth->SetVoice(cpVoiceToken);
+ cpVoiceToken->Release();
+ break;
+ }
+ cpVoiceToken->Release();
+ }
+ cpEnum->Release();
+ }
+ }
+ cpCategory->Release();
+ }
+
+ UTData ut;
+ ut.string = text.utf16();
+ ut.offset = pitch_tag.length(); // Substract injected <pitch> tag offset.
+ ut.id = message.id;
+
+ synth->SetVolume(message.volume);
+ synth->SetRate(10.f * log10(message.rate) / log10(3.f));
+ synth->Speak((LPCWSTR)ut.string.get_data(), flags, &stream_number);
+
+ ids[stream_number] = ut;
+
+ queue.pop_front();
+ }
+}
+
+bool TTS_Windows::is_speaking() const {
+ ERR_FAIL_COND_V(!synth, false);
+
+ SPVOICESTATUS status;
+ synth->GetStatus(&status, nullptr);
+ return (status.dwRunningState == SPRS_IS_SPEAKING);
+}
+
+bool TTS_Windows::is_paused() const {
+ ERR_FAIL_COND_V(!synth, false);
+ return paused;
+}
+
+Array TTS_Windows::get_voices() const {
+ Array list;
+ IEnumSpObjectTokens *cpEnum;
+ ISpObjectToken *cpVoiceToken;
+ ISpDataKey *cpDataKeyAttribs;
+ ULONG ulCount = 0;
+ ISpObjectTokenCategory *cpCategory;
+ HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
+ if (SUCCEEDED(hr)) {
+ hr = cpCategory->SetId(SPCAT_VOICES, false);
+ if (SUCCEEDED(hr)) {
+ hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
+ if (SUCCEEDED(hr)) {
+ hr = cpEnum->GetCount(&ulCount);
+ while (SUCCEEDED(hr) && ulCount--) {
+ hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
+ HRESULT hr_attr = cpVoiceToken->OpenKey(SPTOKENKEY_ATTRIBUTES, &cpDataKeyAttribs);
+ if (SUCCEEDED(hr_attr)) {
+ wchar_t *w_id = nullptr;
+ wchar_t *w_lang = nullptr;
+ wchar_t *w_name = nullptr;
+ cpVoiceToken->GetId(&w_id);
+ cpDataKeyAttribs->GetStringValue(L"Language", &w_lang);
+ cpDataKeyAttribs->GetStringValue(nullptr, &w_name);
+ LCID locale = wcstol(w_lang, nullptr, 16);
+
+ int locale_chars = GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, nullptr, 0);
+ int region_chars = GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, nullptr, 0);
+ wchar_t *w_lang_code = new wchar_t[locale_chars];
+ wchar_t *w_reg_code = new wchar_t[region_chars];
+ GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, w_lang_code, locale_chars);
+ GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, w_reg_code, region_chars);
+
+ Dictionary voice_d;
+ voice_d["id"] = String::utf16((const char16_t *)w_id);
+ if (w_name) {
+ voice_d["name"] = String::utf16((const char16_t *)w_name);
+ } else {
+ voice_d["name"] = voice_d["id"].operator String().replace("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\", "");
+ }
+ voice_d["language"] = String::utf16((const char16_t *)w_lang_code) + "_" + String::utf16((const char16_t *)w_reg_code);
+ list.push_back(voice_d);
+
+ delete[] w_lang_code;
+ delete[] w_reg_code;
+
+ cpDataKeyAttribs->Release();
+ }
+ cpVoiceToken->Release();
+ }
+ cpEnum->Release();
+ }
+ }
+ cpCategory->Release();
+ }
+ return list;
+}
+
+void TTS_Windows::speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ ERR_FAIL_COND(!synth);
+ if (p_interrupt) {
+ stop();
+ }
+
+ if (p_text.is_empty()) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
+ return;
+ }
+
+ DisplayServer::TTSUtterance message;
+ message.text = p_text;
+ message.voice = p_voice;
+ message.volume = CLAMP(p_volume, 0, 100);
+ message.pitch = CLAMP(p_pitch, 0.f, 2.f);
+ message.rate = CLAMP(p_rate, 0.1f, 10.f);
+ message.id = p_utterance_id;
+ queue.push_back(message);
+
+ if (is_paused()) {
+ resume();
+ } else {
+ _update_tts();
+ }
+}
+
+void TTS_Windows::pause() {
+ ERR_FAIL_COND(!synth);
+ if (!paused) {
+ if (synth->Pause() == S_OK) {
+ paused = true;
+ }
+ }
+}
+
+void TTS_Windows::resume() {
+ ERR_FAIL_COND(!synth);
+ synth->Resume();
+ paused = false;
+}
+
+void TTS_Windows::stop() {
+ ERR_FAIL_COND(!synth);
+
+ SPVOICESTATUS status;
+ synth->GetStatus(&status, nullptr);
+ if (ids.has(status.ulCurrentStream)) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[status.ulCurrentStream].id);
+ ids.erase(status.ulCurrentStream);
+ }
+ for (DisplayServer::TTSUtterance &message : queue) {
+ DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
+ }
+ queue.clear();
+ synth->Speak(nullptr, SPF_PURGEBEFORESPEAK, nullptr);
+ synth->Resume();
+ paused = false;
+}
+
+TTS_Windows *TTS_Windows::get_singleton() {
+ return singleton;
+}
+
+TTS_Windows::TTS_Windows() {
+ singleton = this;
+ CoInitialize(nullptr);
+
+ if (SUCCEEDED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&synth))) {
+ ULONGLONG event_mask = SPFEI(SPEI_END_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_WORD_BOUNDARY);
+ synth->SetInterest(event_mask, event_mask);
+ synth->SetNotifyCallbackFunction(&speech_event_callback, (WPARAM)(this), 0);
+ print_verbose("Text-to-Speech: SAPI initialized.");
+ } else {
+ print_verbose("Text-to-Speech: Cannot initialize ISpVoice!");
+ }
+}
+
+TTS_Windows::~TTS_Windows() {
+ if (synth) {
+ synth->Release();
+ }
+ singleton = nullptr;
+}
diff --git a/platform/windows/tts_windows.h b/platform/windows/tts_windows.h
new file mode 100644
index 0000000000..5da404baf9
--- /dev/null
+++ b/platform/windows/tts_windows.h
@@ -0,0 +1,80 @@
+/*************************************************************************/
+/* tts_windows.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TTS_WINDOWS_H
+#define TTS_WINDOWS_H
+
+#include "core/string/ustring.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/variant/array.h"
+#include "servers/display_server.h"
+
+#include <objbase.h>
+#include <sapi.h>
+#include <wchar.h>
+#include <winnls.h>
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+class TTS_Windows {
+ List<DisplayServer::TTSUtterance> queue;
+ ISpVoice *synth = nullptr;
+ bool paused = false;
+ struct UTData {
+ Char16String string;
+ int offset;
+ int id;
+ };
+ Map<ULONG, UTData> ids;
+
+ static void __stdcall speech_event_callback(WPARAM wParam, LPARAM lParam);
+ void _update_tts();
+
+ static TTS_Windows *singleton;
+
+public:
+ static TTS_Windows *get_singleton();
+
+ bool is_speaking() const;
+ bool is_paused() const;
+ Array get_voices() const;
+
+ void speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false);
+ void pause();
+ void resume();
+ void stop();
+
+ TTS_Windows();
+ ~TTS_Windows();
+};
+
+#endif // TTS_WINDOWS_H
diff --git a/scene/2d/gpu_particles_2d.cpp b/scene/2d/gpu_particles_2d.cpp
index c69eeb52a8..04518dff97 100644
--- a/scene/2d/gpu_particles_2d.cpp
+++ b/scene/2d/gpu_particles_2d.cpp
@@ -287,6 +287,15 @@ bool GPUParticles2D::get_fractional_delta() const {
return fractional_delta;
}
+void GPUParticles2D::set_interpolate(bool p_enable) {
+ interpolate = p_enable;
+ RS::get_singleton()->particles_set_interpolate(particles, p_enable);
+}
+
+bool GPUParticles2D::get_interpolate() const {
+ return interpolate;
+}
+
TypedArray<String> GPUParticles2D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
@@ -543,6 +552,7 @@ void GPUParticles2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_use_local_coordinates", "enable"), &GPUParticles2D::set_use_local_coordinates);
ClassDB::bind_method(D_METHOD("set_fixed_fps", "fps"), &GPUParticles2D::set_fixed_fps);
ClassDB::bind_method(D_METHOD("set_fractional_delta", "enable"), &GPUParticles2D::set_fractional_delta);
+ ClassDB::bind_method(D_METHOD("set_interpolate", "enable"), &GPUParticles2D::set_interpolate);
ClassDB::bind_method(D_METHOD("set_process_material", "material"), &GPUParticles2D::set_process_material);
ClassDB::bind_method(D_METHOD("set_speed_scale", "scale"), &GPUParticles2D::set_speed_scale);
ClassDB::bind_method(D_METHOD("set_collision_base_size", "size"), &GPUParticles2D::set_collision_base_size);
@@ -558,6 +568,7 @@ void GPUParticles2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_use_local_coordinates"), &GPUParticles2D::get_use_local_coordinates);
ClassDB::bind_method(D_METHOD("get_fixed_fps"), &GPUParticles2D::get_fixed_fps);
ClassDB::bind_method(D_METHOD("get_fractional_delta"), &GPUParticles2D::get_fractional_delta);
+ ClassDB::bind_method(D_METHOD("get_interpolate"), &GPUParticles2D::get_interpolate);
ClassDB::bind_method(D_METHOD("get_process_material"), &GPUParticles2D::get_process_material);
ClassDB::bind_method(D_METHOD("get_speed_scale"), &GPUParticles2D::get_speed_scale);
ClassDB::bind_method(D_METHOD("get_collision_base_size"), &GPUParticles2D::get_collision_base_size);
@@ -601,6 +612,7 @@ void GPUParticles2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "explosiveness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_explosiveness_ratio", "get_explosiveness_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "randomness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_randomness_ratio", "get_randomness_ratio");
ADD_PROPERTY(PropertyInfo(Variant::INT, "fixed_fps", PROPERTY_HINT_RANGE, "0,1000,1"), "set_fixed_fps", "get_fixed_fps");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interpolate"), "set_interpolate", "get_interpolate");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "fract_delta"), "set_fractional_delta", "get_fractional_delta");
ADD_GROUP("Collision", "collision_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_base_size", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater"), "set_collision_base_size", "get_collision_base_size");
@@ -644,6 +656,7 @@ GPUParticles2D::GPUParticles2D() {
set_lifetime(1);
set_fixed_fps(0);
set_fractional_delta(true);
+ set_interpolate(true);
set_pre_process_time(0);
set_explosiveness_ratio(0);
set_randomness_ratio(0);
diff --git a/scene/2d/gpu_particles_2d.h b/scene/2d/gpu_particles_2d.h
index fc95ae27b2..852270dd3c 100644
--- a/scene/2d/gpu_particles_2d.h
+++ b/scene/2d/gpu_particles_2d.h
@@ -58,6 +58,7 @@ private:
bool local_coords;
int fixed_fps;
bool fractional_delta;
+ bool interpolate = true;
#ifdef TOOLS_ENABLED
bool show_visibility_rect;
#endif
@@ -133,6 +134,9 @@ public:
void set_fractional_delta(bool p_enable);
bool get_fractional_delta() const;
+ void set_interpolate(bool p_enable);
+ bool get_interpolate() const;
+
void set_draw_order(DrawOrder p_order);
DrawOrder get_draw_order() const;
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index aa68349329..a21cb7db62 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -311,7 +311,7 @@ void PathFollow2D::set_offset(real_t p_offset) {
if (path->get_curve().is_valid()) {
real_t path_length = path->get_curve()->get_baked_length();
- if (loop) {
+ if (loop && path_length) {
offset = Math::fposmod(offset, path_length);
if (!Math::is_zero_approx(p_offset) && Math::is_zero_approx(offset)) {
offset = path_length;
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index c0f2b6f07e..749754e6c5 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -58,7 +58,11 @@ Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_distance, bool p
PhysicsServer2D::MotionParameters parameters(get_global_transform(), p_distance, p_margin);
PhysicsServer2D::MotionResult result;
- if (move_and_collide(parameters, result, p_test_only)) {
+
+ bool collided = move_and_collide(parameters, result, p_test_only);
+
+ // Don't report collision when the whole motion is done.
+ if (collided && result.collision_safe_fraction < 1) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
motion_cache.instantiate();
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index cbbadf1178..cab57146b1 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -2143,7 +2143,7 @@ void TileMap::set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPat
TypedArray<Vector2i> used_cells = p_pattern->get_used_cells();
for (int i = 0; i < used_cells.size(); i++) {
Vector2i coords = map_pattern(p_position, used_cells[i], p_pattern);
- set_cell(p_layer, coords, p_pattern->get_cell_source_id(coords), p_pattern->get_cell_atlas_coords(coords), p_pattern->get_cell_alternative_tile(coords));
+ set_cell(p_layer, coords, p_pattern->get_cell_source_id(used_cells[i]), p_pattern->get_cell_atlas_coords(used_cells[i]), p_pattern->get_cell_alternative_tile(used_cells[i]));
}
}
@@ -2512,10 +2512,10 @@ void TileMap::_set_tile_data(int p_layer, const Vector<int> &p_data) {
uint32_t v = decode_uint32(&local[4]);
// Extract the transform flags that used to be in the tilemap.
- bool flip_h = v & (1 << 29);
- bool flip_v = v & (1 << 30);
- bool transpose = v & (1 << 31);
- v &= (1 << 29) - 1;
+ bool flip_h = v & (1UL << 29);
+ bool flip_v = v & (1UL << 30);
+ bool transpose = v & (1UL << 31);
+ v &= (1UL << 29) - 1;
// Extract autotile/atlas coords.
int16_t coord_x = 0;
diff --git a/scene/3d/label_3d.cpp b/scene/3d/label_3d.cpp
index 7dc90da4be..3750249d59 100644
--- a/scene/3d/label_3d.cpp
+++ b/scene/3d/label_3d.cpp
@@ -90,6 +90,9 @@ void Label3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_pixel_size", "pixel_size"), &Label3D::set_pixel_size);
ClassDB::bind_method(D_METHOD("get_pixel_size"), &Label3D::get_pixel_size);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Label3D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Label3D::get_offset);
+
ClassDB::bind_method(D_METHOD("set_draw_flag", "flag", "enabled"), &Label3D::set_draw_flag);
ClassDB::bind_method(D_METHOD("get_draw_flag", "flag"), &Label3D::get_draw_flag);
@@ -112,6 +115,7 @@ void Label3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("_im_update"), &Label3D::_im_update);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pixel_size", PROPERTY_HINT_RANGE, "0.0001,128,0.0001"), "set_pixel_size", "get_pixel_size");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
ADD_GROUP("Flags", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "billboard", PROPERTY_HINT_ENUM, "Disabled,Enabled,Y-Billboard"), "set_billboard_mode", "get_billboard_mode");
@@ -304,7 +308,7 @@ Ref<TriangleMesh> Label3D::generate_triangle_mesh() const {
} break;
}
- Rect2 final_rect = Rect2(offset, Size2(max_line_w, total_h));
+ Rect2 final_rect = Rect2(offset + lbl_offset, Size2(max_line_w, total_h));
if (final_rect.size.x == 0 || final_rect.size.y == 0) {
return Ref<TriangleMesh>();
@@ -551,7 +555,7 @@ void Label3D::_shape() {
} break;
}
- Vector2 offset = Vector2(0, vbegin);
+ Vector2 offset = Vector2(0, vbegin + lbl_offset.y * pixel_size);
for (int i = 0; i < lines_rid.size(); i++) {
const Glyph *glyphs = TS->shaped_text_get_glyphs(lines_rid[i]);
int gl_size = TS->shaped_text_get_glyph_count(lines_rid[i]);
@@ -569,6 +573,7 @@ void Label3D::_shape() {
offset.x = -line_width;
} break;
}
+ offset.x += lbl_offset.x * pixel_size;
offset.y -= (TS->shaped_text_get_ascent(lines_rid[i]) + font->get_spacing(TextServer::SPACING_TOP)) * pixel_size;
if (outline_modulate.a != 0.0 && outline_size > 0) {
@@ -863,6 +868,17 @@ real_t Label3D::get_pixel_size() const {
return pixel_size;
}
+void Label3D::set_offset(const Point2 &p_offset) {
+ if (lbl_offset != p_offset) {
+ lbl_offset = p_offset;
+ _queue_update();
+ }
+}
+
+Point2 Label3D::get_offset() const {
+ return lbl_offset;
+}
+
void Label3D::set_line_spacing(float p_line_spacing) {
if (line_spacing != p_line_spacing) {
line_spacing = p_line_spacing;
diff --git a/scene/3d/label_3d.h b/scene/3d/label_3d.h
index cbc5c3c649..22a99987ef 100644
--- a/scene/3d/label_3d.h
+++ b/scene/3d/label_3d.h
@@ -97,6 +97,7 @@ private:
int font_size = 16;
Ref<Font> font_override;
Color modulate = Color(1, 1, 1, 1);
+ Point2 lbl_offset;
int outline_size = 0;
Color outline_modulate = Color(0, 0, 0, 1);
@@ -199,6 +200,9 @@ public:
void set_pixel_size(real_t p_amount);
real_t get_pixel_size() const;
+ void set_offset(const Point2 &p_offset);
+ Point2 get_offset() const;
+
void set_draw_flag(DrawFlags p_flag, bool p_enable);
bool get_draw_flag(DrawFlags p_flag) const;
diff --git a/scene/3d/path_3d.cpp b/scene/3d/path_3d.cpp
index 7a5cb26a29..4981125057 100644
--- a/scene/3d/path_3d.cpp
+++ b/scene/3d/path_3d.cpp
@@ -310,7 +310,7 @@ void PathFollow3D::set_offset(real_t p_offset) {
if (path->get_curve().is_valid()) {
real_t path_length = path->get_curve()->get_baked_length();
- if (loop) {
+ if (loop && path_length) {
offset = Math::fposmod(offset, path_length);
if (!Math::is_zero_approx(p_offset) && Math::is_zero_approx(offset)) {
offset = path_length;
diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp
index dee76aef10..ecc00fe765 100644
--- a/scene/3d/physics_body_3d.cpp
+++ b/scene/3d/physics_body_3d.cpp
@@ -96,7 +96,11 @@ Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_distance, bool p
parameters.max_collisions = p_max_collisions;
PhysicsServer3D::MotionResult result;
- if (move_and_collide(parameters, result, p_test_only)) {
+
+ bool collided = move_and_collide(parameters, result, p_test_only);
+
+ // Don't report collision when the whole motion is done.
+ if (collided && result.collision_safe_fraction < 1) {
// Create a new instance when the cached reference is invalid or still in use in script.
if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
motion_cache.instantiate();
diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp
index 783edf7fc6..9e403a6ecd 100644
--- a/scene/3d/skeleton_3d.cpp
+++ b/scene/3d/skeleton_3d.cpp
@@ -509,6 +509,7 @@ void Skeleton3D::add_bone(const String &p_name) {
bones.push_back(b);
process_order_dirty = true;
version++;
+ rest_dirty = true;
_make_dirty();
update_gizmos();
}
@@ -567,6 +568,7 @@ void Skeleton3D::set_bone_parent(int p_bone, int p_parent) {
bones.write[p_bone].parent = p_parent;
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
@@ -585,6 +587,7 @@ void Skeleton3D::unparent_bone_and_rest(int p_bone) {
bones.write[p_bone].parent = -1;
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
@@ -607,6 +610,7 @@ void Skeleton3D::set_bone_children(int p_bone, Vector<int> p_children) {
bones.write[p_bone].child_bones = p_children;
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
@@ -616,6 +620,7 @@ void Skeleton3D::add_bone_child(int p_bone, int p_child) {
bones.write[p_bone].child_bones.push_back(p_child);
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
@@ -631,6 +636,7 @@ void Skeleton3D::remove_bone_child(int p_bone, int p_child) {
}
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
@@ -643,6 +649,7 @@ void Skeleton3D::set_bone_rest(int p_bone, const Transform3D &p_rest) {
ERR_FAIL_INDEX(p_bone, bone_size);
bones.write[p_bone].rest = p_rest;
+ rest_dirty = true;
_make_dirty();
}
Transform3D Skeleton3D::get_bone_rest(int p_bone) const {
@@ -651,6 +658,14 @@ Transform3D Skeleton3D::get_bone_rest(int p_bone) const {
return bones[p_bone].rest;
}
+Transform3D Skeleton3D::get_bone_global_rest(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
+ if (rest_dirty) {
+ const_cast<Skeleton3D *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
+ }
+ return bones[p_bone].global_rest;
+}
void Skeleton3D::set_bone_enabled(int p_bone, bool p_enabled) {
const int bone_size = bones.size();
@@ -1058,6 +1073,9 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) {
b.pose_global_no_override = b.pose_global;
}
}
+ if (rest_dirty) {
+ b.global_rest = b.parent >= 0 ? bonesptr[b.parent].global_rest * b.rest : b.rest;
+ }
if (b.local_pose_override_amount >= CMP_EPSILON) {
Transform3D override_local_pose;
@@ -1088,6 +1106,7 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) {
emit_signal(SceneStringNames::get_singleton()->bone_pose_changed, current_bone_idx);
}
+ rest_dirty = false;
}
// Helper functions
@@ -1206,6 +1225,7 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bone_rest", "bone_idx"), &Skeleton3D::get_bone_rest);
ClassDB::bind_method(D_METHOD("set_bone_rest", "bone_idx", "rest"), &Skeleton3D::set_bone_rest);
+ ClassDB::bind_method(D_METHOD("get_bone_global_rest", "bone_idx"), &Skeleton3D::get_bone_global_rest);
ClassDB::bind_method(D_METHOD("create_skin_from_rest_transforms"), &Skeleton3D::create_skin_from_rest_transforms);
ClassDB::bind_method(D_METHOD("register_skin", "skin"), &Skeleton3D::register_skin);
diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h
index 279c3e49a2..f8c9fa2c96 100644
--- a/scene/3d/skeleton_3d.h
+++ b/scene/3d/skeleton_3d.h
@@ -77,6 +77,7 @@ private:
int parent;
Transform3D rest;
+ Transform3D global_rest;
_FORCE_INLINE_ void update_pose_cache() {
if (pose_cache_dirty) {
@@ -142,6 +143,7 @@ private:
void _make_dirty();
bool dirty = false;
+ bool rest_dirty = false;
bool show_rest_only = false;
@@ -198,6 +200,7 @@ public:
void set_bone_rest(int p_bone, const Transform3D &p_rest);
Transform3D get_bone_rest(int p_bone) const;
+ Transform3D get_bone_global_rest(int p_bone) const;
Transform3D get_bone_global_pose(int p_bone) const;
Transform3D get_bone_global_pose_no_override(int p_bone) const;
diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp
index f29b060069..5e1f9d047f 100644
--- a/scene/3d/skeleton_ik_3d.cpp
+++ b/scene/3d/skeleton_ik_3d.cpp
@@ -140,7 +140,7 @@ void FabrikInverseKinematic::solve_simple(Task *p_task, bool p_solve_magnet, Vec
}
}
-void FabrikInverseKinematic::solve_simple_backwards(Chain &r_chain, bool p_solve_magnet) {
+void FabrikInverseKinematic::solve_simple_backwards(const Chain &r_chain, bool p_solve_magnet) {
if (p_solve_magnet && !r_chain.middle_chain_item) {
return;
}
diff --git a/scene/3d/skeleton_ik_3d.h b/scene/3d/skeleton_ik_3d.h
index 3ced5c49d3..0f656187de 100644
--- a/scene/3d/skeleton_ik_3d.h
+++ b/scene/3d/skeleton_ik_3d.h
@@ -103,7 +103,7 @@ private:
static void solve_simple(Task *p_task, bool p_solve_magnet, Vector3 p_origin_pos);
/// Special solvers that solve only chains with one end effector
- static void solve_simple_backwards(Chain &r_chain, bool p_solve_magnet);
+ static void solve_simple_backwards(const Chain &r_chain, bool p_solve_magnet);
static void solve_simple_forwards(Chain &r_chain, bool p_solve_magnet, Vector3 p_origin_pos);
public:
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index d541dd5f37..6a8fa9327c 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -563,7 +563,7 @@ void Sprite3D::_draw() {
value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
if (t.d > 0) {
- value |= 3 << 30;
+ value |= 3UL << 30;
}
v_tangent = value;
}
@@ -926,7 +926,7 @@ void AnimatedSprite3D::_draw() {
value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
if (t.d > 0) {
- value |= 3 << 30;
+ value |= 3UL << 30;
}
v_tangent = value;
}
diff --git a/scene/3d/voxelizer.cpp b/scene/3d/voxelizer.cpp
index bda3868fbb..d6ac5ccf30 100644
--- a/scene/3d/voxelizer.cpp
+++ b/scene/3d/voxelizer.cpp
@@ -777,8 +777,8 @@ Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
/* dt of 1d function using squared distance */
static void edt(float *f, int stride, int n) {
float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
- int *v = (int *)&(d[n]);
- float *z = (float *)&v[n];
+ int *v = reinterpret_cast<int *>(&(d[n]));
+ float *z = reinterpret_cast<float *>(&v[n]);
int k = 0;
v[0] = 0;
diff --git a/scene/animation/animation_node_state_machine.cpp b/scene/animation/animation_node_state_machine.cpp
index 5ea7f4b7d9..4f94ec3584 100644
--- a/scene/animation/animation_node_state_machine.cpp
+++ b/scene/animation/animation_node_state_machine.cpp
@@ -185,8 +185,6 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
return true; //nothing to do
}
- loops_current = 0; // reset loops, so fade does not happen immediately
-
Vector2 current_pos = p_state_machine->states[current].position;
Vector2 target_pos = p_state_machine->states[p_travel].position;
@@ -352,7 +350,6 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, 1.0, AnimationNode::FILTER_IGNORE, false);
pos_current = 0;
- loops_current = 0;
}
if (!p_state_machine->states.has(current)) {
@@ -388,12 +385,8 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
{ //advance and loop check
-
float next_pos = len_current - rem;
-
- if (next_pos < pos_current) {
- loops_current++;
- }
+ end_loop = next_pos < pos_current;
pos_current = next_pos; //looped
}
@@ -443,15 +436,15 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
bool goto_next = false;
if (switch_mode == AnimationNodeStateMachineTransition::SWITCH_MODE_AT_END) {
- goto_next = next_xfade >= (len_current - pos_current) || loops_current > 0;
- if (loops_current > 0) {
+ goto_next = next_xfade >= (len_current - pos_current) || end_loop;
+ if (end_loop) {
next_xfade = 0;
}
} else {
goto_next = fading_from == StringName();
}
- if (goto_next) { //loops should be used because fade time may be too small or zero and animation may have looped
+ if (goto_next) { //end_loop should be used because fade time may be too small or zero and animation may have looped
if (next_xfade) {
//time to fade, baby
@@ -478,7 +471,6 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
rem = len_current; //so it does not show 0 on transition
- loops_current = 0;
}
}
diff --git a/scene/animation/animation_node_state_machine.h b/scene/animation/animation_node_state_machine.h
index 3bae0fcffa..96add7f538 100644
--- a/scene/animation/animation_node_state_machine.h
+++ b/scene/animation/animation_node_state_machine.h
@@ -97,7 +97,7 @@ class AnimationNodeStateMachinePlayback : public Resource {
float len_current = 0.0;
float pos_current = 0.0;
- int loops_current = 0;
+ bool end_loop = false;
StringName current;
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index f5236adbad..424716e002 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -541,9 +541,9 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
player->get_animation_list(&sname);
Ref<Animation> reset_anim;
- bool has_reset_anim = player->has_animation("RESET");
+ bool has_reset_anim = player->has_animation(SceneStringNames::get_singleton()->RESET);
if (has_reset_anim) {
- reset_anim = player->get_animation("RESET");
+ reset_anim = player->get_animation(SceneStringNames::get_singleton()->RESET);
}
for (const StringName &E : sname) {
Ref<Animation> anim = player->get_animation(E);
diff --git a/scene/animation/root_motion_view.cpp b/scene/animation/root_motion_view.cpp
index 42adc1ea02..3192f5f7cd 100644
--- a/scene/animation/root_motion_view.cpp
+++ b/scene/animation/root_motion_view.cpp
@@ -114,9 +114,8 @@ void RootMotionView::_notification(int p_what) {
first = false;
transform.orthonormalize(); //don't want scale, too imprecise
- transform.affine_invert();
- accumulated = transform * accumulated;
+ accumulated = accumulated * transform;
accumulated.origin.x = Math::fposmod(accumulated.origin.x, cell_size);
if (zero_y) {
accumulated.origin.y = 0;
@@ -134,9 +133,9 @@ void RootMotionView::_notification(int p_what) {
Vector3 from(i * cell_size, 0, j * cell_size);
Vector3 from_i((i + 1) * cell_size, 0, j * cell_size);
Vector3 from_j(i * cell_size, 0, (j + 1) * cell_size);
- from = accumulated.xform(from);
- from_i = accumulated.xform(from_i);
- from_j = accumulated.xform(from_j);
+ from = accumulated.xform_inv(from);
+ from_i = accumulated.xform_inv(from_i);
+ from_j = accumulated.xform_inv(from_j);
Color c = color, c_i = color, c_j = color;
c.a *= MAX(0, 1.0 - from.length() / radius);
diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp
index ccc878a6ec..9bd1624e89 100644
--- a/scene/animation/tween.cpp
+++ b/scene/animation/tween.cpp
@@ -152,10 +152,6 @@ bool Tween::is_running() {
return running;
}
-void Tween::set_valid(bool p_valid) {
- valid = p_valid;
-}
-
bool Tween::is_valid() {
return valid;
}
@@ -648,7 +644,7 @@ void Tween::_bind_methods() {
ClassDB::bind_method(D_METHOD("parallel"), &Tween::parallel);
ClassDB::bind_method(D_METHOD("chain"), &Tween::chain);
- ClassDB::bind_method(D_METHOD("interpolate_value", "initial_value", "delta_value", "elapsed_time", "duration", "trans_type", "ease_type"), &Tween::interpolate_variant);
+ ClassDB::bind_static_method("Tween", D_METHOD("interpolate_value", "initial_value", "delta_value", "elapsed_time", "duration", "trans_type", "ease_type"), &Tween::interpolate_variant);
ADD_SIGNAL(MethodInfo("step_finished", PropertyInfo(Variant::INT, "idx")));
ADD_SIGNAL(MethodInfo("loop_finished", PropertyInfo(Variant::INT, "loop_count")));
@@ -679,6 +675,14 @@ void Tween::_bind_methods() {
BIND_ENUM_CONSTANT(EASE_OUT_IN);
}
+Tween::Tween() {
+ ERR_FAIL_MSG("Tween can't be created directly. Use create_tween() method.");
+}
+
+Tween::Tween(bool p_valid) {
+ valid = p_valid;
+}
+
Ref<PropertyTweener> PropertyTweener::from(Variant p_value) {
initial_val = p_value;
do_continue = false;
@@ -846,7 +850,7 @@ bool CallbackTweener::step(float &r_delta) {
Callable::CallError ce;
callback.call(nullptr, 0, result, ce);
if (ce.error != Callable::CallError::CALL_OK) {
- ERR_FAIL_V_MSG(false, "Error calling method from CallbackTweener: " + Variant::get_call_error_text(this, callback.get_method(), nullptr, 0, ce));
+ ERR_FAIL_V_MSG(false, "Error calling method from CallbackTweener: " + Variant::get_call_error_text(callback.get_object(), callback.get_method(), nullptr, 0, ce));
}
finished = true;
@@ -917,7 +921,7 @@ bool MethodTweener::step(float &r_delta) {
Callable::CallError ce;
callback.call(argptr, 1, result, ce);
if (ce.error != Callable::CallError::CALL_OK) {
- ERR_FAIL_V_MSG(false, "Error calling method from MethodTweener: " + Variant::get_call_error_text(this, callback.get_method(), argptr, 1, ce));
+ ERR_FAIL_V_MSG(false, "Error calling method from MethodTweener: " + Variant::get_call_error_text(callback.get_object(), callback.get_method(), argptr, 1, ce));
}
if (time < duration) {
diff --git a/scene/animation/tween.h b/scene/animation/tween.h
index e28a499259..5c1567d510 100644
--- a/scene/animation/tween.h
+++ b/scene/animation/tween.h
@@ -139,7 +139,6 @@ public:
void kill();
bool is_running();
- void set_valid(bool p_valid);
bool is_valid();
void clear();
@@ -160,8 +159,8 @@ public:
Ref<Tween> parallel();
Ref<Tween> chain();
- real_t run_equation(TransitionType p_trans_type, EaseType p_ease_type, real_t t, real_t b, real_t c, real_t d);
- Variant interpolate_variant(Variant p_initial_val, Variant p_delta_val, float p_time, float p_duration, Tween::TransitionType p_trans, Tween::EaseType p_ease);
+ static real_t run_equation(TransitionType p_trans_type, EaseType p_ease_type, real_t t, real_t b, real_t c, real_t d);
+ static Variant interpolate_variant(Variant p_initial_val, Variant p_delta_val, float p_time, float p_duration, Tween::TransitionType p_trans, Tween::EaseType p_ease);
Variant calculate_delta_value(Variant p_intial_val, Variant p_final_val);
bool step(float p_delta);
@@ -169,7 +168,8 @@ public:
Node *get_bound_node() const;
float get_total_time() const;
- Tween() {}
+ Tween();
+ Tween(bool p_valid);
};
VARIANT_ENUM_CAST(Tween::TweenPauseMode);
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index d18a9a75de..fdcd7116f3 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -994,7 +994,8 @@ void CodeEdit::_new_line(bool p_split_current_line, bool p_above) {
}
/* Make sure this is the last char, trailing whitespace or comments are okay. */
- if (should_indent && (!is_whitespace(c) && is_in_comment(cl, cc) == -1)) {
+ /* Increment column for comments because the delimiter (#) should be ignored. */
+ if (should_indent && (!is_whitespace(c) && is_in_comment(cl, line_col + 1) == -1)) {
should_indent = false;
}
}
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 69c29a327a..8303d6db57 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -834,10 +834,10 @@ void PopupMenu::_notification(int p_what) {
// Set margin on the margin container
Ref<StyleBox> panel_style = get_theme_stylebox(SNAME("panel"));
- margin_container->add_theme_constant_override("margin_top", panel_style->get_margin(Side::SIDE_TOP));
- margin_container->add_theme_constant_override("margin_bottom", panel_style->get_margin(Side::SIDE_BOTTOM));
margin_container->add_theme_constant_override("margin_left", panel_style->get_margin(Side::SIDE_LEFT));
+ margin_container->add_theme_constant_override("margin_top", panel_style->get_margin(Side::SIDE_TOP));
margin_container->add_theme_constant_override("margin_right", panel_style->get_margin(Side::SIDE_RIGHT));
+ margin_container->add_theme_constant_override("margin_bottom", panel_style->get_margin(Side::SIDE_BOTTOM));
}
} break;
}
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 1cfe54155a..f1c0260dd5 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -653,21 +653,10 @@ void Node::rpcp(int p_peer_id, const StringName &p_method, const Variant **p_arg
}
Ref<MultiplayerAPI> Node::get_multiplayer() const {
- if (multiplayer.is_valid()) {
- return multiplayer;
- }
if (!is_inside_tree()) {
return Ref<MultiplayerAPI>();
}
- return get_tree()->get_multiplayer();
-}
-
-Ref<MultiplayerAPI> Node::get_custom_multiplayer() const {
- return multiplayer;
-}
-
-void Node::set_custom_multiplayer(Ref<MultiplayerAPI> p_multiplayer) {
- multiplayer = p_multiplayer;
+ return get_tree()->get_multiplayer(get_path());
}
Vector<Multiplayer::RPCConfig> Node::get_node_rpc_methods() const {
@@ -1373,9 +1362,39 @@ bool Node::has_node(const NodePath &p_path) const {
return get_node_or_null(p_path) != nullptr;
}
-TypedArray<Node> Node::find_nodes(const String &p_mask, const String &p_type, bool p_recursive, bool p_owned) const {
+// Finds the first child node (in tree order) whose name matches the given pattern.
+// Can be recursive or not, and limited to owned nodes.
+Node *Node::find_child(const String &p_pattern, bool p_recursive, bool p_owned) const {
+ ERR_FAIL_COND_V(p_pattern.is_empty(), nullptr);
+
+ Node *const *cptr = data.children.ptr();
+ int ccount = data.children.size();
+ for (int i = 0; i < ccount; i++) {
+ if (p_owned && !cptr[i]->data.owner) {
+ continue;
+ }
+ if (cptr[i]->data.name.operator String().match(p_pattern)) {
+ return cptr[i];
+ }
+
+ if (!p_recursive) {
+ continue;
+ }
+
+ Node *ret = cptr[i]->find_child(p_pattern, true, p_owned);
+ if (ret) {
+ return ret;
+ }
+ }
+ return nullptr;
+}
+
+// Finds child nodes based on their name using pattern matching, or class name,
+// or both (either pattern or type can be left empty).
+// Can be recursive or not, and limited to owned nodes.
+TypedArray<Node> Node::find_children(const String &p_pattern, const String &p_type, bool p_recursive, bool p_owned) const {
TypedArray<Node> ret;
- ERR_FAIL_COND_V(p_mask.is_empty() && p_type.is_empty(), ret);
+ ERR_FAIL_COND_V(p_pattern.is_empty() && p_type.is_empty(), ret);
Node *const *cptr = data.children.ptr();
int ccount = data.children.size();
@@ -1384,8 +1403,8 @@ TypedArray<Node> Node::find_nodes(const String &p_mask, const String &p_type, bo
continue;
}
- if (!p_mask.is_empty()) {
- if (!cptr[i]->data.name.operator String().match(p_mask)) {
+ if (!p_pattern.is_empty()) {
+ if (!cptr[i]->data.name.operator String().match(p_pattern)) {
continue;
} else if (p_type.is_empty()) {
ret.append(cptr[i]);
@@ -1407,7 +1426,7 @@ TypedArray<Node> Node::find_nodes(const String &p_mask, const String &p_type, bo
}
if (p_recursive) {
- ret.append_array(cptr[i]->find_nodes(p_mask, p_type, true, p_owned));
+ ret.append_array(cptr[i]->find_children(p_pattern, p_type, true, p_owned));
}
}
@@ -1418,10 +1437,10 @@ Node *Node::get_parent() const {
return data.parent;
}
-Node *Node::find_parent(const String &p_mask) const {
+Node *Node::find_parent(const String &p_pattern) const {
Node *p = data.parent;
while (p) {
- if (p->data.name.operator String().match(p_mask)) {
+ if (p->data.name.operator String().match(p_pattern)) {
return p;
}
p = p->data.parent;
@@ -1542,7 +1561,9 @@ void Node::_acquire_unique_name_in_owner() {
StringName key = StringName(UNIQUE_NODE_PREFIX + data.name.operator String());
Node **which = data.owner->data.owned_unique_nodes.getptr(key);
if (which != nullptr && *which != this) {
- WARN_PRINT(vformat(RTR("Setting node name '%s' to be unique within scene for '%s', but it's already claimed by '%s'. This node is no longer set unique."), get_name(), is_inside_tree() ? get_path() : data.owner->get_path_to(this), is_inside_tree() ? (*which)->get_path() : data.owner->get_path_to(*which)));
+ String which_path = is_inside_tree() ? (*which)->get_path() : data.owner->get_path_to(*which);
+ WARN_PRINT(vformat(RTR("Setting node name '%s' to be unique within scene for '%s', but it's already claimed by '%s'.\n'%s' is no longer set as having a unique name."),
+ get_name(), is_inside_tree() ? get_path() : data.owner->get_path_to(this), which_path, which_path));
data.unique_name_in_owner = false;
return;
}
@@ -2780,8 +2801,9 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_node", "path"), &Node::get_node);
ClassDB::bind_method(D_METHOD("get_node_or_null", "path"), &Node::get_node_or_null);
ClassDB::bind_method(D_METHOD("get_parent"), &Node::get_parent);
- ClassDB::bind_method(D_METHOD("find_nodes", "mask", "type", "recursive", "owned"), &Node::find_nodes, DEFVAL(""), DEFVAL(true), DEFVAL(true));
- ClassDB::bind_method(D_METHOD("find_parent", "mask"), &Node::find_parent);
+ ClassDB::bind_method(D_METHOD("find_child", "pattern", "recursive", "owned"), &Node::find_child, DEFVAL(true), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("find_children", "pattern", "type", "recursive", "owned"), &Node::find_children, DEFVAL(""), DEFVAL(true), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("find_parent", "pattern"), &Node::find_parent);
ClassDB::bind_method(D_METHOD("has_node_and_resource", "path"), &Node::has_node_and_resource);
ClassDB::bind_method(D_METHOD("get_node_and_resource", "path"), &Node::_get_node_and_resource);
@@ -2859,8 +2881,6 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_multiplayer_authority"), &Node::is_multiplayer_authority);
ClassDB::bind_method(D_METHOD("get_multiplayer"), &Node::get_multiplayer);
- ClassDB::bind_method(D_METHOD("get_custom_multiplayer"), &Node::get_custom_multiplayer);
- ClassDB::bind_method(D_METHOD("set_custom_multiplayer", "api"), &Node::set_custom_multiplayer);
ClassDB::bind_method(D_METHOD("rpc_config", "method", "rpc_mode", "call_local", "transfer_mode", "channel"), &Node::rpc_config, DEFVAL(false), DEFVAL(Multiplayer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
ClassDB::bind_method(D_METHOD("set_editor_description", "editor_description"), &Node::set_editor_description);
@@ -2872,8 +2892,6 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_unique_name_in_owner", "enable"), &Node::set_unique_name_in_owner);
ClassDB::bind_method(D_METHOD("is_unique_name_in_owner"), &Node::is_unique_name_in_owner);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "unique_name_in_owner", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_unique_name_in_owner", "is_unique_name_in_owner");
-
#ifdef TOOLS_ENABLED
ClassDB::bind_method(D_METHOD("_set_property_pinned", "property", "pinned"), &Node::set_property_pinned);
#endif
@@ -2964,10 +2982,10 @@ void Node::_bind_methods() {
ADD_SIGNAL(MethodInfo("child_exited_tree", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT, "Node")));
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_name", "get_name");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "unique_name_in_owner", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_unique_name_in_owner", "is_unique_name_in_owner");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "scene_file_path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_scene_file_path", "get_scene_file_path");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "owner", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_owner", "get_owner");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multiplayer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerAPI", PROPERTY_USAGE_NONE), "", "get_multiplayer");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "custom_multiplayer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerAPI", PROPERTY_USAGE_NONE), "set_custom_multiplayer", "get_custom_multiplayer");
ADD_GROUP("Process", "process_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "process_mode", PROPERTY_HINT_ENUM, "Inherit,Pausable,When Paused,Always,Disabled"), "set_process_mode", "get_process_mode");
diff --git a/scene/main/node.h b/scene/main/node.h
index 0973baf793..fb84aabb62 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -310,12 +310,13 @@ public:
bool has_node(const NodePath &p_path) const;
Node *get_node(const NodePath &p_path) const;
Node *get_node_or_null(const NodePath &p_path) const;
- TypedArray<Node> find_nodes(const String &p_mask, const String &p_type = "", bool p_recursive = true, bool p_owned = true) const;
+ Node *find_child(const String &p_pattern, bool p_recursive = true, bool p_owned = true) const;
+ TypedArray<Node> find_children(const String &p_pattern, const String &p_type = "", bool p_recursive = true, bool p_owned = true) const;
bool has_node_and_resource(const NodePath &p_path) const;
Node *get_node_and_resource(const NodePath &p_path, RES &r_res, Vector<StringName> &r_leftover_subpath, bool p_last_is_property = true) const;
Node *get_parent() const;
- Node *find_parent(const String &p_mask) const;
+ Node *find_parent(const String &p_pattern) const;
_FORCE_INLINE_ SceneTree *get_tree() const {
ERR_FAIL_COND_V(!data.tree, nullptr);
@@ -514,8 +515,6 @@ public:
void rpcp(int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount);
Ref<MultiplayerAPI> get_multiplayer() const;
- Ref<MultiplayerAPI> get_custom_multiplayer() const;
- void set_custom_multiplayer(Ref<MultiplayerAPI> p_multiplayer);
Node();
~Node();
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 151239c9e7..82f18d1a42 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -438,6 +438,10 @@ bool SceneTree::process(double p_time) {
if (multiplayer_poll) {
multiplayer->poll();
+ const NodePath *rpath = nullptr;
+ while ((rpath = custom_multiplayers.next(rpath))) {
+ custom_multiplayers[*rpath]->poll();
+ }
}
emit_signal(SNAME("process_frame"));
@@ -1113,9 +1117,7 @@ Ref<SceneTreeTimer> SceneTree::create_timer(double p_delay_sec, bool p_process_a
}
Ref<Tween> SceneTree::create_tween() {
- Ref<Tween> tween;
- tween.instantiate();
- tween->set_valid(true);
+ Ref<Tween> tween = memnew(Tween(true));
tweens.push_back(tween);
return tween;
}
@@ -1133,8 +1135,51 @@ Array SceneTree::get_processed_tweens() {
return ret;
}
-Ref<MultiplayerAPI> SceneTree::get_multiplayer() const {
- return multiplayer;
+Ref<MultiplayerAPI> SceneTree::get_multiplayer(const NodePath &p_for_path) const {
+ Ref<MultiplayerAPI> out = multiplayer;
+ const NodePath *spath = nullptr;
+ while ((spath = custom_multiplayers.next(spath))) {
+ const Vector<StringName> snames = (*spath).get_names();
+ const Vector<StringName> tnames = p_for_path.get_names();
+ if (tnames.size() < snames.size()) {
+ continue;
+ }
+ const StringName *sptr = snames.ptr();
+ const StringName *nptr = tnames.ptr();
+ bool valid = true;
+ for (int i = 0; i < snames.size(); i++) {
+ if (sptr[i] != nptr[i]) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid) {
+ out = custom_multiplayers[*spath];
+ break;
+ }
+ }
+ return out;
+}
+
+void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer, const NodePath &p_root_path) {
+ if (p_root_path.is_empty()) {
+ ERR_FAIL_COND(!p_multiplayer.is_valid());
+ if (multiplayer.is_valid()) {
+ multiplayer->set_root_path(NodePath());
+ }
+ multiplayer = p_multiplayer;
+ multiplayer->set_root_path("/" + root->get_name());
+ } else {
+ if (p_multiplayer.is_valid()) {
+ custom_multiplayers[p_root_path] = p_multiplayer;
+ p_multiplayer->set_root_path(p_root_path);
+ } else {
+ if (custom_multiplayers.has(p_root_path)) {
+ custom_multiplayers[p_root_path]->set_root_path(NodePath());
+ custom_multiplayers.erase(p_root_path);
+ }
+ }
+ }
}
void SceneTree::set_multiplayer_poll_enabled(bool p_enabled) {
@@ -1145,13 +1190,6 @@ bool SceneTree::is_multiplayer_poll_enabled() const {
return multiplayer_poll;
}
-void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer) {
- ERR_FAIL_COND(!p_multiplayer.is_valid());
-
- multiplayer = p_multiplayer;
- multiplayer->set_root_path("/" + root->get_name());
-}
-
void SceneTree::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root);
ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);
@@ -1214,8 +1252,8 @@ void SceneTree::_bind_methods() {
ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene);
- ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer"), &SceneTree::set_multiplayer);
- ClassDB::bind_method(D_METHOD("get_multiplayer"), &SceneTree::get_multiplayer);
+ ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer", "root_path"), &SceneTree::set_multiplayer, DEFVAL(NodePath()));
+ ClassDB::bind_method(D_METHOD("get_multiplayer", "for_path"), &SceneTree::get_multiplayer, DEFVAL(NodePath()));
ClassDB::bind_method(D_METHOD("set_multiplayer_poll_enabled", "enabled"), &SceneTree::set_multiplayer_poll_enabled);
ClassDB::bind_method(D_METHOD("is_multiplayer_poll_enabled"), &SceneTree::is_multiplayer_poll_enabled);
@@ -1225,7 +1263,6 @@ void SceneTree::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "edited_scene_root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_edited_scene_root", "get_edited_scene_root");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "current_scene", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_current_scene", "get_current_scene");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "", "get_root");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multiplayer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerAPI", PROPERTY_USAGE_NONE), "set_multiplayer", "get_multiplayer");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multiplayer_poll"), "set_multiplayer_poll_enabled", "is_multiplayer_poll_enabled");
ADD_SIGNAL(MethodInfo("tree_changed"));
diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h
index 705ca6ebd3..9d7757e0a3 100644
--- a/scene/main/scene_tree.h
+++ b/scene/main/scene_tree.h
@@ -159,6 +159,7 @@ private:
///network///
Ref<MultiplayerAPI> multiplayer;
+ HashMap<NodePath, Ref<MultiplayerAPI>> custom_multiplayers;
bool multiplayer_poll = true;
static SceneTree *singleton;
@@ -351,10 +352,10 @@ public:
//network API
- Ref<MultiplayerAPI> get_multiplayer() const;
+ Ref<MultiplayerAPI> get_multiplayer(const NodePath &p_for_path = NodePath()) const;
+ void set_multiplayer(Ref<MultiplayerAPI> p_multiplayer, const NodePath &p_root_path = NodePath());
void set_multiplayer_poll_enabled(bool p_enabled);
bool is_multiplayer_poll_enabled() const;
- void set_multiplayer(Ref<MultiplayerAPI> p_multiplayer);
static void add_idle_callback(IdleCallback p_callback);
diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index 8b1a4680d2..6feccb7eec 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -1045,7 +1045,9 @@ void Window::popup_centered_clamped(const Size2i &p_size, float p_fallback_ratio
Rect2i popup_rect;
popup_rect.size = Vector2i(MIN(size_ratio.x, p_size.x), MIN(size_ratio.y, p_size.y));
- popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+ if (parent_rect != Rect2()) {
+ popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+ }
popup(popup_rect);
}
@@ -1069,7 +1071,10 @@ void Window::popup_centered(const Size2i &p_minsize) {
Size2 contents_minsize = _get_contents_minimum_size();
popup_rect.size.x = MAX(p_minsize.x, contents_minsize.x);
popup_rect.size.y = MAX(p_minsize.y, contents_minsize.y);
- popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+
+ if (parent_rect != Rect2()) {
+ popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+ }
popup(popup_rect);
}
@@ -1091,8 +1096,10 @@ void Window::popup_centered_ratio(float p_ratio) {
}
Rect2i popup_rect;
- popup_rect.size = parent_rect.size * p_ratio;
- popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+ if (parent_rect != Rect2()) {
+ popup_rect.size = parent_rect.size * p_ratio;
+ popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
+ }
popup(popup_rect);
}
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index e421cdc1f8..6c0192cf44 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -1109,6 +1109,9 @@ void initialize_theme() {
TextServer::SubpixelPositioning font_subpixel_positioning = (TextServer::SubpixelPositioning)(int)GLOBAL_DEF_RST("gui/theme/default_font_subpixel_positioning", TextServer::SUBPIXEL_POSITIONING_AUTO);
ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/default_font_subpixel_positioning", PropertyInfo(Variant::INT, "gui/theme/default_font_subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One half of a pixel,One quarter of a pixel", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ const bool font_msdf = GLOBAL_DEF_RST("gui/theme/default_font_multichannel_signed_distance_field", false);
+ const bool font_generate_mipmaps = GLOBAL_DEF_RST("gui/theme/default_font_generate_mipmaps", false);
+
Ref<Font> font;
if (!font_path.is_empty()) {
font = ResourceLoader::load(font_path);
@@ -1119,7 +1122,7 @@ void initialize_theme() {
// Always make the default theme to avoid invalid default font/icon/style in the given theme.
if (RenderingServer::get_singleton()) {
- make_default_theme(default_theme_scale, font, font_subpixel_positioning, font_hinting, font_antialiased);
+ make_default_theme(default_theme_scale, font, font_subpixel_positioning, font_hinting, font_antialiased, font_msdf, font_generate_mipmaps);
}
if (!theme_path.is_empty()) {
diff --git a/scene/resources/animation_library.cpp b/scene/resources/animation_library.cpp
index 229d9ab218..5d92c3b0c6 100644
--- a/scene/resources/animation_library.cpp
+++ b/scene/resources/animation_library.cpp
@@ -30,8 +30,25 @@
#include "animation_library.h"
+bool AnimationLibrary::is_valid_name(const String &p_name) {
+ return !(p_name.is_empty() || p_name.contains("/") || p_name.contains(":") || p_name.contains(",") || p_name.contains("["));
+}
+
+String AnimationLibrary::validate_name(const String &p_name) {
+ if (p_name.is_empty()) {
+ return "_"; // Should always return a valid name.
+ }
+
+ String name = p_name;
+ const char *characters = "/:,[";
+ for (const char *p = characters; *p; p++) {
+ name = name.replace(String::chr(*p), "_");
+ }
+ return name;
+}
+
Error AnimationLibrary::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) {
- ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + ".");
+ ERR_FAIL_COND_V_MSG(!is_valid_name(p_name), ERR_INVALID_PARAMETER, "Invalid animation name: '" + String(p_name) + "'.");
ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER);
if (animations.has(p_name)) {
@@ -55,7 +72,7 @@ void AnimationLibrary::remove_animation(const StringName &p_name) {
void AnimationLibrary::rename_animation(const StringName &p_name, const StringName &p_new_name) {
ERR_FAIL_COND(!animations.has(p_name));
- ERR_FAIL_COND_MSG(String(p_new_name).contains("/") || String(p_new_name).contains(":") || String(p_new_name).contains(",") || String(p_new_name).contains("["), "Invalid animation name: " + String(p_new_name) + ".");
+ ERR_FAIL_COND_MSG(!is_valid_name(p_new_name), "Invalid animation name: '" + String(p_new_name) + "'.");
ERR_FAIL_COND(animations.has(p_new_name));
animations.insert(p_new_name, animations[p_name]);
diff --git a/scene/resources/animation_library.h b/scene/resources/animation_library.h
index 69ac5a97d2..0f327fb072 100644
--- a/scene/resources/animation_library.h
+++ b/scene/resources/animation_library.h
@@ -49,6 +49,9 @@ protected:
static void _bind_methods();
public:
+ static bool is_valid_name(const String &p_name);
+ static String validate_name(const String &p_name);
+
Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation);
void remove_animation(const StringName &p_name);
void rename_animation(const StringName &p_name, const StringName &p_new_name);
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index f059ec2cf6..271cf61171 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -1026,7 +1026,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
default_style = make_flat_stylebox(Color(1, 0.365, 0.365), 4, 4, 4, 4, 0, false, 2);
}
-void make_default_theme(float p_scale, Ref<Font> p_font, TextServer::SubpixelPositioning p_subpixel, TextServer::Hinting p_hinting, bool p_aa) {
+void make_default_theme(float p_scale, Ref<Font> p_font, TextServer::SubpixelPositioning p_font_subpixel, TextServer::Hinting p_font_hinting, bool p_font_antialiased, bool p_font_msdf, bool p_font_generate_mipmaps) {
Ref<Theme> t;
t.instantiate();
@@ -1051,9 +1051,12 @@ void make_default_theme(float p_scale, Ref<Font> p_font, TextServer::SubpixelPos
Ref<FontData> dynamic_font_data;
dynamic_font_data.instantiate();
dynamic_font_data->set_data_ptr(_font_OpenSans_SemiBold, _font_OpenSans_SemiBold_size);
- dynamic_font_data->set_subpixel_positioning(p_subpixel);
- dynamic_font_data->set_hinting(p_hinting);
- dynamic_font_data->set_antialiased(p_aa);
+ dynamic_font_data->set_subpixel_positioning(p_font_subpixel);
+ dynamic_font_data->set_hinting(p_font_hinting);
+ dynamic_font_data->set_antialiased(p_font_antialiased);
+ dynamic_font_data->set_multichannel_signed_distance_field(p_font_msdf);
+ dynamic_font_data->set_generate_mipmaps(p_font_generate_mipmaps);
+
dynamic_font->add_data(dynamic_font_data);
default_font = dynamic_font;
diff --git a/scene/resources/default_theme/default_theme.h b/scene/resources/default_theme/default_theme.h
index a9e21dda3f..f777330a07 100644
--- a/scene/resources/default_theme/default_theme.h
+++ b/scene/resources/default_theme/default_theme.h
@@ -36,7 +36,7 @@
const int default_font_size = 16;
void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const Ref<Font> &bold_font, const Ref<Font> &bold_italics_font, const Ref<Font> &italics_font, Ref<Texture2D> &default_icon, Ref<StyleBox> &default_style, float p_scale);
-void make_default_theme(float p_scale, Ref<Font> p_font, TextServer::SubpixelPositioning p_subpixel, TextServer::Hinting p_hinting, bool p_aa);
+void make_default_theme(float p_scale, Ref<Font> p_font, TextServer::SubpixelPositioning p_font_subpixel = TextServer::SUBPIXEL_POSITIONING_AUTO, TextServer::Hinting p_font_hinting = TextServer::HINTING_LIGHT, bool p_font_antialiased = true, bool p_font_msdf = false, bool p_font_generate_mipmaps = false);
void clear_default_theme();
#endif
diff --git a/scene/resources/gradient.cpp b/scene/resources/gradient.cpp
index caaa3d8628..a9c44dc6bf 100644
--- a/scene/resources/gradient.cpp
+++ b/scene/resources/gradient.cpp
@@ -157,7 +157,7 @@ void Gradient::reverse() {
emit_signal(CoreStringNames::get_singleton()->changed);
}
-void Gradient::set_points(Vector<Gradient::Point> &p_points) {
+void Gradient::set_points(const Vector<Gradient::Point> &p_points) {
points = p_points;
is_sorted = false;
emit_signal(CoreStringNames::get_singleton()->changed);
diff --git a/scene/resources/gradient.h b/scene/resources/gradient.h
index c2085b3a13..a3d3449099 100644
--- a/scene/resources/gradient.h
+++ b/scene/resources/gradient.h
@@ -73,7 +73,7 @@ public:
void add_point(float p_offset, const Color &p_color);
void remove_point(int p_index);
- void set_points(Vector<Point> &p_points);
+ void set_points(const Vector<Point> &p_points);
Vector<Point> &get_points();
void reverse();
diff --git a/scene/resources/immediate_mesh.cpp b/scene/resources/immediate_mesh.cpp
index 28afef8638..044477e744 100644
--- a/scene/resources/immediate_mesh.cpp
+++ b/scene/resources/immediate_mesh.cpp
@@ -211,7 +211,7 @@ void ImmediateMesh::surface_end() {
value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
if (t.d > 0) {
- value |= 3 << 30;
+ value |= 3UL << 30;
}
*tangent = value;
diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp
index fe52761482..f3cb2b9ea7 100644
--- a/scene/resources/style_box.cpp
+++ b/scene/resources/style_box.cpp
@@ -124,8 +124,8 @@ void StyleBox::_bind_methods() {
ADD_GROUP("Content Margin", "content_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", SIDE_BOTTOM);
GDVIRTUAL_BIND(_get_style_margin, "side")
@@ -316,19 +316,23 @@ void StyleBoxTexture::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
+
ADD_GROUP("Margin", "margin_");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", SIDE_BOTTOM);
+
ADD_GROUP("Expand Margin", "expand_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", SIDE_BOTTOM);
+
ADD_GROUP("Axis Stretch", "axis_stretch_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_stretch_horizontal", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "set_h_axis_stretch_mode", "get_h_axis_stretch_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_stretch_vertical", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "set_v_axis_stretch_mode", "get_v_axis_stretch_mode");
+
ADD_GROUP("Modulate", "modulate_");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate_color"), "set_modulate", "get_modulate");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "is_draw_center_enabled");
@@ -457,6 +461,15 @@ bool StyleBoxFlat::is_draw_center_enabled() const {
return draw_center;
}
+void StyleBoxFlat::set_skew(Vector2 p_skew) {
+ skew = p_skew;
+ emit_changed();
+}
+
+Vector2 StyleBoxFlat::get_skew() const {
+ return skew;
+}
+
void StyleBoxFlat::set_shadow_color(const Color &p_color) {
shadow_color = p_color;
emit_changed();
@@ -542,7 +555,7 @@ inline void set_inner_corner_radius(const Rect2 style_rect, const Rect2 inner_re
}
inline void draw_ring(Vector<Vector2> &verts, Vector<int> &indices, Vector<Color> &colors, const Rect2 &style_rect, const real_t corner_radius[4],
- const Rect2 &ring_rect, const Rect2 &inner_rect, const Color &inner_color, const Color &outer_color, const int corner_detail, const bool fill_center = false) {
+ const Rect2 &ring_rect, const Rect2 &inner_rect, const Color &inner_color, const Color &outer_color, const int corner_detail, const Vector2 &skew, bool fill_center = false) {
int vert_offset = verts.size();
if (!vert_offset) {
vert_offset = 0;
@@ -586,9 +599,12 @@ inline void draw_ring(Vector<Vector2> &verts, Vector<int> &indices, Vector<Color
color = outer_color;
corner_point = outer_points[corner_index];
}
- real_t x = radius * (real_t)cos((corner_index + detail / (double)adapted_corner_detail) * (Math_TAU / 4.0) + Math_PI) + corner_point.x;
- real_t y = radius * (real_t)sin((corner_index + detail / (double)adapted_corner_detail) * (Math_TAU / 4.0) + Math_PI) + corner_point.y;
- verts.push_back(Vector2(x, y));
+
+ const real_t x = radius * (real_t)cos((corner_index + detail / (double)adapted_corner_detail) * (Math_TAU / 4.0) + Math_PI) + corner_point.x;
+ const real_t y = radius * (real_t)sin((corner_index + detail / (double)adapted_corner_detail) * (Math_TAU / 4.0) + Math_PI) + corner_point.y;
+ const float x_skew = -skew.x * (y - ring_rect.get_center().y);
+ const float y_skew = -skew.y * (x - ring_rect.get_center().x);
+ verts.push_back(Vector2(x + x_skew, y + y_skew));
colors.push_back(color);
}
}
@@ -666,10 +682,12 @@ void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
return;
}
- bool rounded_corners = (corner_radius[0] > 0) || (corner_radius[1] > 0) || (corner_radius[2] > 0) || (corner_radius[3] > 0);
- bool aa_on = rounded_corners && anti_aliased;
+ const bool rounded_corners = (corner_radius[0] > 0) || (corner_radius[1] > 0) || (corner_radius[2] > 0) || (corner_radius[3] > 0);
+ // Only enable antialiasing if it is actually needed. This improve performances
+ // and maximizes sharpness for non-skewed StyleBoxes with sharp corners.
+ const bool aa_on = (rounded_corners || !skew.is_equal_approx(Vector2())) && anti_aliased;
- bool blend_on = blend_border && draw_border;
+ const bool blend_on = blend_border && draw_border;
Color border_color_alpha = Color(border_color.r, border_color.g, border_color.b, 0);
Color border_color_blend = (draw_center ? bg_color : border_color_alpha);
@@ -716,24 +734,24 @@ void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
Color shadow_color_transparent = Color(shadow_color.r, shadow_color.g, shadow_color.b, 0);
draw_ring(verts, indices, colors, shadow_inner_rect, adapted_corner,
- shadow_rect, shadow_inner_rect, shadow_color, shadow_color_transparent, corner_detail);
+ shadow_rect, shadow_inner_rect, shadow_color, shadow_color_transparent, corner_detail, skew);
if (draw_center) {
draw_ring(verts, indices, colors, shadow_inner_rect, adapted_corner,
- shadow_inner_rect, shadow_inner_rect, shadow_color, shadow_color, corner_detail, true);
+ shadow_inner_rect, shadow_inner_rect, shadow_color, shadow_color, corner_detail, skew, true);
}
}
// Create border (no AA).
if (draw_border && !aa_on) {
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- border_style_rect, infill_rect, border_color_inner, border_color, corner_detail);
+ border_style_rect, infill_rect, border_color_inner, border_color, corner_detail, skew);
}
// Create infill (no AA).
if (draw_center && (!aa_on || blend_on || !draw_border)) {
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- infill_rect, infill_rect, bg_color, bg_color, corner_detail, true);
+ infill_rect, infill_rect, bg_color, bg_color, corner_detail, skew, true);
}
if (aa_on) {
@@ -765,7 +783,7 @@ void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
aa_border_width[SIDE_RIGHT], aa_border_width[SIDE_BOTTOM]);
// Create infill within AA border.
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- infill_inner_rect_aa, infill_inner_rect_aa, bg_color, bg_color, corner_detail, true);
+ infill_inner_rect_aa, infill_inner_rect_aa, bg_color, bg_color, corner_detail, skew, true);
}
if (!blend_on || !draw_border) {
@@ -776,7 +794,7 @@ void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
// Create infill fake AA gradient.
draw_ring(verts, indices, colors, style_rect, adapted_corner,
- infill_rect_aa, infill_rect, bg_color, alpha_bg, corner_detail);
+ infill_rect_aa, infill_rect, bg_color, alpha_bg, corner_detail, skew);
}
}
@@ -790,17 +808,17 @@ void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
// Create border.
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- border_style_rect_aa, ((blend_on) ? infill_rect : infill_rect_aa), border_color_inner, border_color, corner_detail);
+ border_style_rect_aa, ((blend_on) ? infill_rect : infill_rect_aa), border_color_inner, border_color, corner_detail, skew);
if (!blend_on) {
// Create inner border fake AA gradient.
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- infill_rect_aa, infill_rect, border_color_blend, border_color, corner_detail);
+ infill_rect_aa, infill_rect, border_color_blend, border_color, corner_detail, skew);
}
// Create outer border fake AA gradient.
draw_ring(verts, indices, colors, border_style_rect, adapted_corner,
- style_rect_aa, border_style_rect_aa, border_color, border_color_alpha, corner_detail);
+ style_rect_aa, border_style_rect_aa, border_color, border_color_alpha, corner_detail, skew);
}
}
@@ -858,6 +876,9 @@ void StyleBoxFlat::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_draw_center", "draw_center"), &StyleBoxFlat::set_draw_center);
ClassDB::bind_method(D_METHOD("is_draw_center_enabled"), &StyleBoxFlat::is_draw_center_enabled);
+ ClassDB::bind_method(D_METHOD("set_skew", "skew"), &StyleBoxFlat::set_skew);
+ ClassDB::bind_method(D_METHOD("get_skew"), &StyleBoxFlat::get_skew);
+
ClassDB::bind_method(D_METHOD("set_shadow_color", "color"), &StyleBoxFlat::set_shadow_color);
ClassDB::bind_method(D_METHOD("get_shadow_color"), &StyleBoxFlat::get_shadow_color);
@@ -879,6 +900,7 @@ void StyleBoxFlat::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "bg_color"), "set_bg_color", "get_bg_color");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "is_draw_center_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "skew"), "set_skew", "get_skew");
ADD_GROUP("Border Width", "border_width_");
ADD_PROPERTYI(PropertyInfo(Variant::INT, "border_width_left", PROPERTY_HINT_RANGE, "0,1024,1"), "set_border_width", "get_border_width", SIDE_LEFT);
@@ -901,8 +923,8 @@ void StyleBoxFlat::_bind_methods() {
ADD_GROUP("Expand Margin", "expand_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", SIDE_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", SIDE_BOTTOM);
ADD_GROUP("Shadow", "shadow_");
diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h
index 68ad41b69c..3b3654775f 100644
--- a/scene/resources/style_box.h
+++ b/scene/resources/style_box.h
@@ -155,6 +155,7 @@ class StyleBoxFlat : public StyleBox {
bool draw_center = true;
bool blend_border = false;
+ Vector2 skew;
bool anti_aliased = true;
int corner_detail = 8;
@@ -200,6 +201,9 @@ public:
void set_draw_center(bool p_enabled);
bool is_draw_center_enabled() const;
+ void set_skew(Vector2 p_skew);
+ Vector2 get_skew() const;
+
void set_shadow_color(const Color &p_color);
Color get_shadow_color() const;
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index 4c20e07976..14abe13afa 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -2278,6 +2278,8 @@ Ref<Image> GradientTexture1D::get_image() const {
return RenderingServer::get_singleton()->texture_2d_get(texture);
}
+//////////////////
+
GradientTexture2D::GradientTexture2D() {
_queue_update();
}
@@ -2299,7 +2301,8 @@ void GradientTexture2D::set_gradient(Ref<Gradient> p_gradient) {
if (gradient.is_valid()) {
gradient->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &GradientTexture2D::_queue_update));
}
- _queue_update();
+ _update();
+ emit_changed();
}
Ref<Gradient> GradientTexture2D::get_gradient() const {
diff --git a/servers/display_server.cpp b/servers/display_server.cpp
index 67bfc75426..8d97cd2543 100644
--- a/servers/display_server.cpp
+++ b/servers/display_server.cpp
@@ -220,6 +220,81 @@ void DisplayServer::global_menu_clear(const String &p_menu_root) {
WARN_PRINT("Global menus not supported by this display server.");
}
+bool DisplayServer::tts_is_speaking() const {
+ WARN_PRINT("TTS is not supported by this display server.");
+ return false;
+}
+
+bool DisplayServer::tts_is_paused() const {
+ WARN_PRINT("TTS is not supported by this display server.");
+ return false;
+}
+
+void DisplayServer::tts_pause() {
+ WARN_PRINT("TTS is not supported by this display server.");
+}
+
+void DisplayServer::tts_resume() {
+ WARN_PRINT("TTS is not supported by this display server.");
+}
+
+Array DisplayServer::tts_get_voices() const {
+ WARN_PRINT("TTS is not supported by this display server.");
+ return Array();
+}
+
+PackedStringArray DisplayServer::tts_get_voices_for_language(const String &p_language) const {
+ PackedStringArray ret;
+ Array voices = tts_get_voices();
+ for (int i = 0; i < voices.size(); i++) {
+ const Dictionary &voice = voices[i];
+ if (voice.has("id") && voice.has("language") && voice["language"].operator String().begins_with(p_language)) {
+ ret.push_back(voice["id"]);
+ }
+ }
+ return ret;
+}
+
+void DisplayServer::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
+ WARN_PRINT("TTS is not supported by this display server.");
+}
+
+void DisplayServer::tts_stop() {
+ WARN_PRINT("TTS is not supported by this display server.");
+}
+
+void DisplayServer::tts_set_utterance_callback(TTSUtteranceEvent p_event, const Callable &p_callable) {
+ ERR_FAIL_INDEX(p_event, DisplayServer::TTS_UTTERANCE_MAX);
+ utterance_callback[p_event] = p_callable;
+}
+
+void DisplayServer::tts_post_utterance_event(TTSUtteranceEvent p_event, int p_id, int p_pos) {
+ ERR_FAIL_INDEX(p_event, DisplayServer::TTS_UTTERANCE_MAX);
+ switch (p_event) {
+ case DisplayServer::TTS_UTTERANCE_STARTED:
+ case DisplayServer::TTS_UTTERANCE_ENDED:
+ case DisplayServer::TTS_UTTERANCE_CANCELED: {
+ if (utterance_callback[p_event].is_valid()) {
+ Variant args[1];
+ args[0] = p_id;
+ const Variant *argp[] = { &args[0] };
+ utterance_callback[p_event].call_deferred(argp, 1); // Should be deferred, on some platforms utterance events can be called from different threads in a rapid succession.
+ }
+ } break;
+ case DisplayServer::TTS_UTTERANCE_BOUNDARY: {
+ if (utterance_callback[p_event].is_valid()) {
+ Variant args[2];
+ args[0] = p_pos;
+ args[1] = p_id;
+ const Variant *argp[] = { &args[0], &args[1] };
+ utterance_callback[p_event].call_deferred(argp, 2); // Should be deferred, on some platforms utterance events can be called from different threads in a rapid succession.
+ }
+ } break;
+ default:
+ break;
+ }
+}
+
void DisplayServer::mouse_set_mode(MouseMode p_mode) {
WARN_PRINT("Mouse is not supported by this display server.");
}
@@ -478,6 +553,19 @@ void DisplayServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("global_menu_remove_item", "menu_root", "idx"), &DisplayServer::global_menu_remove_item);
ClassDB::bind_method(D_METHOD("global_menu_clear", "menu_root"), &DisplayServer::global_menu_clear);
+ ClassDB::bind_method(D_METHOD("tts_is_speaking"), &DisplayServer::tts_is_speaking);
+ ClassDB::bind_method(D_METHOD("tts_is_paused"), &DisplayServer::tts_is_paused);
+ ClassDB::bind_method(D_METHOD("tts_get_voices"), &DisplayServer::tts_get_voices);
+ ClassDB::bind_method(D_METHOD("tts_get_voices_for_language", "language"), &DisplayServer::tts_get_voices_for_language);
+
+ ClassDB::bind_method(D_METHOD("tts_speak", "text", "voice", "volume", "pitch", "rate", "utterance_id", "interrupt"), &DisplayServer::tts_speak, DEFVAL(50), DEFVAL(1.f), DEFVAL(1.f), DEFVAL(0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("tts_pause"), &DisplayServer::tts_pause);
+ ClassDB::bind_method(D_METHOD("tts_resume"), &DisplayServer::tts_resume);
+ ClassDB::bind_method(D_METHOD("tts_stop"), &DisplayServer::tts_stop);
+
+ ClassDB::bind_method(D_METHOD("tts_set_utterance_callback", "event", "callable"), &DisplayServer::tts_set_utterance_callback);
+ ClassDB::bind_method(D_METHOD("_tts_post_utterance_event", "event", "id", "char_pos"), &DisplayServer::tts_post_utterance_event);
+
ClassDB::bind_method(D_METHOD("mouse_set_mode", "mouse_mode"), &DisplayServer::mouse_set_mode);
ClassDB::bind_method(D_METHOD("mouse_get_mode"), &DisplayServer::mouse_get_mode);
@@ -621,6 +709,7 @@ void DisplayServer::_bind_methods() {
BIND_ENUM_CONSTANT(FEATURE_ORIENTATION);
BIND_ENUM_CONSTANT(FEATURE_SWAP_BUFFERS);
BIND_ENUM_CONSTANT(FEATURE_CLIPBOARD_PRIMARY);
+ BIND_ENUM_CONSTANT(FEATURE_TEXT_TO_SPEECH);
BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
@@ -689,6 +778,11 @@ void DisplayServer::_bind_methods() {
BIND_ENUM_CONSTANT(DISPLAY_HANDLE);
BIND_ENUM_CONSTANT(WINDOW_HANDLE);
BIND_ENUM_CONSTANT(WINDOW_VIEW);
+
+ BIND_ENUM_CONSTANT(TTS_UTTERANCE_STARTED);
+ BIND_ENUM_CONSTANT(TTS_UTTERANCE_ENDED);
+ BIND_ENUM_CONSTANT(TTS_UTTERANCE_CANCELED);
+ BIND_ENUM_CONSTANT(TTS_UTTERANCE_BOUNDARY);
}
void DisplayServer::register_create_function(const char *p_name, CreateFunction p_function, GetRenderingDriversFunction p_get_drivers) {
diff --git a/servers/display_server.h b/servers/display_server.h
index 4961b07ba3..19efcbd3dd 100644
--- a/servers/display_server.h
+++ b/servers/display_server.h
@@ -121,6 +121,7 @@ public:
FEATURE_SWAP_BUFFERS,
FEATURE_KEEP_SCREEN_ON,
FEATURE_CLIPBOARD_PRIMARY,
+ FEATURE_TEXT_TO_SPEECH,
};
virtual bool has_feature(Feature p_feature) const = 0;
@@ -172,6 +173,40 @@ public:
virtual void global_menu_remove_item(const String &p_menu_root, int p_idx);
virtual void global_menu_clear(const String &p_menu_root);
+ struct TTSUtterance {
+ String text;
+ String voice;
+ int volume = 50;
+ float pitch = 1.f;
+ float rate = 1.f;
+ int id = 0;
+ };
+
+ enum TTSUtteranceEvent {
+ TTS_UTTERANCE_STARTED,
+ TTS_UTTERANCE_ENDED,
+ TTS_UTTERANCE_CANCELED,
+ TTS_UTTERANCE_BOUNDARY,
+ TTS_UTTERANCE_MAX,
+ };
+
+private:
+ Callable utterance_callback[TTS_UTTERANCE_MAX];
+
+public:
+ virtual bool tts_is_speaking() const;
+ virtual bool tts_is_paused() const;
+ virtual Array tts_get_voices() const;
+ virtual PackedStringArray tts_get_voices_for_language(const String &p_language) const;
+
+ virtual void tts_speak(const String &p_text, const String &p_voice, int p_volume = 50, float p_pitch = 1.f, float p_rate = 1.f, int p_utterance_id = 0, bool p_interrupt = false);
+ virtual void tts_pause();
+ virtual void tts_resume();
+ virtual void tts_stop();
+
+ virtual void tts_set_utterance_callback(TTSUtteranceEvent p_event, const Callable &p_callable);
+ virtual void tts_post_utterance_event(TTSUtteranceEvent p_event, int p_id, int p_pos = 0);
+
enum MouseMode {
MOUSE_MODE_VISIBLE,
MOUSE_MODE_HIDDEN,
@@ -431,5 +466,6 @@ VARIANT_ENUM_CAST(DisplayServer::WindowFlags)
VARIANT_ENUM_CAST(DisplayServer::HandleType)
VARIANT_ENUM_CAST(DisplayServer::CursorShape)
VARIANT_ENUM_CAST(DisplayServer::VSyncMode)
+VARIANT_ENUM_CAST(DisplayServer::TTSUtteranceEvent)
#endif // DISPLAY_SERVER_H
diff --git a/servers/navigation_server_2d.cpp b/servers/navigation_server_2d.cpp
index 0fef416680..a92fe8c79a 100644
--- a/servers/navigation_server_2d.cpp
+++ b/servers/navigation_server_2d.cpp
@@ -138,11 +138,11 @@ static Object *obj_to_obj(Object *d) {
return d;
}
-static StringName sn_to_sn(StringName &d) {
+static StringName sn_to_sn(const StringName &d) {
return d;
}
-static Variant var_to_var(Variant &d) {
+static Variant var_to_var(const Variant &d) {
return d;
}
diff --git a/servers/physics_2d/godot_space_2d.cpp b/servers/physics_2d/godot_space_2d.cpp
index 63e3af1395..a2459501c8 100644
--- a/servers/physics_2d/godot_space_2d.cpp
+++ b/servers/physics_2d/godot_space_2d.cpp
@@ -1033,9 +1033,9 @@ void GodotSpace2D::_broadphase_unpair(GodotCollisionObject2D *A, int p_subindex_
return;
}
- GodotSpace2D *self = (GodotSpace2D *)p_self;
+ GodotSpace2D *self = static_cast<GodotSpace2D *>(p_self);
self->collision_pairs--;
- GodotConstraint2D *c = (GodotConstraint2D *)p_data;
+ GodotConstraint2D *c = static_cast<GodotConstraint2D *>(p_data);
memdelete(c);
}
diff --git a/servers/physics_server_2d_wrap_mt.cpp b/servers/physics_server_2d_wrap_mt.cpp
index 02223b83f0..699f515270 100644
--- a/servers/physics_server_2d_wrap_mt.cpp
+++ b/servers/physics_server_2d_wrap_mt.cpp
@@ -37,7 +37,7 @@ void PhysicsServer2DWrapMT::thread_exit() {
}
void PhysicsServer2DWrapMT::thread_step(real_t p_delta) {
- physics_2d_server->step(p_delta);
+ physics_server_2d->step(p_delta);
step_sem.post();
}
@@ -50,7 +50,7 @@ void PhysicsServer2DWrapMT::_thread_callback(void *_instance) {
void PhysicsServer2DWrapMT::thread_loop() {
server_thread = Thread::get_caller_id();
- physics_2d_server->init();
+ physics_server_2d->init();
exit.clear();
step_thread_up.set();
@@ -61,7 +61,7 @@ void PhysicsServer2DWrapMT::thread_loop() {
command_queue.flush_all(); // flush all
- physics_2d_server->finish();
+ physics_server_2d->finish();
}
/* EVENT QUEUING */
@@ -71,7 +71,7 @@ void PhysicsServer2DWrapMT::step(real_t p_step) {
command_queue.push(this, &PhysicsServer2DWrapMT::thread_step, p_step);
} else {
command_queue.flush_all(); //flush all pending from other threads
- physics_2d_server->step(p_step);
+ physics_server_2d->step(p_step);
}
}
@@ -83,15 +83,15 @@ void PhysicsServer2DWrapMT::sync() {
step_sem.wait(); //must not wait if a step was not issued
}
}
- physics_2d_server->sync();
+ physics_server_2d->sync();
}
void PhysicsServer2DWrapMT::flush_queries() {
- physics_2d_server->flush_queries();
+ physics_server_2d->flush_queries();
}
void PhysicsServer2DWrapMT::end_sync() {
- physics_2d_server->end_sync();
+ physics_server_2d->end_sync();
}
void PhysicsServer2DWrapMT::init() {
@@ -102,7 +102,7 @@ void PhysicsServer2DWrapMT::init() {
OS::get_singleton()->delay_usec(1000);
}
} else {
- physics_2d_server->init();
+ physics_server_2d->init();
}
}
@@ -111,13 +111,13 @@ void PhysicsServer2DWrapMT::finish() {
command_queue.push(this, &PhysicsServer2DWrapMT::thread_exit);
thread.wait_to_finish();
} else {
- physics_2d_server->finish();
+ physics_server_2d->finish();
}
}
PhysicsServer2DWrapMT::PhysicsServer2DWrapMT(PhysicsServer2D *p_contained, bool p_create_thread) :
command_queue(p_create_thread) {
- physics_2d_server = p_contained;
+ physics_server_2d = p_contained;
create_thread = p_create_thread;
pool_max_size = GLOBAL_GET("memory/limits/multithreaded_server/rid_pool_prealloc");
@@ -132,6 +132,6 @@ PhysicsServer2DWrapMT::PhysicsServer2DWrapMT(PhysicsServer2D *p_contained, bool
}
PhysicsServer2DWrapMT::~PhysicsServer2DWrapMT() {
- memdelete(physics_2d_server);
+ memdelete(physics_server_2d);
//finish();
}
diff --git a/servers/physics_server_2d_wrap_mt.h b/servers/physics_server_2d_wrap_mt.h
index aa3a8bc04a..ddb071f603 100644
--- a/servers/physics_server_2d_wrap_mt.h
+++ b/servers/physics_server_2d_wrap_mt.h
@@ -44,7 +44,7 @@
#endif
class PhysicsServer2DWrapMT : public PhysicsServer2D {
- mutable PhysicsServer2D *physics_2d_server;
+ mutable PhysicsServer2D *physics_server_2d;
mutable CommandQueueMT command_queue;
@@ -71,7 +71,7 @@ class PhysicsServer2DWrapMT : public PhysicsServer2D {
public:
#define ServerName PhysicsServer2D
#define ServerNameWrapMT PhysicsServer2DWrapMT
-#define server_name physics_2d_server
+#define server_name physics_server_2d
#define WRITE_ACTION
#include "servers/server_wrap_mt_common.h"
@@ -96,7 +96,7 @@ public:
//these work well, but should be used from the main thread only
bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false);
- return physics_2d_server->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count);
+ return physics_server_2d->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count);
}
/* SPACE API */
@@ -111,18 +111,18 @@ public:
// this function only works on physics process, errors and returns null otherwise
PhysicsDirectSpaceState2D *space_get_direct_state(RID p_space) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), nullptr);
- return physics_2d_server->space_get_direct_state(p_space);
+ return physics_server_2d->space_get_direct_state(p_space);
}
FUNC2(space_set_debug_contacts, RID, int);
virtual Vector<Vector2> space_get_contacts(RID p_space) const override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), Vector<Vector2>());
- return physics_2d_server->space_get_contacts(p_space);
+ return physics_server_2d->space_get_contacts(p_space);
}
virtual int space_get_contact_count(RID p_space) const override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), 0);
- return physics_2d_server->space_get_contact_count(p_space);
+ return physics_server_2d->space_get_contact_count(p_space);
}
/* AREA API */
@@ -250,20 +250,20 @@ public:
FUNC3(body_set_force_integration_callback, RID, const Callable &, const Variant &);
bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) override {
- return physics_2d_server->body_collide_shape(p_body, p_body_shape, p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count);
+ return physics_server_2d->body_collide_shape(p_body, p_body_shape, p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count);
}
FUNC2(body_set_pickable, RID, bool);
bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false);
- return physics_2d_server->body_test_motion(p_body, p_parameters, r_result);
+ return physics_server_2d->body_test_motion(p_body, p_parameters, r_result);
}
// this function only works on physics process, errors and returns null otherwise
PhysicsDirectBodyState2D *body_get_direct_state(RID p_body) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), nullptr);
- return physics_2d_server->body_get_direct_state(p_body);
+ return physics_server_2d->body_get_direct_state(p_body);
}
/* JOINT API */
@@ -309,11 +309,11 @@ public:
virtual void finish() override;
virtual bool is_flushing_queries() const override {
- return physics_2d_server->is_flushing_queries();
+ return physics_server_2d->is_flushing_queries();
}
int get_process_info(ProcessInfo p_info) override {
- return physics_2d_server->get_process_info(p_info);
+ return physics_server_2d->get_process_info(p_info);
}
PhysicsServer2DWrapMT(PhysicsServer2D *p_contained, bool p_create_thread);
diff --git a/servers/physics_server_3d_wrap_mt.cpp b/servers/physics_server_3d_wrap_mt.cpp
index 822ca44b72..7faa193ec2 100644
--- a/servers/physics_server_3d_wrap_mt.cpp
+++ b/servers/physics_server_3d_wrap_mt.cpp
@@ -37,7 +37,7 @@ void PhysicsServer3DWrapMT::thread_exit() {
}
void PhysicsServer3DWrapMT::thread_step(real_t p_delta) {
- physics_3d_server->step(p_delta);
+ physics_server_3d->step(p_delta);
step_sem.post();
}
@@ -50,7 +50,7 @@ void PhysicsServer3DWrapMT::_thread_callback(void *_instance) {
void PhysicsServer3DWrapMT::thread_loop() {
server_thread = Thread::get_caller_id();
- physics_3d_server->init();
+ physics_server_3d->init();
exit = false;
step_thread_up = true;
@@ -61,7 +61,7 @@ void PhysicsServer3DWrapMT::thread_loop() {
command_queue.flush_all(); // flush all
- physics_3d_server->finish();
+ physics_server_3d->finish();
}
/* EVENT QUEUING */
@@ -71,7 +71,7 @@ void PhysicsServer3DWrapMT::step(real_t p_step) {
command_queue.push(this, &PhysicsServer3DWrapMT::thread_step, p_step);
} else {
command_queue.flush_all(); //flush all pending from other threads
- physics_3d_server->step(p_step);
+ physics_server_3d->step(p_step);
}
}
@@ -83,15 +83,15 @@ void PhysicsServer3DWrapMT::sync() {
step_sem.wait(); //must not wait if a step was not issued
}
}
- physics_3d_server->sync();
+ physics_server_3d->sync();
}
void PhysicsServer3DWrapMT::flush_queries() {
- physics_3d_server->flush_queries();
+ physics_server_3d->flush_queries();
}
void PhysicsServer3DWrapMT::end_sync() {
- physics_3d_server->end_sync();
+ physics_server_3d->end_sync();
}
void PhysicsServer3DWrapMT::init() {
@@ -102,7 +102,7 @@ void PhysicsServer3DWrapMT::init() {
OS::get_singleton()->delay_usec(1000);
}
} else {
- physics_3d_server->init();
+ physics_server_3d->init();
}
}
@@ -111,13 +111,13 @@ void PhysicsServer3DWrapMT::finish() {
command_queue.push(this, &PhysicsServer3DWrapMT::thread_exit);
thread.wait_to_finish();
} else {
- physics_3d_server->finish();
+ physics_server_3d->finish();
}
}
PhysicsServer3DWrapMT::PhysicsServer3DWrapMT(PhysicsServer3D *p_contained, bool p_create_thread) :
command_queue(p_create_thread) {
- physics_3d_server = p_contained;
+ physics_server_3d = p_contained;
create_thread = p_create_thread;
pool_max_size = GLOBAL_GET("memory/limits/multithreaded_server/rid_pool_prealloc");
@@ -132,6 +132,6 @@ PhysicsServer3DWrapMT::PhysicsServer3DWrapMT(PhysicsServer3D *p_contained, bool
}
PhysicsServer3DWrapMT::~PhysicsServer3DWrapMT() {
- memdelete(physics_3d_server);
+ memdelete(physics_server_3d);
//finish();
}
diff --git a/servers/physics_server_3d_wrap_mt.h b/servers/physics_server_3d_wrap_mt.h
index e44f82672d..d4a4ad3132 100644
--- a/servers/physics_server_3d_wrap_mt.h
+++ b/servers/physics_server_3d_wrap_mt.h
@@ -43,7 +43,7 @@
#endif
class PhysicsServer3DWrapMT : public PhysicsServer3D {
- mutable PhysicsServer3D *physics_3d_server;
+ mutable PhysicsServer3D *physics_server_3d;
mutable CommandQueueMT command_queue;
@@ -70,7 +70,7 @@ class PhysicsServer3DWrapMT : public PhysicsServer3D {
public:
#define ServerName PhysicsServer3D
#define ServerNameWrapMT PhysicsServer3DWrapMT
-#define server_name physics_3d_server
+#define server_name physics_server_3d
#define WRITE_ACTION
#include "servers/server_wrap_mt_common.h"
@@ -100,7 +100,7 @@ public:
//these work well, but should be used from the main thread only
bool shape_collide(RID p_shape_A, const Transform &p_xform_A, const Vector3 &p_motion_A, RID p_shape_B, const Transform &p_xform_B, const Vector3 &p_motion_B, Vector3 *r_results, int p_result_max, int &r_result_count) {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false);
- return physics_3d_server->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count);
+ return physics_server_3d->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count);
}
#endif
/* SPACE API */
@@ -115,18 +115,18 @@ public:
// this function only works on physics process, errors and returns null otherwise
PhysicsDirectSpaceState3D *space_get_direct_state(RID p_space) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), nullptr);
- return physics_3d_server->space_get_direct_state(p_space);
+ return physics_server_3d->space_get_direct_state(p_space);
}
FUNC2(space_set_debug_contacts, RID, int);
virtual Vector<Vector3> space_get_contacts(RID p_space) const override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), Vector<Vector3>());
- return physics_3d_server->space_get_contacts(p_space);
+ return physics_server_3d->space_get_contacts(p_space);
}
virtual int space_get_contact_count(RID p_space) const override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), 0);
- return physics_3d_server->space_get_contact_count(p_space);
+ return physics_server_3d->space_get_contact_count(p_space);
}
/* AREA API */
@@ -256,13 +256,13 @@ public:
bool body_test_motion(RID p_body, const MotionParameters &p_parameters, MotionResult *r_result = nullptr) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), false);
- return physics_3d_server->body_test_motion(p_body, p_parameters, r_result);
+ return physics_server_3d->body_test_motion(p_body, p_parameters, r_result);
}
// this function only works on physics process, errors and returns null otherwise
PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) override {
ERR_FAIL_COND_V(main_thread != Thread::get_caller_id(), nullptr);
- return physics_3d_server->body_get_direct_state(p_body);
+ return physics_server_3d->body_get_direct_state(p_body);
}
/* SOFT BODY API */
@@ -385,11 +385,11 @@ public:
virtual void finish() override;
virtual bool is_flushing_queries() const override {
- return physics_3d_server->is_flushing_queries();
+ return physics_server_3d->is_flushing_queries();
}
int get_process_info(ProcessInfo p_info) override {
- return physics_3d_server->get_process_info(p_info);
+ return physics_server_3d->get_process_info(p_info);
}
PhysicsServer3DWrapMT(PhysicsServer3D *p_contained, bool p_create_thread);
diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp
index 9843492316..f02bf80645 100644
--- a/servers/register_server_types.cpp
+++ b/servers/register_server_types.cpp
@@ -85,17 +85,17 @@ ShaderTypes *shader_types = nullptr;
PhysicsServer3D *_createGodotPhysics3DCallback() {
bool using_threads = GLOBAL_GET("physics/3d/run_on_separate_thread");
- PhysicsServer3D *physics_server = memnew(GodotPhysicsServer3D(using_threads));
+ PhysicsServer3D *physics_server_3d = memnew(GodotPhysicsServer3D(using_threads));
- return memnew(PhysicsServer3DWrapMT(physics_server, using_threads));
+ return memnew(PhysicsServer3DWrapMT(physics_server_3d, using_threads));
}
PhysicsServer2D *_createGodotPhysics2DCallback() {
bool using_threads = GLOBAL_GET("physics/2d/run_on_separate_thread");
- PhysicsServer2D *physics_server = memnew(GodotPhysicsServer2D(using_threads));
+ PhysicsServer2D *physics_server_2d = memnew(GodotPhysicsServer2D(using_threads));
- return memnew(PhysicsServer2DWrapMT(physics_server, using_threads));
+ return memnew(PhysicsServer2DWrapMT(physics_server_2d, using_threads));
}
static bool has_server_feature_callback(const String &p_feature) {
diff --git a/servers/rendering/dummy/rasterizer_scene_dummy.h b/servers/rendering/dummy/rasterizer_scene_dummy.h
index 3855222554..fa58322ea8 100644
--- a/servers/rendering/dummy/rasterizer_scene_dummy.h
+++ b/servers/rendering/dummy/rasterizer_scene_dummy.h
@@ -184,7 +184,7 @@ public:
void voxel_gi_set_quality(RS::VoxelGIQuality) override {}
void render_scene(RID p_render_buffers, const CameraData *p_camera_data, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data = nullptr, RendererScene::RenderInfo *r_info = nullptr) override {}
- void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override {}
+ void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override {}
void render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) override {}
void set_scene_pass(uint64_t p_pass) override {}
diff --git a/servers/rendering/renderer_rd/SCsub b/servers/rendering/renderer_rd/SCsub
index d3ad381965..774a6b7951 100644
--- a/servers/rendering/renderer_rd/SCsub
+++ b/servers/rendering/renderer_rd/SCsub
@@ -4,6 +4,7 @@ Import("env")
env.add_source_files(env.servers_sources, "*.cpp")
+SConscript("effects/SCsub")
SConscript("forward_clustered/SCsub")
SConscript("forward_mobile/SCsub")
SConscript("shaders/SCsub")
diff --git a/servers/rendering/renderer_rd/effects/SCsub b/servers/rendering/renderer_rd/effects/SCsub
new file mode 100644
index 0000000000..86681f9c74
--- /dev/null
+++ b/servers/rendering/renderer_rd/effects/SCsub
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+
+Import("env")
+
+env.add_source_files(env.servers_sources, "*.cpp")
diff --git a/servers/rendering/renderer_rd/effects/tone_mapper.cpp b/servers/rendering/renderer_rd/effects/tone_mapper.cpp
new file mode 100644
index 0000000000..7eb15f418b
--- /dev/null
+++ b/servers/rendering/renderer_rd/effects/tone_mapper.cpp
@@ -0,0 +1,280 @@
+/*************************************************************************/
+/* tone_mapper.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "tone_mapper.h"
+#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
+#include "servers/rendering/renderer_rd/storage_rd/material_storage.h"
+#include "servers/rendering/renderer_rd/uniform_set_cache_rd.h"
+
+using namespace RendererRD;
+
+ToneMapper::ToneMapper() {
+ {
+ // Initialize tonemapper
+ Vector<String> tonemap_modes;
+ tonemap_modes.push_back("\n");
+ tonemap_modes.push_back("\n#define USE_GLOW_FILTER_BICUBIC\n");
+ tonemap_modes.push_back("\n#define USE_1D_LUT\n");
+ tonemap_modes.push_back("\n#define USE_GLOW_FILTER_BICUBIC\n#define USE_1D_LUT\n");
+ tonemap_modes.push_back("\n#define SUBPASS\n");
+ tonemap_modes.push_back("\n#define SUBPASS\n#define USE_1D_LUT\n");
+
+ // multiview versions of our shaders
+ tonemap_modes.push_back("\n#define MULTIVIEW\n");
+ tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_GLOW_FILTER_BICUBIC\n");
+ tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_1D_LUT\n");
+ tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_GLOW_FILTER_BICUBIC\n#define USE_1D_LUT\n");
+ tonemap_modes.push_back("\n#define MULTIVIEW\n#define SUBPASS\n");
+ tonemap_modes.push_back("\n#define MULTIVIEW\n#define SUBPASS\n#define USE_1D_LUT\n");
+
+ tonemap.shader.initialize(tonemap_modes);
+
+ if (!RendererCompositorRD::singleton->is_xr_enabled()) {
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_NORMAL_MULTIVIEW, false);
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_BICUBIC_GLOW_FILTER_MULTIVIEW, false);
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_1D_LUT_MULTIVIEW, false);
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT_MULTIVIEW, false);
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_SUBPASS_MULTIVIEW, false);
+ tonemap.shader.set_variant_enabled(TONEMAP_MODE_SUBPASS_1D_LUT_MULTIVIEW, false);
+ }
+
+ tonemap.shader_version = tonemap.shader.version_create();
+
+ for (int i = 0; i < TONEMAP_MODE_MAX; i++) {
+ if (tonemap.shader.is_variant_enabled(i)) {
+ tonemap.pipelines[i].setup(tonemap.shader.version_get_shader(tonemap.shader_version, i), RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0);
+ } else {
+ tonemap.pipelines[i].clear();
+ }
+ }
+ }
+
+ // TODO maybe centralise this in mesh_storage?
+ { //create index array for copy shaders
+ Vector<uint8_t> pv;
+ pv.resize(6 * 4);
+ {
+ uint8_t *w = pv.ptrw();
+ int *p32 = (int *)w;
+ p32[0] = 0;
+ p32[1] = 1;
+ p32[2] = 2;
+ p32[3] = 0;
+ p32[4] = 2;
+ p32[5] = 3;
+ }
+ index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT32, pv);
+ index_array = RD::get_singleton()->index_array_create(index_buffer, 0, 6);
+ }
+}
+
+ToneMapper::~ToneMapper() {
+ RD::get_singleton()->free(index_buffer); //array gets freed as dependency
+ tonemap.shader.version_free(tonemap.shader_version);
+}
+
+void ToneMapper::tonemapper(RID p_source_color, RID p_dst_framebuffer, const TonemapSettings &p_settings) {
+ UniformSetCacheRD *uniform_set_cache = UniformSetCacheRD::get_singleton();
+ ERR_FAIL_NULL(uniform_set_cache);
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ ERR_FAIL_NULL(material_storage);
+
+ memset(&tonemap.push_constant, 0, sizeof(TonemapPushConstant));
+
+ tonemap.push_constant.use_bcs = p_settings.use_bcs;
+ tonemap.push_constant.bcs[0] = p_settings.brightness;
+ tonemap.push_constant.bcs[1] = p_settings.contrast;
+ tonemap.push_constant.bcs[2] = p_settings.saturation;
+
+ tonemap.push_constant.use_glow = p_settings.use_glow;
+ tonemap.push_constant.glow_intensity = p_settings.glow_intensity;
+ tonemap.push_constant.glow_map_strength = p_settings.glow_map_strength;
+ tonemap.push_constant.glow_levels[0] = p_settings.glow_levels[0]; // clean this up to just pass by pointer or something
+ tonemap.push_constant.glow_levels[1] = p_settings.glow_levels[1];
+ tonemap.push_constant.glow_levels[2] = p_settings.glow_levels[2];
+ tonemap.push_constant.glow_levels[3] = p_settings.glow_levels[3];
+ tonemap.push_constant.glow_levels[4] = p_settings.glow_levels[4];
+ tonemap.push_constant.glow_levels[5] = p_settings.glow_levels[5];
+ tonemap.push_constant.glow_levels[6] = p_settings.glow_levels[6];
+ tonemap.push_constant.glow_texture_size[0] = p_settings.glow_texture_size.x;
+ tonemap.push_constant.glow_texture_size[1] = p_settings.glow_texture_size.y;
+ tonemap.push_constant.glow_mode = p_settings.glow_mode;
+
+ int mode = p_settings.glow_use_bicubic_upscale ? TONEMAP_MODE_BICUBIC_GLOW_FILTER : TONEMAP_MODE_NORMAL;
+ if (p_settings.use_1d_color_correction) {
+ mode += 2;
+ }
+
+ tonemap.push_constant.tonemapper = p_settings.tonemap_mode;
+ tonemap.push_constant.use_auto_exposure = p_settings.use_auto_exposure;
+ tonemap.push_constant.exposure = p_settings.exposure;
+ tonemap.push_constant.white = p_settings.white;
+ tonemap.push_constant.auto_exposure_grey = p_settings.auto_exposure_grey;
+ tonemap.push_constant.luminance_multiplier = p_settings.luminance_multiplier;
+
+ tonemap.push_constant.use_color_correction = p_settings.use_color_correction;
+
+ tonemap.push_constant.use_fxaa = p_settings.use_fxaa;
+ tonemap.push_constant.use_debanding = p_settings.use_debanding;
+ tonemap.push_constant.pixel_size[0] = 1.0 / p_settings.texture_size.x;
+ tonemap.push_constant.pixel_size[1] = 1.0 / p_settings.texture_size.y;
+
+ if (p_settings.view_count > 1) {
+ // Use MULTIVIEW versions
+ mode += 6;
+ }
+
+ RID default_shader = material_storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
+ RID default_mipmap_shader = material_storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
+
+ RD::Uniform u_source_color;
+ u_source_color.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_source_color.binding = 0;
+ u_source_color.append_id(default_shader);
+ u_source_color.append_id(p_source_color);
+
+ RD::Uniform u_exposure_texture;
+ u_exposure_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_exposure_texture.binding = 0;
+ u_exposure_texture.append_id(default_shader);
+ u_exposure_texture.append_id(p_settings.exposure_texture);
+
+ RD::Uniform u_glow_texture;
+ u_glow_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_glow_texture.binding = 0;
+ u_glow_texture.append_id(default_mipmap_shader);
+ u_glow_texture.append_id(p_settings.glow_texture);
+
+ RD::Uniform u_glow_map;
+ u_glow_map.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_glow_map.binding = 1;
+ u_glow_map.append_id(default_mipmap_shader);
+ u_glow_map.append_id(p_settings.glow_map);
+
+ RD::Uniform u_color_correction_texture;
+ u_color_correction_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_color_correction_texture.binding = 0;
+ u_color_correction_texture.append_id(default_shader);
+ u_color_correction_texture.append_id(p_settings.color_correction_texture);
+
+ RID shader = tonemap.shader.version_get_shader(tonemap.shader_version, mode);
+ ERR_FAIL_COND(shader.is_null());
+
+ RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_dst_framebuffer, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_DISCARD);
+ RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, tonemap.pipelines[mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_dst_framebuffer), false, RD::get_singleton()->draw_list_get_current_pass()));
+ RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set_cache->get_cache(shader, 0, u_source_color), 0);
+ RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set_cache->get_cache(shader, 1, u_exposure_texture), 1);
+ RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set_cache->get_cache(shader, 2, u_glow_texture, u_glow_map), 2);
+ RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set_cache->get_cache(shader, 3, u_color_correction_texture), 3);
+ RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array);
+
+ RD::get_singleton()->draw_list_set_push_constant(draw_list, &tonemap.push_constant, sizeof(TonemapPushConstant));
+ RD::get_singleton()->draw_list_draw(draw_list, true);
+ RD::get_singleton()->draw_list_end();
+}
+
+void ToneMapper::tonemapper(RD::DrawListID p_subpass_draw_list, RID p_source_color, RD::FramebufferFormatID p_dst_format_id, const TonemapSettings &p_settings) {
+ UniformSetCacheRD *uniform_set_cache = UniformSetCacheRD::get_singleton();
+ ERR_FAIL_NULL(uniform_set_cache);
+ MaterialStorage *material_storage = MaterialStorage::get_singleton();
+ ERR_FAIL_NULL(material_storage);
+
+ memset(&tonemap.push_constant, 0, sizeof(TonemapPushConstant));
+
+ tonemap.push_constant.use_bcs = p_settings.use_bcs;
+ tonemap.push_constant.bcs[0] = p_settings.brightness;
+ tonemap.push_constant.bcs[1] = p_settings.contrast;
+ tonemap.push_constant.bcs[2] = p_settings.saturation;
+
+ ERR_FAIL_COND_MSG(p_settings.use_glow, "Glow is not supported when using subpasses.");
+ tonemap.push_constant.use_glow = p_settings.use_glow;
+
+ int mode = p_settings.use_1d_color_correction ? TONEMAP_MODE_SUBPASS_1D_LUT : TONEMAP_MODE_SUBPASS;
+ if (p_settings.view_count > 1) {
+ // Use MULTIVIEW versions
+ mode += 6;
+ }
+
+ tonemap.push_constant.tonemapper = p_settings.tonemap_mode;
+ tonemap.push_constant.use_auto_exposure = p_settings.use_auto_exposure;
+ tonemap.push_constant.exposure = p_settings.exposure;
+ tonemap.push_constant.white = p_settings.white;
+ tonemap.push_constant.auto_exposure_grey = p_settings.auto_exposure_grey;
+
+ tonemap.push_constant.use_color_correction = p_settings.use_color_correction;
+
+ tonemap.push_constant.use_debanding = p_settings.use_debanding;
+ tonemap.push_constant.luminance_multiplier = p_settings.luminance_multiplier;
+
+ RID default_shader = material_storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
+ RID default_mipmap_shader = material_storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
+
+ RD::Uniform u_source_color;
+ u_source_color.uniform_type = RD::UNIFORM_TYPE_INPUT_ATTACHMENT;
+ u_source_color.binding = 0;
+ u_source_color.append_id(p_source_color);
+
+ RD::Uniform u_exposure_texture;
+ u_exposure_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_exposure_texture.binding = 0;
+ u_exposure_texture.append_id(default_shader);
+ u_exposure_texture.append_id(p_settings.exposure_texture);
+
+ RD::Uniform u_glow_texture;
+ u_glow_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_glow_texture.binding = 0;
+ u_glow_texture.append_id(default_mipmap_shader);
+ u_glow_texture.append_id(p_settings.glow_texture);
+
+ RD::Uniform u_glow_map;
+ u_glow_map.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_glow_map.binding = 1;
+ u_glow_map.append_id(default_mipmap_shader);
+ u_glow_map.append_id(p_settings.glow_map);
+
+ RD::Uniform u_color_correction_texture;
+ u_color_correction_texture.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
+ u_color_correction_texture.binding = 0;
+ u_color_correction_texture.append_id(default_shader);
+ u_color_correction_texture.append_id(p_settings.color_correction_texture);
+
+ RID shader = tonemap.shader.version_get_shader(tonemap.shader_version, mode);
+ ERR_FAIL_COND(shader.is_null());
+
+ RD::get_singleton()->draw_list_bind_render_pipeline(p_subpass_draw_list, tonemap.pipelines[mode].get_render_pipeline(RD::INVALID_ID, p_dst_format_id, false, RD::get_singleton()->draw_list_get_current_pass()));
+ RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, uniform_set_cache->get_cache(shader, 0, u_source_color), 0);
+ RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, uniform_set_cache->get_cache(shader, 1, u_exposure_texture), 1); // should be set to a default texture, it's ignored
+ RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, uniform_set_cache->get_cache(shader, 2, u_glow_texture, u_glow_map), 2); // should be set to a default texture, it's ignored
+ RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, uniform_set_cache->get_cache(shader, 3, u_color_correction_texture), 3);
+ RD::get_singleton()->draw_list_bind_index_array(p_subpass_draw_list, index_array);
+
+ RD::get_singleton()->draw_list_set_push_constant(p_subpass_draw_list, &tonemap.push_constant, sizeof(TonemapPushConstant));
+ RD::get_singleton()->draw_list_draw(p_subpass_draw_list, true);
+}
diff --git a/servers/rendering/renderer_rd/effects/tone_mapper.h b/servers/rendering/renderer_rd/effects/tone_mapper.h
new file mode 100644
index 0000000000..357e814845
--- /dev/null
+++ b/servers/rendering/renderer_rd/effects/tone_mapper.h
@@ -0,0 +1,155 @@
+/*************************************************************************/
+/* tone_mapper.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TONE_MAPPER_RD_H
+#define TONE_MAPPER_RD_H
+
+#include "servers/rendering/renderer_rd/pipeline_cache_rd.h"
+#include "servers/rendering/renderer_rd/shaders/effects/tonemap.glsl.gen.h"
+#include "servers/rendering/renderer_scene_render.h"
+
+#include "servers/rendering_server.h"
+
+namespace RendererRD {
+
+class ToneMapper {
+private:
+ enum TonemapMode {
+ TONEMAP_MODE_NORMAL,
+ TONEMAP_MODE_BICUBIC_GLOW_FILTER,
+ TONEMAP_MODE_1D_LUT,
+ TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT,
+ TONEMAP_MODE_SUBPASS,
+ TONEMAP_MODE_SUBPASS_1D_LUT,
+
+ TONEMAP_MODE_NORMAL_MULTIVIEW,
+ TONEMAP_MODE_BICUBIC_GLOW_FILTER_MULTIVIEW,
+ TONEMAP_MODE_1D_LUT_MULTIVIEW,
+ TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT_MULTIVIEW,
+ TONEMAP_MODE_SUBPASS_MULTIVIEW,
+ TONEMAP_MODE_SUBPASS_1D_LUT_MULTIVIEW,
+
+ TONEMAP_MODE_MAX
+ };
+
+ struct TonemapPushConstant {
+ float bcs[3]; // 12 - 12
+ uint32_t use_bcs; // 4 - 16
+
+ uint32_t use_glow; // 4 - 20
+ uint32_t use_auto_exposure; // 4 - 24
+ uint32_t use_color_correction; // 4 - 28
+ uint32_t tonemapper; // 4 - 32
+
+ uint32_t glow_texture_size[2]; // 8 - 40
+ float glow_intensity; // 4 - 44
+ float glow_map_strength; // 4 - 48
+
+ uint32_t glow_mode; // 4 - 52
+ float glow_levels[7]; // 28 - 80
+
+ float exposure; // 4 - 84
+ float white; // 4 - 88
+ float auto_exposure_grey; // 4 - 92
+ float luminance_multiplier; // 4 - 96
+
+ float pixel_size[2]; // 8 - 104
+ uint32_t use_fxaa; // 4 - 108
+ uint32_t use_debanding; // 4 - 112
+ };
+
+ /* tonemap actually writes to a framebuffer, which is
+ * better to do using the raster pipeline rather than
+ * compute, as that framebuffer might be in different formats
+ */
+ struct Tonemap {
+ TonemapPushConstant push_constant;
+ TonemapShaderRD shader;
+ RID shader_version;
+ PipelineCacheRD pipelines[TONEMAP_MODE_MAX];
+ } tonemap;
+
+ RID index_buffer;
+ RID index_array;
+
+public:
+ ToneMapper();
+ ~ToneMapper();
+
+ struct TonemapSettings {
+ bool use_glow = false;
+ enum GlowMode {
+ GLOW_MODE_ADD,
+ GLOW_MODE_SCREEN,
+ GLOW_MODE_SOFTLIGHT,
+ GLOW_MODE_REPLACE,
+ GLOW_MODE_MIX
+ };
+
+ GlowMode glow_mode = GLOW_MODE_ADD;
+ float glow_intensity = 1.0;
+ float glow_map_strength = 0.0f;
+ float glow_levels[7] = { 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0 };
+ Vector2i glow_texture_size;
+ bool glow_use_bicubic_upscale = false;
+ RID glow_texture;
+ RID glow_map;
+
+ RS::EnvironmentToneMapper tonemap_mode = RS::ENV_TONE_MAPPER_LINEAR;
+ float exposure = 1.0;
+ float white = 1.0;
+
+ bool use_auto_exposure = false;
+ float auto_exposure_grey = 0.5;
+ RID exposure_texture;
+ float luminance_multiplier = 1.0;
+
+ bool use_bcs = false;
+ float brightness = 1.0;
+ float contrast = 1.0;
+ float saturation = 1.0;
+
+ bool use_color_correction = false;
+ bool use_1d_color_correction = false;
+ RID color_correction_texture;
+
+ bool use_fxaa = false;
+ bool use_debanding = false;
+ Vector2i texture_size;
+ uint32_t view_count = 1;
+ };
+
+ void tonemapper(RID p_source_color, RID p_dst_framebuffer, const TonemapSettings &p_settings);
+ void tonemapper(RD::DrawListID p_subpass_draw_list, RID p_source_color, RD::FramebufferFormatID p_dst_format_id, const TonemapSettings &p_settings);
+};
+
+} // namespace RendererRD
+
+#endif // !TONE_MAPPER_RD_H
diff --git a/servers/rendering/renderer_rd/effects_rd.cpp b/servers/rendering/renderer_rd/effects_rd.cpp
index a5a9dae0b9..f05027d569 100644
--- a/servers/rendering/renderer_rd/effects_rd.cpp
+++ b/servers/rendering/renderer_rd/effects_rd.cpp
@@ -70,28 +70,6 @@ RID EffectsRD::_get_uniform_set_from_image(RID p_image) {
return uniform_set;
}
-RID EffectsRD::_get_uniform_set_for_input(RID p_texture) {
- if (input_to_uniform_set_cache.has(p_texture)) {
- RID uniform_set = input_to_uniform_set_cache[p_texture];
- if (RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
- return uniform_set;
- }
- }
-
- Vector<RD::Uniform> uniforms;
- RD::Uniform u;
- u.uniform_type = RD::UNIFORM_TYPE_INPUT_ATTACHMENT;
- u.binding = 0;
- u.append_id(p_texture);
- uniforms.push_back(u);
- // This is specific to our subpass shader
- RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, tonemap.shader.version_get_shader(tonemap.shader_version, TONEMAP_MODE_SUBPASS), 0);
-
- input_to_uniform_set_cache[p_texture] = uniform_set;
-
- return uniform_set;
-}
-
RID EffectsRD::_get_uniform_set_from_texture(RID p_texture, bool p_use_mipmaps) {
if (texture_to_uniform_set_cache.has(p_texture)) {
RID uniform_set = texture_to_uniform_set_cache[p_texture];
@@ -108,50 +86,13 @@ RID EffectsRD::_get_uniform_set_from_texture(RID p_texture, bool p_use_mipmaps)
u.append_id(p_texture);
uniforms.push_back(u);
// anything with the same configuration (one texture in binding 0 for set 0), is good
- RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, tonemap.shader.version_get_shader(tonemap.shader_version, 0), 0);
+ RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, copy_to_fb.shader.version_get_shader(copy_to_fb.shader_version, 0), 0);
texture_to_uniform_set_cache[p_texture] = uniform_set;
return uniform_set;
}
-RID EffectsRD::_get_uniform_set_from_texture_pair(RID p_texture1, RID p_texture2, bool p_use_mipmaps) {
- TexturePair tp;
- tp.texture1 = p_texture1;
- tp.texture2 = p_texture2;
-
- if (texture_pair_to_uniform_set_cache.has(tp)) {
- RID uniform_set = texture_pair_to_uniform_set_cache[tp];
- if (RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
- return uniform_set;
- }
- }
-
- Vector<RD::Uniform> uniforms;
- {
- RD::Uniform u;
- u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
- u.binding = 0;
- u.append_id(p_use_mipmaps ? default_mipmap_sampler : default_sampler);
- u.append_id(p_texture1);
- uniforms.push_back(u);
- }
- {
- RD::Uniform u;
- u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
- u.binding = 1;
- u.append_id(p_use_mipmaps ? default_mipmap_sampler : default_sampler);
- u.append_id(p_texture2);
- uniforms.push_back(u);
- }
- // anything with the same configuration (one texture in binding 0 for set 0), is good
- RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, tonemap.shader.version_get_shader(tonemap.shader_version, 0), 2);
-
- texture_pair_to_uniform_set_cache[tp] = uniform_set;
-
- return uniform_set;
-}
-
RID EffectsRD::_get_compute_uniform_set_from_texture(RID p_texture, bool p_use_mipmaps) {
if (texture_to_compute_uniform_set_cache.has(p_texture)) {
RID uniform_set = texture_to_compute_uniform_set_cache[p_texture];
@@ -851,105 +792,6 @@ void EffectsRD::copy_cubemap_to_dp(RID p_source_rd_texture, RID p_dst_framebuffe
RD::get_singleton()->draw_list_end(RD::BARRIER_MASK_RASTER | RD::BARRIER_MASK_TRANSFER);
}
-void EffectsRD::tonemapper(RID p_source_color, RID p_dst_framebuffer, const TonemapSettings &p_settings) {
- memset(&tonemap.push_constant, 0, sizeof(TonemapPushConstant));
-
- tonemap.push_constant.use_bcs = p_settings.use_bcs;
- tonemap.push_constant.bcs[0] = p_settings.brightness;
- tonemap.push_constant.bcs[1] = p_settings.contrast;
- tonemap.push_constant.bcs[2] = p_settings.saturation;
-
- tonemap.push_constant.use_glow = p_settings.use_glow;
- tonemap.push_constant.glow_intensity = p_settings.glow_intensity;
- tonemap.push_constant.glow_map_strength = p_settings.glow_map_strength;
- tonemap.push_constant.glow_levels[0] = p_settings.glow_levels[0]; // clean this up to just pass by pointer or something
- tonemap.push_constant.glow_levels[1] = p_settings.glow_levels[1];
- tonemap.push_constant.glow_levels[2] = p_settings.glow_levels[2];
- tonemap.push_constant.glow_levels[3] = p_settings.glow_levels[3];
- tonemap.push_constant.glow_levels[4] = p_settings.glow_levels[4];
- tonemap.push_constant.glow_levels[5] = p_settings.glow_levels[5];
- tonemap.push_constant.glow_levels[6] = p_settings.glow_levels[6];
- tonemap.push_constant.glow_texture_size[0] = p_settings.glow_texture_size.x;
- tonemap.push_constant.glow_texture_size[1] = p_settings.glow_texture_size.y;
- tonemap.push_constant.glow_mode = p_settings.glow_mode;
-
- int mode = p_settings.glow_use_bicubic_upscale ? TONEMAP_MODE_BICUBIC_GLOW_FILTER : TONEMAP_MODE_NORMAL;
- if (p_settings.use_1d_color_correction) {
- mode += 2;
- }
-
- tonemap.push_constant.tonemapper = p_settings.tonemap_mode;
- tonemap.push_constant.use_auto_exposure = p_settings.use_auto_exposure;
- tonemap.push_constant.exposure = p_settings.exposure;
- tonemap.push_constant.white = p_settings.white;
- tonemap.push_constant.auto_exposure_grey = p_settings.auto_exposure_grey;
- tonemap.push_constant.luminance_multiplier = p_settings.luminance_multiplier;
-
- tonemap.push_constant.use_color_correction = p_settings.use_color_correction;
-
- tonemap.push_constant.use_fxaa = p_settings.use_fxaa;
- tonemap.push_constant.use_debanding = p_settings.use_debanding;
- tonemap.push_constant.pixel_size[0] = 1.0 / p_settings.texture_size.x;
- tonemap.push_constant.pixel_size[1] = 1.0 / p_settings.texture_size.y;
-
- if (p_settings.view_count > 1) {
- // Use MULTIVIEW versions
- mode += 6;
- }
-
- RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_dst_framebuffer, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_DISCARD);
- RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, tonemap.pipelines[mode].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_dst_framebuffer), false, RD::get_singleton()->draw_list_get_current_pass()));
- RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_source_color), 0);
- RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_settings.exposure_texture), 1);
- RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture_pair(p_settings.glow_texture, p_settings.glow_map, true), 2);
- RD::get_singleton()->draw_list_bind_uniform_set(draw_list, _get_uniform_set_from_texture(p_settings.color_correction_texture), 3);
- RD::get_singleton()->draw_list_bind_index_array(draw_list, index_array);
-
- RD::get_singleton()->draw_list_set_push_constant(draw_list, &tonemap.push_constant, sizeof(TonemapPushConstant));
- RD::get_singleton()->draw_list_draw(draw_list, true);
- RD::get_singleton()->draw_list_end();
-}
-
-void EffectsRD::tonemapper(RD::DrawListID p_subpass_draw_list, RID p_source_color, RD::FramebufferFormatID p_dst_format_id, const TonemapSettings &p_settings) {
- memset(&tonemap.push_constant, 0, sizeof(TonemapPushConstant));
-
- tonemap.push_constant.use_bcs = p_settings.use_bcs;
- tonemap.push_constant.bcs[0] = p_settings.brightness;
- tonemap.push_constant.bcs[1] = p_settings.contrast;
- tonemap.push_constant.bcs[2] = p_settings.saturation;
-
- ERR_FAIL_COND_MSG(p_settings.use_glow, "Glow is not supported when using subpasses.");
- tonemap.push_constant.use_glow = p_settings.use_glow;
-
- int mode = p_settings.use_1d_color_correction ? TONEMAP_MODE_SUBPASS_1D_LUT : TONEMAP_MODE_SUBPASS;
- if (p_settings.view_count > 1) {
- // Use MULTIVIEW versions
- mode += 6;
- }
-
- tonemap.push_constant.tonemapper = p_settings.tonemap_mode;
- tonemap.push_constant.use_auto_exposure = p_settings.use_auto_exposure;
- tonemap.push_constant.exposure = p_settings.exposure;
- tonemap.push_constant.white = p_settings.white;
- tonemap.push_constant.auto_exposure_grey = p_settings.auto_exposure_grey;
-
- tonemap.push_constant.use_color_correction = p_settings.use_color_correction;
-
- tonemap.push_constant.use_debanding = p_settings.use_debanding;
- tonemap.push_constant.luminance_multiplier = p_settings.luminance_multiplier;
-
- RD::get_singleton()->draw_list_bind_render_pipeline(p_subpass_draw_list, tonemap.pipelines[mode].get_render_pipeline(RD::INVALID_ID, p_dst_format_id, false, RD::get_singleton()->draw_list_get_current_pass()));
- RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, _get_uniform_set_for_input(p_source_color), 0);
- RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, _get_uniform_set_from_texture(p_settings.exposure_texture), 1); // should be set to a default texture, it's ignored
- RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, _get_uniform_set_from_texture_pair(p_settings.glow_texture, p_settings.glow_map, true), 2); // should be set to a default texture, it's ignored
- RD::get_singleton()->draw_list_bind_uniform_set(p_subpass_draw_list, _get_uniform_set_from_texture(p_settings.color_correction_texture), 3);
-
- RD::get_singleton()->draw_list_bind_index_array(p_subpass_draw_list, index_array);
-
- RD::get_singleton()->draw_list_set_push_constant(p_subpass_draw_list, &tonemap.push_constant, sizeof(TonemapPushConstant));
- RD::get_singleton()->draw_list_draw(p_subpass_draw_list, true);
-}
-
void EffectsRD::luminance_reduction(RID p_source_texture, const Size2i p_source_size, const Vector<RID> p_reduce, RID p_prev_luminance, float p_min_luminance, float p_max_luminance, float p_adjust, bool p_set) {
ERR_FAIL_COND_MSG(prefer_raster_effects, "Can't use compute version of luminance reduction with the mobile renderer.");
@@ -2420,46 +2262,6 @@ EffectsRD::EffectsRD(bool p_prefer_raster_effects) {
}
}
- {
- // Initialize tonemapper
- Vector<String> tonemap_modes;
- tonemap_modes.push_back("\n");
- tonemap_modes.push_back("\n#define USE_GLOW_FILTER_BICUBIC\n");
- tonemap_modes.push_back("\n#define USE_1D_LUT\n");
- tonemap_modes.push_back("\n#define USE_GLOW_FILTER_BICUBIC\n#define USE_1D_LUT\n");
- tonemap_modes.push_back("\n#define SUBPASS\n");
- tonemap_modes.push_back("\n#define SUBPASS\n#define USE_1D_LUT\n");
-
- // multiview versions of our shaders
- tonemap_modes.push_back("\n#define MULTIVIEW\n");
- tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_GLOW_FILTER_BICUBIC\n");
- tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_1D_LUT\n");
- tonemap_modes.push_back("\n#define MULTIVIEW\n#define USE_GLOW_FILTER_BICUBIC\n#define USE_1D_LUT\n");
- tonemap_modes.push_back("\n#define MULTIVIEW\n#define SUBPASS\n");
- tonemap_modes.push_back("\n#define MULTIVIEW\n#define SUBPASS\n#define USE_1D_LUT\n");
-
- tonemap.shader.initialize(tonemap_modes);
-
- if (!RendererCompositorRD::singleton->is_xr_enabled()) {
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_NORMAL_MULTIVIEW, false);
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_BICUBIC_GLOW_FILTER_MULTIVIEW, false);
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_1D_LUT_MULTIVIEW, false);
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT_MULTIVIEW, false);
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_SUBPASS_MULTIVIEW, false);
- tonemap.shader.set_variant_enabled(TONEMAP_MODE_SUBPASS_1D_LUT_MULTIVIEW, false);
- }
-
- tonemap.shader_version = tonemap.shader.version_create();
-
- for (int i = 0; i < TONEMAP_MODE_MAX; i++) {
- if (tonemap.shader.is_variant_enabled(i)) {
- tonemap.pipelines[i].setup(tonemap.shader.version_get_shader(tonemap.shader_version, i), RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0);
- } else {
- tonemap.pipelines[i].clear();
- }
- }
- }
-
if (prefer_raster_effects) {
Vector<String> luminance_reduce_modes;
luminance_reduce_modes.push_back("\n#define FIRST_PASS\n"); // LUMINANCE_REDUCE_FRAGMENT_FIRST
@@ -3076,5 +2878,4 @@ EffectsRD::~EffectsRD() {
copy_to_fb.shader.version_free(copy_to_fb.shader_version);
cube_to_dp.shader.version_free(cube_to_dp.shader_version);
sort.shader.version_free(sort.shader_version);
- tonemap.shader.version_free(tonemap.shader_version);
}
diff --git a/servers/rendering/renderer_rd/effects_rd.h b/servers/rendering/renderer_rd/effects_rd.h
index eca5e09800..8174e30238 100644
--- a/servers/rendering/renderer_rd/effects_rd.h
+++ b/servers/rendering/renderer_rd/effects_rd.h
@@ -65,7 +65,6 @@
#include "servers/rendering/renderer_rd/shaders/ssil_importance_map.glsl.gen.h"
#include "servers/rendering/renderer_rd/shaders/ssil_interleave.glsl.gen.h"
#include "servers/rendering/renderer_rd/shaders/subsurface_scattering.glsl.gen.h"
-#include "servers/rendering/renderer_rd/shaders/tonemap.glsl.gen.h"
#include "servers/rendering/renderer_scene_render.h"
#include "servers/rendering_server.h"
@@ -248,61 +247,6 @@ private:
PipelineCacheRD raster_pipeline;
} roughness;
- enum TonemapMode {
- TONEMAP_MODE_NORMAL,
- TONEMAP_MODE_BICUBIC_GLOW_FILTER,
- TONEMAP_MODE_1D_LUT,
- TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT,
- TONEMAP_MODE_SUBPASS,
- TONEMAP_MODE_SUBPASS_1D_LUT,
-
- TONEMAP_MODE_NORMAL_MULTIVIEW,
- TONEMAP_MODE_BICUBIC_GLOW_FILTER_MULTIVIEW,
- TONEMAP_MODE_1D_LUT_MULTIVIEW,
- TONEMAP_MODE_BICUBIC_GLOW_FILTER_1D_LUT_MULTIVIEW,
- TONEMAP_MODE_SUBPASS_MULTIVIEW,
- TONEMAP_MODE_SUBPASS_1D_LUT_MULTIVIEW,
-
- TONEMAP_MODE_MAX
- };
-
- struct TonemapPushConstant {
- float bcs[3]; // 12 - 12
- uint32_t use_bcs; // 4 - 16
-
- uint32_t use_glow; // 4 - 20
- uint32_t use_auto_exposure; // 4 - 24
- uint32_t use_color_correction; // 4 - 28
- uint32_t tonemapper; // 4 - 32
-
- uint32_t glow_texture_size[2]; // 8 - 40
- float glow_intensity; // 4 - 44
- float glow_map_strength; // 4 - 48
-
- uint32_t glow_mode; // 4 - 52
- float glow_levels[7]; // 28 - 80
-
- float exposure; // 4 - 84
- float white; // 4 - 88
- float auto_exposure_grey; // 4 - 92
- float luminance_multiplier; // 4 - 96
-
- float pixel_size[2]; // 8 - 104
- uint32_t use_fxaa; // 4 - 108
- uint32_t use_debanding; // 4 - 112
- };
-
- /* tonemap actually writes to a framebuffer, which is
- * better to do using the raster pipeline rather than
- * compute, as that framebuffer might be in different formats
- */
- struct Tonemap {
- TonemapPushConstant push_constant;
- TonemapShaderRD shader;
- RID shader_version;
- PipelineCacheRD pipelines[TONEMAP_MODE_MAX];
- } tonemap;
-
enum LuminanceReduceMode {
LUMINANCE_REDUCE_READ,
LUMINANCE_REDUCE,
@@ -884,9 +828,7 @@ private:
Map<TextureSamplerPair, RID> texture_sampler_to_compute_uniform_set_cache;
RID _get_uniform_set_from_image(RID p_texture);
- RID _get_uniform_set_for_input(RID p_texture);
RID _get_uniform_set_from_texture(RID p_texture, bool p_use_mipmaps = false);
- RID _get_uniform_set_from_texture_pair(RID p_texture1, RID p_texture2, bool p_use_mipmaps = false);
RID _get_compute_uniform_set_from_texture(RID p_texture, bool p_use_mipmaps = false);
RID _get_compute_uniform_set_from_texture_and_sampler(RID p_texture, RID p_sampler);
RID _get_compute_uniform_set_from_texture_pair(RID p_texture, RID p_texture2, bool p_use_mipmaps = false);
@@ -936,49 +878,6 @@ public:
void bokeh_dof(const BokehBuffers &p_buffers, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_bokeh_size, RS::DOFBokehShape p_bokeh_shape, RS::DOFBlurQuality p_quality, bool p_use_jitter, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal);
void bokeh_dof_raster(const BokehBuffers &p_buffers, bool p_dof_far, float p_dof_far_begin, float p_dof_far_size, bool p_dof_near, float p_dof_near_begin, float p_dof_near_size, float p_dof_blur_amount, RenderingServer::DOFBokehShape p_bokeh_shape, RS::DOFBlurQuality p_quality, float p_cam_znear, float p_cam_zfar, bool p_cam_orthogonal);
- struct TonemapSettings {
- bool use_glow = false;
- enum GlowMode {
- GLOW_MODE_ADD,
- GLOW_MODE_SCREEN,
- GLOW_MODE_SOFTLIGHT,
- GLOW_MODE_REPLACE,
- GLOW_MODE_MIX
- };
-
- GlowMode glow_mode = GLOW_MODE_ADD;
- float glow_intensity = 1.0;
- float glow_map_strength = 0.0f;
- float glow_levels[7] = { 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0 };
- Vector2i glow_texture_size;
- bool glow_use_bicubic_upscale = false;
- RID glow_texture;
- RID glow_map;
-
- RS::EnvironmentToneMapper tonemap_mode = RS::ENV_TONE_MAPPER_LINEAR;
- float exposure = 1.0;
- float white = 1.0;
-
- bool use_auto_exposure = false;
- float auto_exposure_grey = 0.5;
- RID exposure_texture;
- float luminance_multiplier = 1.0;
-
- bool use_bcs = false;
- float brightness = 1.0;
- float contrast = 1.0;
- float saturation = 1.0;
-
- bool use_color_correction = false;
- bool use_1d_color_correction = false;
- RID color_correction_texture;
-
- bool use_fxaa = false;
- bool use_debanding = false;
- Vector2i texture_size;
- uint32_t view_count = 1;
- };
-
struct SSAOSettings {
float radius = 1.0;
float intensity = 2.0;
@@ -1017,9 +916,6 @@ public:
Size2i quarter_screen_size = Size2i();
};
- void tonemapper(RID p_source_color, RID p_dst_framebuffer, const TonemapSettings &p_settings);
- void tonemapper(RD::DrawListID p_subpass_draw_list, RID p_source_color, RD::FramebufferFormatID p_dst_format_id, const TonemapSettings &p_settings);
-
void downsample_depth(RID p_depth_buffer, const Vector<RID> &p_depth_mipmaps, RS::EnvironmentSSAOQuality p_ssao_quality, RS::EnvironmentSSILQuality p_ssil_quality, bool p_invalidate_uniform_set, bool p_ssao_half_size, bool p_ssil_half_size, Size2i p_full_screen_size, const CameraMatrix &p_projection);
void gather_ssao(RD::ComputeListID p_compute_list, const Vector<RID> p_ao_slices, const SSAOSettings &p_settings, bool p_adaptive_base_pass, RID p_gather_uniform_set, RID p_importance_map_uniform_set);
diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
index 93baa9a96f..ace948d149 100644
--- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
+++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
@@ -210,7 +210,7 @@ void RenderForwardClustered::RenderBufferDataForwardClustered::configure(RID p_c
tf.array_layers = view_count; // create a layer for every view
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
- RD::TextureSamples ts[RS::VIEWPORT_MSAA_MAX] = {
+ const RD::TextureSamples ts[RS::VIEWPORT_MSAA_MAX] = {
RD::TEXTURE_SAMPLES_1,
RD::TEXTURE_SAMPLES_2,
RD::TEXTURE_SAMPLES_4,
@@ -1124,7 +1124,7 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con
distance = -distance_max;
}
- if (p_render_data->cam_ortogonal) {
+ if (p_render_data->cam_orthogonal) {
distance = 1.0;
}
@@ -1815,7 +1815,7 @@ void RenderForwardClustered::_render_particle_collider_heightfield(RID p_fb, con
RD::get_singleton()->draw_command_end_label();
}
-void RenderForwardClustered::_render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
+void RenderForwardClustered::_render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
RENDER_TIMESTAMP("Setup Rendering 3D Material");
RD::get_singleton()->draw_command_begin_label("Render 3D Material");
diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h
index 37366d3e14..0e588aecb4 100644
--- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h
+++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h
@@ -218,7 +218,7 @@ class RenderForwardClustered : public RendererSceneRenderRD {
INSTANCE_DATA_FLAGS_PARTICLE_TRAIL_SHIFT = 16,
INSTANCE_DATA_FLAGS_PARTICLE_TRAIL_MASK = 0xFF,
INSTANCE_DATA_FLAGS_FADE_SHIFT = 24,
- INSTANCE_DATA_FLAGS_FADE_MASK = 0xFF << INSTANCE_DATA_FLAGS_FADE_SHIFT
+ INSTANCE_DATA_FLAGS_FADE_MASK = 0xFFUL << INSTANCE_DATA_FLAGS_FADE_SHIFT
};
struct SceneState {
@@ -611,7 +611,7 @@ protected:
virtual void _render_shadow_process() override;
virtual void _render_shadow_end(uint32_t p_barrier = RD::BARRIER_MASK_ALL) override;
- virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
+ virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
virtual void _render_uv2(const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
virtual void _render_sdfgi(RID p_render_buffers, const Vector3i &p_from, const Vector3i &p_size, const AABB &p_bounds, const PagedArray<GeometryInstance *> &p_instances, const RID &p_albedo_texture, const RID &p_emission_texture, const RID &p_emission_aniso_texture, const RID &p_geom_facing_texture) override;
virtual void _render_particle_collider_heightfield(RID p_fb, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, const PagedArray<GeometryInstance *> &p_instances) override;
diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
index ade2b976c8..b9f49cf008 100644
--- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
+++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
@@ -158,7 +158,7 @@ void RenderForwardMobile::RenderBufferDataForwardMobile::configure(RID p_color_b
tf.array_layers = view_count; // create a layer for every view
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
- RD::TextureSamples ts[RS::VIEWPORT_MSAA_MAX] = {
+ const RD::TextureSamples ts[RS::VIEWPORT_MSAA_MAX] = {
RD::TEXTURE_SAMPLES_1,
RD::TEXTURE_SAMPLES_2,
RD::TEXTURE_SAMPLES_4,
@@ -977,7 +977,7 @@ void RenderForwardMobile::_render_shadow_end(uint32_t p_barrier) {
/* */
-void RenderForwardMobile::_render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
+void RenderForwardMobile::_render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
RENDER_TIMESTAMP("Setup Rendering 3D Material");
RD::get_singleton()->draw_command_begin_label("Render 3D Material");
@@ -1441,7 +1441,7 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const
distance = -distance_max;
}
- if (p_render_data->cam_ortogonal) {
+ if (p_render_data->cam_orthogonal) {
distance = 1.0;
}
diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h
index 0ddfe89eea..0a7e973120 100644
--- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h
+++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h
@@ -214,7 +214,7 @@ protected:
virtual void _render_shadow_process() override;
virtual void _render_shadow_end(uint32_t p_barrier = RD::BARRIER_MASK_ALL) override;
- virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
+ virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
virtual void _render_uv2(const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
virtual void _render_sdfgi(RID p_render_buffers, const Vector3i &p_from, const Vector3i &p_size, const AABB &p_bounds, const PagedArray<GeometryInstance *> &p_instances, const RID &p_albedo_texture, const RID &p_emission_texture, const RID &p_emission_aniso_texture, const RID &p_geom_facing_texture) override;
virtual void _render_particle_collider_heightfield(RID p_fb, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, const PagedArray<GeometryInstance *> &p_instances) override;
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
index 29bc767c86..8c727b2512 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
@@ -132,9 +132,9 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve
buffers.resize(5);
{
- const uint8_t *r = polygon_buffer.ptr();
- float *fptr = (float *)r;
- uint32_t *uptr = (uint32_t *)r;
+ uint8_t *r = polygon_buffer.ptrw();
+ float *fptr = reinterpret_cast<float *>(r);
+ uint32_t *uptr = reinterpret_cast<uint32_t *>(r);
uint32_t base_offset = 0;
{ //vertices
RD::VertexAttribute vd;
@@ -1843,7 +1843,7 @@ void RendererCanvasRenderRD::occluder_polygon_set_shape(RID p_occluder, const Ve
{
uint8_t *vw = geometry.ptrw();
- float *vwptr = (float *)vw;
+ float *vwptr = reinterpret_cast<float *>(vw);
uint8_t *iw = indices.ptrw();
uint16_t *iwptr = (uint16_t *)iw;
diff --git a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
index d8b7d5384e..0a16bf4bd1 100644
--- a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
@@ -879,7 +879,7 @@ void RendererSceneGIRD::SDFGI::update_light() {
push_constant.process_offset = 0;
push_constant.process_increment = 1;
} else {
- static uint32_t frames_to_update_table[RS::ENV_SDFGI_UPDATE_LIGHT_MAX] = {
+ static const uint32_t frames_to_update_table[RS::ENV_SDFGI_UPDATE_LIGHT_MAX] = {
1, 2, 4, 8, 16
};
diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
index bdbc228bde..26365aafc4 100644
--- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
@@ -2391,7 +2391,7 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende
float bokeh_size = camfx->dof_blur_amount * 64.0;
if (can_use_storage) {
- storage->get_effects()->bokeh_dof(buffers, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_ortogonal);
+ storage->get_effects()->bokeh_dof(buffers, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_orthogonal);
} else {
// Set framebuffers.
buffers.base_fb = rb->texture_fb;
@@ -2406,7 +2406,7 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende
// Set weight buffers.
buffers.base_weight_fb = rb->base_weight_fb;
- storage->get_effects()->bokeh_dof_raster(buffers, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_ortogonal);
+ storage->get_effects()->bokeh_dof_raster(buffers, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, p_render_data->z_near, p_render_data->z_far, p_render_data->cam_orthogonal);
}
RD::get_singleton()->draw_command_end_label();
}
@@ -2486,7 +2486,7 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende
{
RD::get_singleton()->draw_command_begin_label("Tonemap");
- EffectsRD::TonemapSettings tonemap;
+ RendererRD::ToneMapper::TonemapSettings tonemap;
if (can_use_effects && env && env->auto_exposure && rb->luminance.current.is_valid()) {
tonemap.use_auto_exposure = true;
@@ -2498,7 +2498,7 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende
if (can_use_effects && env && env->glow_enabled) {
tonemap.use_glow = true;
- tonemap.glow_mode = EffectsRD::TonemapSettings::GlowMode(env->glow_blend_mode);
+ tonemap.glow_mode = RendererRD::ToneMapper::TonemapSettings::GlowMode(env->glow_blend_mode);
tonemap.glow_intensity = env->glow_blend_mode == RS::ENV_GLOW_BLEND_MODE_MIX ? env->glow_mix : env->glow_intensity;
for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
tonemap.glow_levels[i] = env->glow_levels[i];
@@ -2556,7 +2556,7 @@ void RendererSceneRenderRD::_render_buffers_post_process_and_tonemap(const Rende
tonemap.luminance_multiplier = _render_buffers_get_luminance_multiplier();
tonemap.view_count = p_render_data->view_count;
- storage->get_effects()->tonemapper(rb->internal_texture, texture_storage->render_target_get_rd_framebuffer(rb->render_target), tonemap);
+ tone_mapper->tonemapper(rb->internal_texture, texture_storage->render_target_get_rd_framebuffer(rb->render_target), tonemap);
RD::get_singleton()->draw_command_end_label();
}
@@ -2587,7 +2587,7 @@ void RendererSceneRenderRD::_post_process_subpass(RID p_source_texture, RID p_fr
RD::DrawListID draw_list = RD::get_singleton()->draw_list_switch_to_next_pass();
- EffectsRD::TonemapSettings tonemap;
+ RendererRD::ToneMapper::TonemapSettings tonemap;
if (env) {
tonemap.tonemap_mode = env->tone_mapper;
@@ -2637,7 +2637,7 @@ void RendererSceneRenderRD::_post_process_subpass(RID p_source_texture, RID p_fr
tonemap.luminance_multiplier = _render_buffers_get_luminance_multiplier();
tonemap.view_count = p_render_data->view_count;
- storage->get_effects()->tonemapper(draw_list, p_source_texture, RD::get_singleton()->framebuffer_get_format(p_framebuffer), tonemap);
+ tone_mapper->tonemapper(draw_list, p_source_texture, RD::get_singleton()->framebuffer_get_format(p_framebuffer), tonemap);
RD::get_singleton()->draw_command_end_label();
}
@@ -4998,7 +4998,7 @@ void RendererSceneRenderRD::render_scene(RID p_render_buffers, const CameraData
render_data.cam_transform = p_camera_data->main_transform;
render_data.cam_projection = p_camera_data->main_projection;
render_data.view_projection[0] = p_camera_data->main_projection;
- render_data.cam_ortogonal = p_camera_data->is_ortogonal;
+ render_data.cam_orthogonal = p_camera_data->is_orthogonal;
render_data.view_count = p_camera_data->view_count;
for (uint32_t v = 0; v < p_camera_data->view_count; v++) {
@@ -5327,8 +5327,8 @@ void RendererSceneRenderRD::_render_shadow_pass(RID p_light, RID p_shadow_atlas,
}
}
-void RendererSceneRenderRD::render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
- _render_material(p_cam_transform, p_cam_projection, p_cam_ortogonal, p_instances, p_framebuffer, p_region);
+void RendererSceneRenderRD::render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
+ _render_material(p_cam_transform, p_cam_projection, p_cam_orthogonal, p_instances, p_framebuffer, p_region);
}
void RendererSceneRenderRD::render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) {
@@ -5838,11 +5838,17 @@ void fog() {
light_projectors_set_filter(RS::LightProjectorFilter(int(GLOBAL_GET("rendering/textures/light_projectors/filter"))));
cull_argument.set_page_pool(&cull_argument_pool);
+
+ tone_mapper = memnew(RendererRD::ToneMapper);
}
RendererSceneRenderRD::~RendererSceneRenderRD() {
RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
+ if (tone_mapper) {
+ memdelete(tone_mapper);
+ }
+
for (const KeyValue<int, ShadowCubemap> &E : shadow_cubemaps) {
RD::get_singleton()->free(E.value.cubemap);
}
diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.h b/servers/rendering/renderer_rd/renderer_scene_render_rd.h
index b2c8daffb1..2b79d8997f 100644
--- a/servers/rendering/renderer_rd/renderer_scene_render_rd.h
+++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.h
@@ -35,6 +35,7 @@
#include "core/templates/rid_owner.h"
#include "servers/rendering/renderer_compositor.h"
#include "servers/rendering/renderer_rd/cluster_builder_rd.h"
+#include "servers/rendering/renderer_rd/effects/tone_mapper.h"
#include "servers/rendering/renderer_rd/renderer_scene_environment_rd.h"
#include "servers/rendering/renderer_rd/renderer_scene_gi_rd.h"
#include "servers/rendering/renderer_rd/renderer_scene_sky_rd.h"
@@ -50,7 +51,7 @@ struct RenderDataRD {
Transform3D cam_transform = Transform3D();
CameraMatrix cam_projection = CameraMatrix();
- bool cam_ortogonal = false;
+ bool cam_orthogonal = false;
// For stereo rendering
uint32_t view_count = 1;
@@ -93,6 +94,7 @@ class RendererSceneRenderRD : public RendererSceneRender {
protected:
RendererStorageRD *storage = nullptr;
+ RendererRD::ToneMapper *tone_mapper = nullptr;
double time;
double time_step = 0;
@@ -113,7 +115,7 @@ protected:
virtual void _render_shadow_process() = 0;
virtual void _render_shadow_end(uint32_t p_barrier = RD::BARRIER_MASK_ALL) = 0;
- virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) = 0;
+ virtual void _render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) = 0;
virtual void _render_uv2(const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) = 0;
virtual void _render_sdfgi(RID p_render_buffers, const Vector3i &p_from, const Vector3i &p_size, const AABB &p_bounds, const PagedArray<GeometryInstance *> &p_instances, const RID &p_albedo_texture, const RID &p_emission_texture, const RID &p_emission_aniso_texture, const RID &p_geom_facing_texture) = 0;
virtual void _render_particle_collider_heightfield(RID p_fb, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, const PagedArray<GeometryInstance *> &p_instances) = 0;
@@ -1411,7 +1413,7 @@ public:
virtual void render_scene(RID p_render_buffers, const CameraData *p_camera_data, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data = nullptr, RendererScene::RenderInfo *r_render_info = nullptr) override;
- virtual void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
+ virtual void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) override;
virtual void render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) override;
diff --git a/servers/rendering/renderer_rd/shaders/SCsub b/servers/rendering/renderer_rd/shaders/SCsub
index fc513d3fb9..acb843bfb6 100644
--- a/servers/rendering/renderer_rd/shaders/SCsub
+++ b/servers/rendering/renderer_rd/shaders/SCsub
@@ -15,3 +15,5 @@ if "RD_GLSL" in env["BUILDERS"]:
# compile shaders
for glsl_file in glsl_files:
env.RD_GLSL(glsl_file)
+
+SConscript("effects/SCsub")
diff --git a/servers/rendering/renderer_rd/shaders/effects/SCsub b/servers/rendering/renderer_rd/shaders/effects/SCsub
new file mode 100644
index 0000000000..fc513d3fb9
--- /dev/null
+++ b/servers/rendering/renderer_rd/shaders/effects/SCsub
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+
+Import("env")
+
+if "RD_GLSL" in env["BUILDERS"]:
+ # find all include files
+ gl_include_files = [str(f) for f in Glob("*_inc.glsl")]
+
+ # find all shader code(all glsl files excluding our include files)
+ glsl_files = [str(f) for f in Glob("*.glsl") if str(f) not in gl_include_files]
+
+ # make sure we recompile shaders if include files change
+ env.Depends([f + ".gen.h" for f in glsl_files], gl_include_files)
+
+ # compile shaders
+ for glsl_file in glsl_files:
+ env.RD_GLSL(glsl_file)
diff --git a/servers/rendering/renderer_rd/shaders/tonemap.glsl b/servers/rendering/renderer_rd/shaders/effects/tonemap.glsl
index 19a9350137..19a9350137 100644
--- a/servers/rendering/renderer_rd/shaders/tonemap.glsl
+++ b/servers/rendering/renderer_rd/shaders/effects/tonemap.glsl
diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
index 75c502c666..d939a0d641 100644
--- a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
@@ -339,7 +339,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_FLOAT: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedFloat32Array &a = value;
@@ -361,7 +361,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_VEC2: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedVector2Array &a = value;
@@ -385,7 +385,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_VEC3: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedVector3Array &a = value;
@@ -411,7 +411,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_VEC4: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
if (value.get_type() == Variant::PACKED_COLOR_ARRAY) {
@@ -491,7 +491,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_MAT2: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedFloat32Array &a = value;
@@ -532,7 +532,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_MAT3: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedFloat32Array &a = value;
@@ -587,7 +587,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
}
} break;
case ShaderLanguage::TYPE_MAT4: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
if (p_array_size > 0) {
const PackedFloat32Array &a = value;
@@ -748,12 +748,12 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
}
} break;
case ShaderLanguage::TYPE_FLOAT: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
gui[0] = value[0].real;
} break;
case ShaderLanguage::TYPE_VEC2: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
for (int i = 0; i < 2; i++) {
gui[i] = value[i].real;
@@ -761,7 +761,7 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
} break;
case ShaderLanguage::TYPE_VEC3: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
for (int i = 0; i < 3; i++) {
gui[i] = value[i].real;
@@ -769,14 +769,14 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
} break;
case ShaderLanguage::TYPE_VEC4: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
for (int i = 0; i < 4; i++) {
gui[i] = value[i].real;
}
} break;
case ShaderLanguage::TYPE_MAT2: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
//in std140 members of mat2 are treated as vec4s
gui[0] = value[0].real;
@@ -789,7 +789,7 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
gui[7] = 0;
} break;
case ShaderLanguage::TYPE_MAT3: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
gui[0] = value[0].real;
gui[1] = value[1].real;
@@ -805,7 +805,7 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
gui[11] = 0;
} break;
case ShaderLanguage::TYPE_MAT4: {
- float *gui = (float *)data;
+ float *gui = reinterpret_cast<float *>(data);
for (int i = 0; i < 16; i++) {
gui[i] = value[i].real;
@@ -1885,7 +1885,7 @@ void MaterialStorage::global_variable_remove(const StringName &p_name) {
if (!global_variables.variables.has(p_name)) {
return;
}
- GlobalVariables::Variable &gv = global_variables.variables[p_name];
+ const GlobalVariables::Variable &gv = global_variables.variables[p_name];
if (gv.buffer_index >= 0) {
global_variables.buffer_usage[gv.buffer_index].elements = 0;
@@ -2110,7 +2110,7 @@ void MaterialStorage::global_variables_instance_update(RID p_instance, int p_ind
ERR_FAIL_INDEX(p_index, ShaderLanguage::MAX_INSTANCE_UNIFORM_INDICES);
ERR_FAIL_COND_MSG(p_value.get_type() > Variant::COLOR, "Unsupported variant type for instance parameter: " + Variant::get_type_name(p_value.get_type())); //anything greater not supported
- ShaderLanguage::DataType datatype_from_value[Variant::COLOR + 1] = {
+ const ShaderLanguage::DataType datatype_from_value[Variant::COLOR + 1] = {
ShaderLanguage::TYPE_MAX, //nil
ShaderLanguage::TYPE_BOOL, //bool
ShaderLanguage::TYPE_INT, //int
diff --git a/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
index 8c60264ce3..0f74c591c6 100644
--- a/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp
@@ -50,7 +50,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 3);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 0.0;
fptr[1] = 0.0;
fptr[2] = 0.0;
@@ -62,7 +62,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 3);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 1.0;
fptr[1] = 0.0;
fptr[2] = 0.0;
@@ -74,7 +74,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 4);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 1.0;
fptr[1] = 0.0;
fptr[2] = 0.0;
@@ -87,7 +87,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 4);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 1.0;
fptr[1] = 1.0;
fptr[2] = 1.0;
@@ -100,7 +100,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 2);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 0.0;
fptr[1] = 0.0;
}
@@ -110,7 +110,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 2);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 0.0;
fptr[1] = 0.0;
}
@@ -121,7 +121,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 4);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 0.0;
fptr[1] = 0.0;
fptr[2] = 0.0;
@@ -134,7 +134,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(uint32_t) * 4);
{
uint8_t *w = buffer.ptrw();
- uint32_t *fptr = (uint32_t *)w;
+ uint32_t *fptr = reinterpret_cast<uint32_t *>(w);
fptr[0] = 0;
fptr[1] = 0;
fptr[2] = 0;
@@ -147,7 +147,7 @@ MeshStorage::MeshStorage() {
buffer.resize(sizeof(float) * 4);
{
uint8_t *w = buffer.ptrw();
- float *fptr = (float *)w;
+ float *fptr = reinterpret_cast<float *>(w);
fptr[0] = 0.0;
fptr[1] = 0.0;
fptr[2] = 0.0;
@@ -284,9 +284,9 @@ void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface)
case RS::ARRAY_CUSTOM2:
case RS::ARRAY_CUSTOM3: {
int idx = i - RS::ARRAY_CUSTOM0;
- uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
+ const uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
uint32_t fmt = (p_surface.format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK;
- uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
+ const uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
attrib_stride += fmtsize[fmt];
} break;
@@ -1098,10 +1098,10 @@ void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::V
vd.offset = attribute_stride;
int idx = i - RS::ARRAY_CUSTOM0;
- uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
+ const uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT };
uint32_t fmt = (s->format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK;
- uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
- RD::DataFormat fmtrd[RS::ARRAY_CUSTOM_MAX] = { RD::DATA_FORMAT_R8G8B8A8_UNORM, RD::DATA_FORMAT_R8G8B8A8_SNORM, RD::DATA_FORMAT_R16G16_SFLOAT, RD::DATA_FORMAT_R16G16B16A16_SFLOAT, RD::DATA_FORMAT_R32_SFLOAT, RD::DATA_FORMAT_R32G32_SFLOAT, RD::DATA_FORMAT_R32G32B32_SFLOAT, RD::DATA_FORMAT_R32G32B32A32_SFLOAT };
+ const uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 };
+ const RD::DataFormat fmtrd[RS::ARRAY_CUSTOM_MAX] = { RD::DATA_FORMAT_R8G8B8A8_UNORM, RD::DATA_FORMAT_R8G8B8A8_SNORM, RD::DATA_FORMAT_R16G16_SFLOAT, RD::DATA_FORMAT_R16G16B16A16_SFLOAT, RD::DATA_FORMAT_R32_SFLOAT, RD::DATA_FORMAT_R32G32_SFLOAT, RD::DATA_FORMAT_R32G32B32_SFLOAT, RD::DATA_FORMAT_R32G32B32A32_SFLOAT };
vd.format = fmtrd[fmt];
attribute_stride += fmtsize[fmt];
buffer = s->attribute_buffer;
@@ -1238,7 +1238,7 @@ void MeshStorage::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
if (multimesh->buffer_set) {
Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer);
const uint8_t *r = buffer.ptr();
- const float *data = (const float *)r;
+ const float *data = reinterpret_cast<const float *>(r);
_multimesh_re_create_aabb(multimesh, data, multimesh->instances);
}
}
diff --git a/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp b/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
index 75dd20bdbd..402536de88 100644
--- a/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
@@ -1722,7 +1722,7 @@ RID ParticlesStorage::particles_collision_get_heightfield_framebuffer(RID p_part
if (particles_collision->heightfield_texture == RID()) {
//create
- int resolutions[RS::PARTICLES_COLLISION_HEIGHTFIELD_RESOLUTION_MAX] = { 256, 512, 1024, 2048, 4096, 8192 };
+ const int resolutions[RS::PARTICLES_COLLISION_HEIGHTFIELD_RESOLUTION_MAX] = { 256, 512, 1024, 2048, 4096, 8192 };
Size2i size;
if (particles_collision->extents.x > particles_collision->extents.z) {
size.x = resolutions[particles_collision->heightfield_resolution];
diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp
index 55193a45f0..528f381139 100644
--- a/servers/rendering/renderer_scene_cull.cpp
+++ b/servers/rendering/renderer_scene_cull.cpp
@@ -2444,7 +2444,7 @@ void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_
Transform3D transform = camera->transform;
CameraMatrix projection;
bool vaspect = camera->vaspect;
- bool is_ortogonal = false;
+ bool is_orthogonal = false;
switch (camera->type) {
case Camera::ORTHOGONAL: {
@@ -2454,7 +2454,7 @@ void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_
camera->znear,
camera->zfar,
camera->vaspect);
- is_ortogonal = true;
+ is_orthogonal = true;
} break;
case Camera::PERSPECTIVE: {
projection.set_perspective(
@@ -2476,7 +2476,7 @@ void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_
} break;
}
- camera_data.set_camera(transform, projection, is_ortogonal, vaspect);
+ camera_data.set_camera(transform, projection, is_orthogonal, vaspect);
} else {
// Setup our camera for our XR interface.
// We can support multiple views here each with their own camera
@@ -2510,7 +2510,7 @@ void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_
RENDER_TIMESTAMP("Update Occlusion Buffer")
// For now just cull on the first camera
- RendererSceneOcclusionCull::get_singleton()->buffer_update(p_viewport, camera_data.main_transform, camera_data.main_projection, camera_data.is_ortogonal, RendererThreadPool::singleton->thread_work_pool);
+ RendererSceneOcclusionCull::get_singleton()->buffer_update(p_viewport, camera_data.main_transform, camera_data.main_projection, camera_data.is_orthogonal, RendererThreadPool::singleton->thread_work_pool);
_render_scene(&camera_data, p_render_buffers, environment, camera->effects, camera->visible_layers, p_scenario, p_viewport, p_shadow_atlas, RID(), -1, p_screen_mesh_lod_threshold, true, r_render_info);
#endif
@@ -2920,7 +2920,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
RENDER_TIMESTAMP("Cull 3D Scene");
- //rasterizer->set_camera(p_camera_data->main_transform, p_camera_data.main_projection, p_camera_data.is_ortogonal);
+ //rasterizer->set_camera(p_camera_data->main_transform, p_camera_data.main_projection, p_camera_data.is_orthogonal);
/* STEP 2 - CULL */
@@ -2959,7 +2959,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
scene_render->set_directional_shadow_count(lights_with_shadow.size());
for (int i = 0; i < lights_with_shadow.size(); i++) {
- _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_ortogonal, p_camera_data->vaspect);
+ _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect);
}
}
@@ -3097,7 +3097,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
ins->transform.origin + cam_xf.basis.get_axis(0) * radius
};
- if (!p_camera_data->is_ortogonal) {
+ if (!p_camera_data->is_orthogonal) {
//if using perspetive, map them to near plane
for (int j = 0; j < 2; j++) {
if (p.distance_to(points[j]) < 0) {
@@ -3125,7 +3125,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
base + cam_xf.basis.get_axis(0) * w
};
- if (!p_camera_data->is_ortogonal) {
+ if (!p_camera_data->is_orthogonal) {
//if using perspetive, map them to near plane
for (int j = 0; j < 2; j++) {
if (p.distance_to(points[j]) < 0) {
@@ -3156,7 +3156,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
if (redraw && max_shadows_used < MAX_UPDATE_SHADOWS) {
//must redraw!
RENDER_TIMESTAMP("> Render Light3D " + itos(i));
- light->shadow_dirty = _light_instance_update_shadow(ins, p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_ortogonal, p_camera_data->vaspect, p_shadow_atlas, scenario, p_screen_mesh_lod_threshold);
+ light->shadow_dirty = _light_instance_update_shadow(ins, p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect, p_shadow_atlas, scenario, p_screen_mesh_lod_threshold);
RENDER_TIMESTAMP("< Render Light3D " + itos(i));
} else {
light->shadow_dirty = redraw;
@@ -3229,7 +3229,7 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c
render_sdfgi_data[i].instances.clear();
}
- // virtual void render_scene(RID p_render_buffers, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold,const RenderShadowData *p_render_shadows,int p_render_shadow_count,const RenderSDFGIData *p_render_sdfgi_regions,int p_render_sdfgi_region_count,const RenderSDFGIStaticLightData *p_render_sdfgi_static_lights=nullptr) = 0;
+ // virtual void render_scene(RID p_render_buffers, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold,const RenderShadowData *p_render_shadows,int p_render_shadow_count,const RenderSDFGIData *p_render_sdfgi_regions,int p_render_sdfgi_region_count,const RenderSDFGIStaticLightData *p_render_sdfgi_static_lights=nullptr) = 0;
}
RID RendererSceneCull::_render_get_environment(RID p_camera, RID p_scenario) {
diff --git a/servers/rendering/renderer_scene_render.cpp b/servers/rendering/renderer_scene_render.cpp
index c802f72fdf..fadece317a 100644
--- a/servers/rendering/renderer_scene_render.cpp
+++ b/servers/rendering/renderer_scene_render.cpp
@@ -30,9 +30,9 @@
#include "renderer_scene_render.h"
-void RendererSceneRender::CameraData::set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_ortogonal, bool p_vaspect) {
+void RendererSceneRender::CameraData::set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_orthogonal, bool p_vaspect) {
view_count = 1;
- is_ortogonal = p_is_ortogonal;
+ is_orthogonal = p_is_orthogonal;
vaspect = p_vaspect;
main_transform = p_transform;
@@ -42,11 +42,11 @@ void RendererSceneRender::CameraData::set_camera(const Transform3D p_transform,
view_projection[0] = p_projection;
}
-void RendererSceneRender::CameraData::set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_ortogonal, bool p_vaspect) {
+void RendererSceneRender::CameraData::set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_orthogonal, bool p_vaspect) {
ERR_FAIL_COND_MSG(p_view_count != 2, "Incorrect view count for stereoscopic view");
view_count = p_view_count;
- is_ortogonal = p_is_ortogonal;
+ is_orthogonal = p_is_orthogonal;
vaspect = p_vaspect;
Vector<Plane> planes[2];
diff --git a/servers/rendering/renderer_scene_render.h b/servers/rendering/renderer_scene_render.h
index 0b8734e68c..d43bfb170e 100644
--- a/servers/rendering/renderer_scene_render.h
+++ b/servers/rendering/renderer_scene_render.h
@@ -234,7 +234,7 @@ public:
struct CameraData {
// flags
uint32_t view_count;
- bool is_ortogonal;
+ bool is_orthogonal;
bool vaspect;
// Main/center projection
@@ -244,13 +244,13 @@ public:
Transform3D view_offset[RendererSceneRender::MAX_RENDER_VIEWS];
CameraMatrix view_projection[RendererSceneRender::MAX_RENDER_VIEWS];
- void set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_ortogonal, bool p_vaspect);
- void set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_ortogonal, bool p_vaspect);
+ void set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_orthogonal, bool p_vaspect);
+ void set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_orthogonal, bool p_vaspect);
};
virtual void render_scene(RID p_render_buffers, const CameraData *p_camera_data, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data = nullptr, RendererScene::RenderInfo *r_render_info = nullptr) = 0;
- virtual void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) = 0;
+ virtual void render_material(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, const PagedArray<GeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) = 0;
virtual void render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<GeometryInstance *> &p_instances) = 0;
virtual void set_scene_pass(uint64_t p_pass) = 0;
diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp
index af5da6ae6f..54d1a6fd8d 100644
--- a/servers/rendering/shader_language.cpp
+++ b/servers/rendering/shader_language.cpp
@@ -4670,16 +4670,18 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons
expr = _parse_array_constructor(p_block, p_function_info);
} else {
DataType datatype;
- DataPrecision precision;
- bool precision_defined = false;
+ DataPrecision precision = PRECISION_DEFAULT;
if (is_token_precision(tk.type)) {
precision = get_token_precision(tk.type);
- precision_defined = true;
tk = _get_token();
}
datatype = get_token_datatype(tk.type);
+ if (precision != PRECISION_DEFAULT && _validate_precision(datatype, precision) != OK) {
+ return nullptr;
+ }
+
tk = _get_token();
if (tk.type == TK_BRACKET_OPEN) {
@@ -4697,7 +4699,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons
OperatorNode *func = alloc_node<OperatorNode>();
func->op = OP_CONSTRUCT;
- if (precision_defined) {
+ if (precision != PRECISION_DEFAULT) {
func->return_precision_cache = precision;
}
@@ -6426,10 +6428,6 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun
if (!is_struct) {
is_struct = shader->structs.has(tk.text); // check again.
}
- if (is_struct && precision != PRECISION_DEFAULT) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
if (!is_token_nonvoid_datatype(tk.type)) {
_set_error(RTR("Expected variable type after precision modifier."));
return ERR_PARSE_ERROR;
@@ -6449,6 +6447,10 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun
return ERR_PARSE_ERROR;
}
+ if (precision != PRECISION_DEFAULT && _validate_precision(type, precision) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
int array_size = 0;
bool fixed_array_size = false;
bool first = true;
@@ -6600,10 +6602,6 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun
if (is_token_precision(tk.type)) {
precision2 = get_token_precision(tk.type);
tk = _get_token();
- if (shader->structs.has(tk.text)) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
if (!is_token_nonvoid_datatype(tk.type)) {
_set_error(RTR("Expected data type after precision modifier."));
return ERR_PARSE_ERROR;
@@ -6624,6 +6622,10 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun
type2 = get_token_datatype(tk.type);
}
+ if (precision2 != PRECISION_DEFAULT && _validate_precision(type2, precision2) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
int array_size2 = 0;
tk = _get_token();
@@ -7427,6 +7429,25 @@ String ShaderLanguage::_get_qualifier_str(ArgumentQualifier p_qualifier) const {
return "";
}
+Error ShaderLanguage::_validate_precision(DataType p_type, DataPrecision p_precision) {
+ switch (p_type) {
+ case TYPE_STRUCT: {
+ _set_error(RTR("The precision modifier cannot be used on structs."));
+ return FAILED;
+ } break;
+ case TYPE_BOOL:
+ case TYPE_BVEC2:
+ case TYPE_BVEC3:
+ case TYPE_BVEC4: {
+ _set_error(RTR("The precision modifier cannot be used on boolean types."));
+ return FAILED;
+ } break;
+ default:
+ break;
+ }
+ return OK;
+}
+
Error ShaderLanguage::_validate_datatype(DataType p_type) {
if (RenderingServer::get_singleton()->is_low_end()) {
bool invalid_type = false;
@@ -7608,8 +7629,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
}
StringName struct_name = "";
bool struct_dt = false;
- bool use_precision = false;
- DataPrecision precision = DataPrecision::PRECISION_DEFAULT;
+ DataPrecision precision = PRECISION_DEFAULT;
if (tk.type == TK_STRUCT) {
_set_error(RTR("Nested structs are not allowed."));
@@ -7618,7 +7638,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
if (is_token_precision(tk.type)) {
precision = get_token_precision(tk.type);
- use_precision = true;
tk = _get_token();
}
@@ -7630,10 +7649,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
}
#endif // DEBUG_ENABLED
struct_dt = true;
- if (use_precision) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
}
if (!is_token_datatype(tk.type) && !struct_dt) {
@@ -7642,6 +7657,10 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
} else {
type = struct_dt ? TYPE_STRUCT : get_token_datatype(tk.type);
+ if (precision != PRECISION_DEFAULT && _validate_precision(type, precision) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
if (type == TYPE_VOID || is_sampler_type(type)) {
_set_error(vformat(RTR("A '%s' data type is not allowed here."), get_datatype_name(type)));
return ERR_PARSE_ERROR;
@@ -7762,7 +7781,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
}
}
- bool precision_defined = false;
DataPrecision precision = PRECISION_DEFAULT;
DataInterpolation interpolation = INTERPOLATION_SMOOTH;
DataType type;
@@ -7781,16 +7799,11 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
if (is_token_precision(tk.type)) {
precision = get_token_precision(tk.type);
- precision_defined = true;
tk = _get_token();
}
if (shader->structs.has(tk.text)) {
if (uniform) {
- if (precision_defined) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
_set_error(vformat(RTR("The '%s' data type is not supported for uniforms."), "struct"));
return ERR_PARSE_ERROR;
} else {
@@ -7806,6 +7819,10 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
type = get_token_datatype(tk.type);
+ if (precision != PRECISION_DEFAULT && _validate_precision(type, precision) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
if (type == TYPE_VOID) {
_set_error(vformat(RTR("The '%s' data type is not allowed here."), "void"));
return ERR_PARSE_ERROR;
@@ -8249,10 +8266,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
}
if (shader->structs.has(tk.text)) {
- if (precision != PRECISION_DEFAULT) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
is_struct = true;
struct_name = tk.text;
} else {
@@ -8276,6 +8289,11 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
} else {
type = get_token_datatype(tk.type);
}
+
+ if (precision != PRECISION_DEFAULT && _validate_precision(type, precision) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
prev_pos = _get_tkpos();
tk = _get_token();
@@ -8652,44 +8670,41 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
break;
}
- bool is_const = false;
+ bool param_is_const = false;
if (tk.type == TK_CONST) {
- is_const = true;
+ param_is_const = true;
tk = _get_token();
}
- ArgumentQualifier qualifier = ARGUMENT_QUALIFIER_IN;
-
+ ArgumentQualifier param_qualifier = ARGUMENT_QUALIFIER_IN;
if (tk.type == TK_ARG_IN) {
- qualifier = ARGUMENT_QUALIFIER_IN;
+ param_qualifier = ARGUMENT_QUALIFIER_IN;
tk = _get_token();
} else if (tk.type == TK_ARG_OUT) {
- if (is_const) {
+ if (param_is_const) {
_set_error(vformat(RTR("The '%s' qualifier cannot be used within a function parameter declared with '%s'."), "out", "const"));
return ERR_PARSE_ERROR;
}
- qualifier = ARGUMENT_QUALIFIER_OUT;
+ param_qualifier = ARGUMENT_QUALIFIER_OUT;
tk = _get_token();
} else if (tk.type == TK_ARG_INOUT) {
- if (is_const) {
+ if (param_is_const) {
_set_error(vformat(RTR("The '%s' qualifier cannot be used within a function parameter declared with '%s'."), "inout", "const"));
return ERR_PARSE_ERROR;
}
- qualifier = ARGUMENT_QUALIFIER_INOUT;
+ param_qualifier = ARGUMENT_QUALIFIER_INOUT;
tk = _get_token();
}
- DataType ptype;
- StringName pname;
+ DataType param_type;
+ StringName param_name;
StringName param_struct_name;
- DataPrecision pprecision = PRECISION_DEFAULT;
- bool use_precision = false;
+ DataPrecision param_precision = PRECISION_DEFAULT;
int arg_array_size = 0;
if (is_token_precision(tk.type)) {
- pprecision = get_token_precision(tk.type);
+ param_precision = get_token_precision(tk.type);
tk = _get_token();
- use_precision = true;
}
is_struct = false;
@@ -8702,10 +8717,6 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
used_structs[param_struct_name].used = true;
}
#endif // DEBUG_ENABLED
- if (use_precision) {
- _set_error(RTR("The precision modifier cannot be used on structs."));
- return ERR_PARSE_ERROR;
- }
}
if (!is_struct && !is_token_datatype(tk.type)) {
@@ -8713,7 +8724,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
return ERR_PARSE_ERROR;
}
- if (qualifier == ARGUMENT_QUALIFIER_OUT || qualifier == ARGUMENT_QUALIFIER_INOUT) {
+ if (param_qualifier == ARGUMENT_QUALIFIER_OUT || param_qualifier == ARGUMENT_QUALIFIER_INOUT) {
if (is_sampler_type(get_token_datatype(tk.type))) {
_set_error(RTR("Opaque types cannot be output parameters."));
return ERR_PARSE_ERROR;
@@ -8721,18 +8732,22 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
}
if (is_struct) {
- ptype = TYPE_STRUCT;
+ param_type = TYPE_STRUCT;
} else {
- ptype = get_token_datatype(tk.type);
- if (_validate_datatype(ptype) != OK) {
+ param_type = get_token_datatype(tk.type);
+ if (_validate_datatype(param_type) != OK) {
return ERR_PARSE_ERROR;
}
- if (ptype == TYPE_VOID) {
+ if (param_type == TYPE_VOID) {
_set_error(RTR("Void type not allowed as argument."));
return ERR_PARSE_ERROR;
}
}
+ if (param_precision != PRECISION_DEFAULT && _validate_precision(param_type, param_precision) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+
tk = _get_token();
if (tk.type == TK_BRACKET_OPEN) {
@@ -8747,32 +8762,32 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct
return ERR_PARSE_ERROR;
}
- pname = tk.text;
+ param_name = tk.text;
ShaderLanguage::IdentifierType itype;
- if (_find_identifier(func_node->body, false, builtins, pname, (ShaderLanguage::DataType *)nullptr, &itype)) {
+ if (_find_identifier(func_node->body, false, builtins, param_name, (ShaderLanguage::DataType *)nullptr, &itype)) {
if (itype != IDENTIFIER_FUNCTION) {
- _set_redefinition_error(String(pname));
+ _set_redefinition_error(String(param_name));
return ERR_PARSE_ERROR;
}
}
- if (has_builtin(p_functions, pname)) {
- _set_redefinition_error(String(pname));
+ if (has_builtin(p_functions, param_name)) {
+ _set_redefinition_error(String(param_name));
return ERR_PARSE_ERROR;
}
FunctionNode::Argument arg;
- arg.type = ptype;
- arg.name = pname;
+ arg.type = param_type;
+ arg.name = param_name;
arg.type_str = param_struct_name;
- arg.precision = pprecision;
- arg.qualifier = qualifier;
+ arg.precision = param_precision;
+ arg.qualifier = param_qualifier;
arg.tex_argument_check = false;
arg.tex_builtin_check = false;
arg.tex_argument_filter = FILTER_DEFAULT;
arg.tex_argument_repeat = REPEAT_DEFAULT;
- arg.is_const = is_const;
+ arg.is_const = param_is_const;
tk = _get_token();
if (tk.type == TK_BRACKET_OPEN) {
diff --git a/servers/rendering/shader_language.h b/servers/rendering/shader_language.h
index 66ae220edf..de6d912a4f 100644
--- a/servers/rendering/shader_language.h
+++ b/servers/rendering/shader_language.h
@@ -1038,6 +1038,7 @@ private:
static bool is_const_suffix_lut_initialized;
+ Error _validate_precision(DataType p_type, DataPrecision p_precision);
Error _validate_datatype(DataType p_type);
bool _compare_datatypes(DataType p_datatype_a, String p_datatype_name_a, int p_array_size_a, DataType p_datatype_b, String p_datatype_name_b, int p_array_size_b);
bool _compare_datatypes_in_nodes(Node *a, Node *b);
diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp
index b58e6138eb..c2a6b83485 100644
--- a/servers/rendering_server.cpp
+++ b/servers/rendering_server.cpp
@@ -424,7 +424,7 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
value |= CLAMP(int((src[i * 4 + 1] * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
value |= CLAMP(int((src[i * 4 + 2] * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
if (src[i * 4 + 3] > 0) {
- value |= 3 << 30;
+ value |= 3UL << 30;
}
memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], &value, 4);
@@ -440,7 +440,7 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
value |= CLAMP(int((src[i * 4 + 1] * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
value |= CLAMP(int((src[i * 4 + 2] * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
if (src[i * 4 + 3] > 0) {
- value |= 3 << 30;
+ value |= 3UL << 30;
}
memcpy(&vw[p_offsets[ai] + i * p_vertex_stride], &value, 4);
}
@@ -1093,7 +1093,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
Vector2 *w = arr_2d.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float *)&r[j * vertex_elem_size + offsets[i]];
+ const float *v = reinterpret_cast<const float *>(&r[j * vertex_elem_size + offsets[i]]);
w[j] = Vector2(v[0], v[1]);
}
}
@@ -1107,7 +1107,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
Vector3 *w = arr_3d.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float *)&r[j * vertex_elem_size + offsets[i]];
+ const float *v = reinterpret_cast<const float *>(&r[j * vertex_elem_size + offsets[i]]);
w[j] = Vector3(v[0], v[1], v[2]);
}
}
@@ -1156,7 +1156,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
Color *w = arr.ptrw();
for (int32_t j = 0; j < p_vertex_len; j++) {
- const uint8_t *v = (const uint8_t *)&ar[j * attrib_elem_size + offsets[i]];
+ const uint8_t *v = reinterpret_cast<const uint8_t *>(&ar[j * attrib_elem_size + offsets[i]]);
w[j] = Color(v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, v[3] / 255.0);
}
@@ -1170,7 +1170,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
Vector2 *w = arr.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float *)&ar[j * attrib_elem_size + offsets[i]];
+ const float *v = reinterpret_cast<const float *>(&ar[j * attrib_elem_size + offsets[i]]);
w[j] = Vector2(v[0], v[1]);
}
@@ -1184,7 +1184,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
Vector2 *w = arr.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float *)&ar[j * attrib_elem_size + offsets[i]];
+ const float *v = reinterpret_cast<const float *>(&ar[j * attrib_elem_size + offsets[i]]);
w[j] = Vector2(v[0], v[1]);
}
@@ -1209,7 +1209,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
uint8_t *w = arr.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const uint8_t *v = (const uint8_t *)&ar[j * attrib_elem_size + offsets[i]];
+ const uint8_t *v = reinterpret_cast<const uint8_t *>(&ar[j * attrib_elem_size + offsets[i]]);
memcpy(&w[j * s], v, s);
}
@@ -1228,7 +1228,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
float *w = arr.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float *)&ar[j * attrib_elem_size + offsets[i]];
+ const float *v = reinterpret_cast<const float *>(&ar[j * attrib_elem_size + offsets[i]]);
memcpy(&w[j * s], v, s * sizeof(float));
}
ret[i] = arr;
diff --git a/servers/text/text_server_extension.cpp b/servers/text/text_server_extension.cpp
index 001706bb6f..005cb68302 100644
--- a/servers/text/text_server_extension.cpp
+++ b/servers/text/text_server_extension.cpp
@@ -293,6 +293,8 @@ void TextServerExtension::_bind_methods() {
GDVIRTUAL_BIND(strip_diacritics, "string");
+ GDVIRTUAL_BIND(string_get_word_breaks, "string", "language");
+
GDVIRTUAL_BIND(string_to_upper, "string", "language");
GDVIRTUAL_BIND(string_to_lower, "string", "language");
@@ -1503,6 +1505,14 @@ Array TextServerExtension::parse_structured_text(StructuredTextParser p_parser_t
return Array();
}
+PackedInt32Array TextServerExtension::string_get_word_breaks(const String &p_string, const String &p_language) const {
+ PackedInt32Array ret;
+ if (GDVIRTUAL_CALL(string_get_word_breaks, p_string, p_language, ret)) {
+ return ret;
+ }
+ return PackedInt32Array();
+}
+
TextServerExtension::TextServerExtension() {
//NOP
}
diff --git a/servers/text/text_server_extension.h b/servers/text/text_server_extension.h
index ce781097f3..7b7fc61ed7 100644
--- a/servers/text/text_server_extension.h
+++ b/servers/text/text_server_extension.h
@@ -485,6 +485,9 @@ public:
virtual String strip_diacritics(const String &p_string) const override;
GDVIRTUAL1RC(String, strip_diacritics, const String &);
+ virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const override;
+ GDVIRTUAL2RC(PackedInt32Array, string_get_word_breaks, const String &, const String &);
+
virtual String string_to_upper(const String &p_string, const String &p_language = "") const override;
virtual String string_to_lower(const String &p_string, const String &p_language = "") const override;
GDVIRTUAL2RC(String, string_to_upper, const String &, const String &);
diff --git a/servers/text_server.cpp b/servers/text_server.cpp
index d66e769e3c..7d9945f5d7 100644
--- a/servers/text_server.cpp
+++ b/servers/text_server.cpp
@@ -439,6 +439,8 @@ void TextServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("parse_number", "number", "language"), &TextServer::parse_number, DEFVAL(""));
ClassDB::bind_method(D_METHOD("percent_sign", "language"), &TextServer::percent_sign, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("string_get_word_breaks", "string", "language"), &TextServer::string_get_word_breaks, DEFVAL(""));
+
ClassDB::bind_method(D_METHOD("strip_diacritics", "string"), &TextServer::strip_diacritics);
ClassDB::bind_method(D_METHOD("string_to_upper", "string", "language"), &TextServer::string_to_upper, DEFVAL(""));
diff --git a/servers/text_server.h b/servers/text_server.h
index 7e7f26b32d..b08aa26917 100644
--- a/servers/text_server.h
+++ b/servers/text_server.h
@@ -431,6 +431,9 @@ public:
virtual String parse_number(const String &p_string, const String &p_language = "") const = 0;
virtual String percent_sign(const String &p_language = "") const = 0;
+ // String functions.
+ virtual PackedInt32Array string_get_word_breaks(const String &p_string, const String &p_language = "") const = 0;
+
virtual String strip_diacritics(const String &p_string) const;
// Other string operations.
diff --git a/tests/scene/test_code_edit.h b/tests/scene/test_code_edit.h
index 574cacda95..62931cd4dd 100644
--- a/tests/scene/test_code_edit.h
+++ b/tests/scene/test_code_edit.h
@@ -2179,8 +2179,24 @@ TEST_CASE("[SceneTree][CodeEdit] indent") {
SEND_GUI_ACTION(code_edit, "ui_text_newline");
CHECK(code_edit->get_line(0) == "test: # string");
CHECK(code_edit->get_line(1) == "");
+ code_edit->remove_string_delimiter("#");
+
+ /* Non-whitespace prevents auto-indentation. */
+ code_edit->add_comment_delimiter("#", "");
+ code_edit->set_text("");
+ code_edit->insert_text_at_caret("test := 0 # comment");
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line(0) == "test := 0 # comment");
+ CHECK(code_edit->get_line(1) == "");
code_edit->remove_comment_delimiter("#");
+ /* Even when there's no comments. */
+ code_edit->set_text("");
+ code_edit->insert_text_at_caret("test := 0");
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line(0) == "test := 0");
+ CHECK(code_edit->get_line(1) == "");
+
/* If between brace pairs an extra line is added. */
code_edit->set_text("");
code_edit->insert_text_at_caret("test{}");
@@ -2256,8 +2272,24 @@ TEST_CASE("[SceneTree][CodeEdit] indent") {
SEND_GUI_ACTION(code_edit, "ui_text_newline");
CHECK(code_edit->get_line(0) == "test: # string");
CHECK(code_edit->get_line(1) == "");
+ code_edit->remove_string_delimiter("#");
+
+ /* Non-whitespace prevents auto-indentation. */
+ code_edit->add_comment_delimiter("#", "");
+ code_edit->set_text("");
+ code_edit->insert_text_at_caret("test := 0 # comment");
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line(0) == "test := 0 # comment");
+ CHECK(code_edit->get_line(1) == "");
code_edit->remove_comment_delimiter("#");
+ /* Even when there's no comments. */
+ code_edit->set_text("");
+ code_edit->insert_text_at_caret("test := 0");
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line(0) == "test := 0");
+ CHECK(code_edit->get_line(1) == "");
+
/* If between brace pairs an extra line is added. */
code_edit->set_text("");
code_edit->insert_text_at_caret("test{}");
diff --git a/tests/servers/test_text_server.h b/tests/servers/test_text_server.h
index d7de94516f..066c280fd5 100644
--- a/tests/servers/test_text_server.h
+++ b/tests/servers/test_text_server.h
@@ -514,6 +514,49 @@ TEST_SUITE("[[TextServer]") {
CHECK(ts->strip_diacritics(U"ṽṿ ẁẃẅẇẉ ẋẍ ẏ ẑẓẕ ẖ ẗẘẙẛ") == U"vv wwwww xx y zzz h twys");
}
}
+
+ SUBCASE("[TextServer] Word break") {
+ for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
+ Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(i);
+
+ if (!ts->has_feature(TextServer::FEATURE_SIMPLE_LAYOUT)) {
+ continue;
+ }
+
+ TEST_FAIL_COND(ts.is_null(), "Invalid TS interface.");
+ {
+ String text1 = U"linguistically similar and effectively form";
+ // 14^ 22^ 26^ 38^
+ PackedInt32Array breaks = ts->string_get_word_breaks(text1, "en");
+ CHECK(breaks.size() == 4);
+ if (breaks.size() == 4) {
+ CHECK(breaks[0] == 14);
+ CHECK(breaks[1] == 22);
+ CHECK(breaks[2] == 26);
+ CHECK(breaks[3] == 38);
+ }
+ }
+
+ if (ts->has_feature(TextServer::FEATURE_BREAK_ITERATORS)) {
+ String text2 = U"เป็นภาษาราชการและภาษาประจำชาติของประเทศไทย";
+ // เป็น ภาษา ราชการ และ ภาษา ประจำ ชาติ ของ ประเทศไทย
+ // 3^ 7^ 13^ 16^ 20^ 25^ 29^ 32^
+
+ PackedInt32Array breaks = ts->string_get_word_breaks(text2, "th");
+ CHECK(breaks.size() == 8);
+ if (breaks.size() == 8) {
+ CHECK(breaks[0] == 3);
+ CHECK(breaks[1] == 7);
+ CHECK(breaks[2] == 13);
+ CHECK(breaks[3] == 16);
+ CHECK(breaks[4] == 20);
+ CHECK(breaks[5] == 25);
+ CHECK(breaks[6] == 29);
+ CHECK(breaks[7] == 32);
+ }
+ }
+ }
+ }
}
}
}; // namespace TestTextServer
diff --git a/tests/test_macros.h b/tests/test_macros.h
index 6e7a84bfb2..9cb9624d52 100644
--- a/tests/test_macros.h
+++ b/tests/test_macros.h
@@ -63,22 +63,22 @@
// Stringify all `Variant` compatible types for doctest output by default.
// https://github.com/onqtam/doctest/blob/master/doc/markdown/stringification.md
-#define DOCTEST_STRINGIFY_VARIANT(m_type) \
- template <> \
- struct doctest::StringMaker<m_type> { \
- static doctest::String convert(const m_type &p_val) { \
- const Variant val = p_val; \
- return val.get_construct_string().utf8().get_data(); \
- } \
+#define DOCTEST_STRINGIFY_VARIANT(m_type) \
+ template <> \
+ struct doctest::StringMaker<m_type> { \
+ static doctest::String convert(const m_type &p_val) { \
+ const Variant val = p_val; \
+ return val.operator ::String().utf8().get_data(); \
+ } \
};
-#define DOCTEST_STRINGIFY_VARIANT_POINTER(m_type) \
- template <> \
- struct doctest::StringMaker<m_type> { \
- static doctest::String convert(const m_type *p_val) { \
- const Variant val = p_val; \
- return val.get_construct_string().utf8().get_data(); \
- } \
+#define DOCTEST_STRINGIFY_VARIANT_POINTER(m_type) \
+ template <> \
+ struct doctest::StringMaker<m_type> { \
+ static doctest::String convert(const m_type *p_val) { \
+ const Variant val = p_val; \
+ return val.operator ::String().utf8().get_data(); \
+ } \
};
DOCTEST_STRINGIFY_VARIANT(Variant);
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index dc28a98c97..a059949105 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -160,10 +160,10 @@ struct GodotTestCaseListener : public doctest::IReporter {
SignalWatcher *signal_watcher = nullptr;
- PhysicsServer3D *physics_3d_server = nullptr;
- PhysicsServer2D *physics_2d_server = nullptr;
- NavigationServer3D *navigation_3d_server = nullptr;
- NavigationServer2D *navigation_2d_server = nullptr;
+ PhysicsServer3D *physics_server_3d = nullptr;
+ PhysicsServer2D *physics_server_2d = nullptr;
+ NavigationServer3D *navigation_server_3d = nullptr;
+ NavigationServer2D *navigation_server_2d = nullptr;
void test_case_start(const doctest::TestCaseData &p_in) override {
SignalWatcher::get_singleton()->_clear_signals();
@@ -190,19 +190,19 @@ struct GodotTestCaseListener : public doctest::IReporter {
RenderingServerDefault::get_singleton()->init();
RenderingServerDefault::get_singleton()->set_render_loop_enabled(false);
- physics_3d_server = PhysicsServer3DManager::new_default_server();
- physics_3d_server->init();
+ physics_server_3d = PhysicsServer3DManager::new_default_server();
+ physics_server_3d->init();
- physics_2d_server = PhysicsServer2DManager::new_default_server();
- physics_2d_server->init();
+ physics_server_2d = PhysicsServer2DManager::new_default_server();
+ physics_server_2d->init();
- navigation_3d_server = NavigationServer3DManager::new_default_server();
- navigation_2d_server = memnew(NavigationServer2D);
+ navigation_server_3d = NavigationServer3DManager::new_default_server();
+ navigation_server_2d = memnew(NavigationServer2D);
memnew(InputMap);
InputMap::get_singleton()->load_default();
- make_default_theme(1.0, Ref<Font>(), TextServer::SUBPIXEL_POSITIONING_AUTO, TextServer::HINTING_LIGHT, true);
+ make_default_theme(1.0, Ref<Font>());
memnew(SceneTree);
SceneTree::get_singleton()->initialize();
@@ -225,26 +225,26 @@ struct GodotTestCaseListener : public doctest::IReporter {
clear_default_theme();
- if (navigation_3d_server) {
- memdelete(navigation_3d_server);
- navigation_3d_server = nullptr;
+ if (navigation_server_3d) {
+ memdelete(navigation_server_3d);
+ navigation_server_3d = nullptr;
}
- if (navigation_2d_server) {
- memdelete(navigation_2d_server);
- navigation_2d_server = nullptr;
+ if (navigation_server_2d) {
+ memdelete(navigation_server_2d);
+ navigation_server_2d = nullptr;
}
- if (physics_3d_server) {
- physics_3d_server->finish();
- memdelete(physics_3d_server);
- physics_3d_server = nullptr;
+ if (physics_server_3d) {
+ physics_server_3d->finish();
+ memdelete(physics_server_3d);
+ physics_server_3d = nullptr;
}
- if (physics_2d_server) {
- physics_2d_server->finish();
- memdelete(physics_2d_server);
- physics_2d_server = nullptr;
+ if (physics_server_2d) {
+ physics_server_2d->finish();
+ memdelete(physics_server_2d);
+ physics_server_2d = nullptr;
}
if (Input::get_singleton()) {
diff --git a/thirdparty/noise/FastNoiseLite.h b/thirdparty/noise/FastNoiseLite.h
index 3db344c149..8015bf636a 100644
--- a/thirdparty/noise/FastNoiseLite.h
+++ b/thirdparty/noise/FastNoiseLite.h
@@ -295,7 +295,7 @@ public:
/// Noise output bounded between -1...1
/// </returns>
template <typename FNfloat>
- float GetNoise(FNfloat x, FNfloat y)
+ float GetNoise(FNfloat x, FNfloat y) const
{
Arguments_must_be_floating_point_values<FNfloat>();
@@ -321,7 +321,7 @@ public:
/// Noise output bounded between -1...1
/// </returns>
template <typename FNfloat>
- float GetNoise(FNfloat x, FNfloat y, FNfloat z)
+ float GetNoise(FNfloat x, FNfloat y, FNfloat z) const
{
Arguments_must_be_floating_point_values<FNfloat>();
@@ -350,7 +350,7 @@ public:
/// noise = GetNoise(x, y)</code>
/// </example>
template <typename FNfloat>
- void DomainWarp(FNfloat& x, FNfloat& y)
+ void DomainWarp(FNfloat& x, FNfloat& y) const
{
Arguments_must_be_floating_point_values<FNfloat>();
@@ -377,7 +377,7 @@ public:
/// noise = GetNoise(x, y, z)</code>
/// </example>
template <typename FNfloat>
- void DomainWarp(FNfloat& x, FNfloat& y, FNfloat& z)
+ void DomainWarp(FNfloat& x, FNfloat& y, FNfloat& z) const
{
Arguments_must_be_floating_point_values<FNfloat>();
@@ -528,7 +528,7 @@ private:
}
- float GradCoord(int seed, int xPrimed, int yPrimed, float xd, float yd)
+ float GradCoord(int seed, int xPrimed, int yPrimed, float xd, float yd) const
{
int hash = Hash(seed, xPrimed, yPrimed);
hash ^= hash >> 15;
@@ -541,7 +541,7 @@ private:
}
- float GradCoord(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd)
+ float GradCoord(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd) const
{
int hash = Hash(seed, xPrimed, yPrimed, zPrimed);
hash ^= hash >> 15;
@@ -555,7 +555,7 @@ private:
}
- void GradCoordOut(int seed, int xPrimed, int yPrimed, float& xo, float& yo)
+ void GradCoordOut(int seed, int xPrimed, int yPrimed, float& xo, float& yo) const
{
int hash = Hash(seed, xPrimed, yPrimed) & (255 << 1);
@@ -564,7 +564,7 @@ private:
}
- void GradCoordOut(int seed, int xPrimed, int yPrimed, int zPrimed, float& xo, float& yo, float& zo)
+ void GradCoordOut(int seed, int xPrimed, int yPrimed, int zPrimed, float& xo, float& yo, float& zo) const
{
int hash = Hash(seed, xPrimed, yPrimed, zPrimed) & (255 << 2);
@@ -574,7 +574,7 @@ private:
}
- void GradCoordDual(int seed, int xPrimed, int yPrimed, float xd, float yd, float& xo, float& yo)
+ void GradCoordDual(int seed, int xPrimed, int yPrimed, float xd, float yd, float& xo, float& yo) const
{
int hash = Hash(seed, xPrimed, yPrimed);
int index1 = hash & (127 << 1);
@@ -592,7 +592,7 @@ private:
}
- void GradCoordDual(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd, float& xo, float& yo, float& zo)
+ void GradCoordDual(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd, float& xo, float& yo, float& zo) const
{
int hash = Hash(seed, xPrimed, yPrimed, zPrimed);
int index1 = hash & (63 << 2);
@@ -616,7 +616,7 @@ private:
// Generic noise gen
template <typename FNfloat>
- float GenNoiseSingle(int seed, FNfloat x, FNfloat y)
+ float GenNoiseSingle(int seed, FNfloat x, FNfloat y) const
{
switch (mNoiseType)
{
@@ -638,7 +638,7 @@ private:
}
template <typename FNfloat>
- float GenNoiseSingle(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float GenNoiseSingle(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
switch (mNoiseType)
{
@@ -663,7 +663,7 @@ private:
// Noise Coordinate Transforms (frequency, and possible skew or rotation)
template <typename FNfloat>
- void TransformNoiseCoordinate(FNfloat& x, FNfloat& y)
+ void TransformNoiseCoordinate(FNfloat& x, FNfloat& y) const
{
x *= mFrequency;
y *= mFrequency;
@@ -686,7 +686,7 @@ private:
}
template <typename FNfloat>
- void TransformNoiseCoordinate(FNfloat& x, FNfloat& y, FNfloat& z)
+ void TransformNoiseCoordinate(FNfloat& x, FNfloat& y, FNfloat& z) const
{
x *= mFrequency;
y *= mFrequency;
@@ -757,7 +757,7 @@ private:
// Domain Warp Coordinate Transforms
template <typename FNfloat>
- void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y)
+ void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y) const
{
switch (mDomainWarpType)
{
@@ -777,7 +777,7 @@ private:
}
template <typename FNfloat>
- void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y, FNfloat& z)
+ void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y, FNfloat& z) const
{
switch (mWarpTransformType3D)
{
@@ -844,7 +844,7 @@ private:
// Fractal FBm
template <typename FNfloat>
- float GenFractalFBm(FNfloat x, FNfloat y)
+ float GenFractalFBm(FNfloat x, FNfloat y) const
{
int seed = mSeed;
float sum = 0;
@@ -865,7 +865,7 @@ private:
}
template <typename FNfloat>
- float GenFractalFBm(FNfloat x, FNfloat y, FNfloat z)
+ float GenFractalFBm(FNfloat x, FNfloat y, FNfloat z) const
{
int seed = mSeed;
float sum = 0;
@@ -890,7 +890,7 @@ private:
// Fractal Ridged
template <typename FNfloat>
- float GenFractalRidged(FNfloat x, FNfloat y)
+ float GenFractalRidged(FNfloat x, FNfloat y) const
{
int seed = mSeed;
float sum = 0;
@@ -911,7 +911,7 @@ private:
}
template <typename FNfloat>
- float GenFractalRidged(FNfloat x, FNfloat y, FNfloat z)
+ float GenFractalRidged(FNfloat x, FNfloat y, FNfloat z) const
{
int seed = mSeed;
float sum = 0;
@@ -936,7 +936,7 @@ private:
// Fractal PingPong
template <typename FNfloat>
- float GenFractalPingPong(FNfloat x, FNfloat y)
+ float GenFractalPingPong(FNfloat x, FNfloat y) const
{
int seed = mSeed;
float sum = 0;
@@ -957,7 +957,7 @@ private:
}
template <typename FNfloat>
- float GenFractalPingPong(FNfloat x, FNfloat y, FNfloat z)
+ float GenFractalPingPong(FNfloat x, FNfloat y, FNfloat z) const
{
int seed = mSeed;
float sum = 0;
@@ -982,7 +982,7 @@ private:
// Simplex/OpenSimplex2 Noise
template <typename FNfloat>
- float SingleSimplex(int seed, FNfloat x, FNfloat y)
+ float SingleSimplex(int seed, FNfloat x, FNfloat y) const
{
// 2D OpenSimplex2 case uses the same algorithm as ordinary Simplex.
@@ -1053,7 +1053,7 @@ private:
}
template <typename FNfloat>
- float SingleOpenSimplex2(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SingleOpenSimplex2(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
// 3D OpenSimplex2 case uses two offset rotated cube grids.
@@ -1155,7 +1155,7 @@ private:
// OpenSimplex2S Noise
template <typename FNfloat>
- float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y)
+ float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y) const
{
// 2D OpenSimplex2S case is a modified 2D simplex noise.
@@ -1286,7 +1286,7 @@ private:
}
template <typename FNfloat>
- float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
// 3D OpenSimplex2S case uses two offset rotated cube grids.
@@ -1482,7 +1482,7 @@ private:
// Cellular Noise
template <typename FNfloat>
- float SingleCellular(int seed, FNfloat x, FNfloat y)
+ float SingleCellular(int seed, FNfloat x, FNfloat y) const
{
int xr = FastRound(x);
int yr = FastRound(y);
@@ -1612,7 +1612,7 @@ private:
}
template <typename FNfloat>
- float SingleCellular(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SingleCellular(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
int xr = FastRound(x);
int yr = FastRound(y);
@@ -1769,7 +1769,7 @@ private:
// Perlin Noise
template <typename FNfloat>
- float SinglePerlin(int seed, FNfloat x, FNfloat y)
+ float SinglePerlin(int seed, FNfloat x, FNfloat y) const
{
int x0 = FastFloor(x);
int y0 = FastFloor(y);
@@ -1794,7 +1794,7 @@ private:
}
template <typename FNfloat>
- float SinglePerlin(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SinglePerlin(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
int x0 = FastFloor(x);
int y0 = FastFloor(y);
@@ -1833,7 +1833,7 @@ private:
// Value Cubic Noise
template <typename FNfloat>
- float SingleValueCubic(int seed, FNfloat x, FNfloat y)
+ float SingleValueCubic(int seed, FNfloat x, FNfloat y) const
{
int x1 = FastFloor(x);
int y1 = FastFloor(y);
@@ -1863,7 +1863,7 @@ private:
}
template <typename FNfloat>
- float SingleValueCubic(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SingleValueCubic(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
int x1 = FastFloor(x);
int y1 = FastFloor(y);
@@ -1920,7 +1920,7 @@ private:
// Value Noise
template <typename FNfloat>
- float SingleValue(int seed, FNfloat x, FNfloat y)
+ float SingleValue(int seed, FNfloat x, FNfloat y) const
{
int x0 = FastFloor(x);
int y0 = FastFloor(y);
@@ -1940,7 +1940,7 @@ private:
}
template <typename FNfloat>
- float SingleValue(int seed, FNfloat x, FNfloat y, FNfloat z)
+ float SingleValue(int seed, FNfloat x, FNfloat y, FNfloat z) const
{
int x0 = FastFloor(x);
int y0 = FastFloor(y);
@@ -1972,7 +1972,7 @@ private:
// Domain Warp
template <typename FNfloat>
- void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr)
+ void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr) const
{
switch (mDomainWarpType)
{
@@ -1989,7 +1989,7 @@ private:
}
template <typename FNfloat>
- void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr)
+ void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr) const
{
switch (mDomainWarpType)
{
@@ -2009,7 +2009,7 @@ private:
// Domain Warp Single Wrapper
template <typename FNfloat>
- void DomainWarpSingle(FNfloat& x, FNfloat& y)
+ void DomainWarpSingle(FNfloat& x, FNfloat& y) const
{
int seed = mSeed;
float amp = mDomainWarpAmp * mFractalBounding;
@@ -2023,7 +2023,7 @@ private:
}
template <typename FNfloat>
- void DomainWarpSingle(FNfloat& x, FNfloat& y, FNfloat& z)
+ void DomainWarpSingle(FNfloat& x, FNfloat& y, FNfloat& z) const
{
int seed = mSeed;
float amp = mDomainWarpAmp * mFractalBounding;
@@ -2041,7 +2041,7 @@ private:
// Domain Warp Fractal Progressive
template <typename FNfloat>
- void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y)
+ void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y) const
{
int seed = mSeed;
float amp = mDomainWarpAmp * mFractalBounding;
@@ -2062,7 +2062,7 @@ private:
}
template <typename FNfloat>
- void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y, FNfloat& z)
+ void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y, FNfloat& z) const
{
int seed = mSeed;
float amp = mDomainWarpAmp * mFractalBounding;
@@ -2087,7 +2087,7 @@ private:
// Domain Warp Fractal Independant
template <typename FNfloat>
- void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y)
+ void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y) const
{
FNfloat xs = x;
FNfloat ys = y;
@@ -2108,7 +2108,7 @@ private:
}
template <typename FNfloat>
- void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y, FNfloat& z)
+ void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y, FNfloat& z) const
{
FNfloat xs = x;
FNfloat ys = y;
@@ -2133,7 +2133,7 @@ private:
// Domain Warp Basic Grid
template <typename FNfloat>
- void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr)
+ void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr) const
{
FNfloat xf = x * frequency;
FNfloat yf = y * frequency;
@@ -2166,7 +2166,7 @@ private:
}
template <typename FNfloat>
- void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr)
+ void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr) const
{
FNfloat xf = x * frequency;
FNfloat yf = y * frequency;
@@ -2228,7 +2228,7 @@ private:
// Domain Warp Simplex/OpenSimplex2
template <typename FNfloat>
- void SingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr, bool outGradOnly)
+ void SingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr, bool outGradOnly) const
{
const float SQRT3 = 1.7320508075688772935274463415059f;
const float G2 = (3 - SQRT3) / 6;
@@ -2326,7 +2326,7 @@ private:
}
template <typename FNfloat>
- void SingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr, bool outGradOnly)
+ void SingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr, bool outGradOnly) const
{
x *= frequency;
y *= frequency;
diff --git a/thirdparty/noise/patches/FastNoiseLite.patch b/thirdparty/noise/patches/FastNoiseLite.patch
index acb1edfd73..41ec943077 100644
--- a/thirdparty/noise/patches/FastNoiseLite.patch
+++ b/thirdparty/noise/patches/FastNoiseLite.patch
@@ -16,3 +16,417 @@
-#endif
+}
+#endif // namespace fastnoiselite
+@@ -295,7 +295,7 @@ public:
+ /// Noise output bounded between -1...1
+ /// </returns>
+ template <typename FNfloat>
+- float GetNoise(FNfloat x, FNfloat y)
++ float GetNoise(FNfloat x, FNfloat y) const
+ {
+ Arguments_must_be_floating_point_values<FNfloat>();
+
+@@ -321,7 +321,7 @@ public:
+ /// Noise output bounded between -1...1
+ /// </returns>
+ template <typename FNfloat>
+- float GetNoise(FNfloat x, FNfloat y, FNfloat z)
++ float GetNoise(FNfloat x, FNfloat y, FNfloat z) const
+ {
+ Arguments_must_be_floating_point_values<FNfloat>();
+
+@@ -350,7 +350,7 @@ public:
+ /// noise = GetNoise(x, y)</code>
+ /// </example>
+ template <typename FNfloat>
+- void DomainWarp(FNfloat& x, FNfloat& y)
++ void DomainWarp(FNfloat& x, FNfloat& y) const
+ {
+ Arguments_must_be_floating_point_values<FNfloat>();
+
+@@ -377,7 +377,7 @@ public:
+ /// noise = GetNoise(x, y, z)</code>
+ /// </example>
+ template <typename FNfloat>
+- void DomainWarp(FNfloat& x, FNfloat& y, FNfloat& z)
++ void DomainWarp(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ Arguments_must_be_floating_point_values<FNfloat>();
+
+@@ -528,7 +528,7 @@ private:
+ }
+
+
+- float GradCoord(int seed, int xPrimed, int yPrimed, float xd, float yd)
++ float GradCoord(int seed, int xPrimed, int yPrimed, float xd, float yd) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed);
+ hash ^= hash >> 15;
+@@ -541,7 +541,7 @@ private:
+ }
+
+
+- float GradCoord(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd)
++ float GradCoord(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed, zPrimed);
+ hash ^= hash >> 15;
+@@ -555,7 +555,7 @@ private:
+ }
+
+
+- void GradCoordOut(int seed, int xPrimed, int yPrimed, float& xo, float& yo)
++ void GradCoordOut(int seed, int xPrimed, int yPrimed, float& xo, float& yo) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed) & (255 << 1);
+
+@@ -564,7 +564,7 @@ private:
+ }
+
+
+- void GradCoordOut(int seed, int xPrimed, int yPrimed, int zPrimed, float& xo, float& yo, float& zo)
++ void GradCoordOut(int seed, int xPrimed, int yPrimed, int zPrimed, float& xo, float& yo, float& zo) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed, zPrimed) & (255 << 2);
+
+@@ -574,7 +574,7 @@ private:
+ }
+
+
+- void GradCoordDual(int seed, int xPrimed, int yPrimed, float xd, float yd, float& xo, float& yo)
++ void GradCoordDual(int seed, int xPrimed, int yPrimed, float xd, float yd, float& xo, float& yo) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed);
+ int index1 = hash & (127 << 1);
+@@ -592,7 +592,7 @@ private:
+ }
+
+
+- void GradCoordDual(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd, float& xo, float& yo, float& zo)
++ void GradCoordDual(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd, float& xo, float& yo, float& zo) const
+ {
+ int hash = Hash(seed, xPrimed, yPrimed, zPrimed);
+ int index1 = hash & (63 << 2);
+@@ -616,7 +616,7 @@ private:
+ // Generic noise gen
+
+ template <typename FNfloat>
+- float GenNoiseSingle(int seed, FNfloat x, FNfloat y)
++ float GenNoiseSingle(int seed, FNfloat x, FNfloat y) const
+ {
+ switch (mNoiseType)
+ {
+@@ -638,7 +638,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float GenNoiseSingle(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float GenNoiseSingle(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ switch (mNoiseType)
+ {
+@@ -663,7 +663,7 @@ private:
+ // Noise Coordinate Transforms (frequency, and possible skew or rotation)
+
+ template <typename FNfloat>
+- void TransformNoiseCoordinate(FNfloat& x, FNfloat& y)
++ void TransformNoiseCoordinate(FNfloat& x, FNfloat& y) const
+ {
+ x *= mFrequency;
+ y *= mFrequency;
+@@ -686,7 +686,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void TransformNoiseCoordinate(FNfloat& x, FNfloat& y, FNfloat& z)
++ void TransformNoiseCoordinate(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ x *= mFrequency;
+ y *= mFrequency;
+@@ -757,7 +757,7 @@ private:
+ // Domain Warp Coordinate Transforms
+
+ template <typename FNfloat>
+- void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y)
++ void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y) const
+ {
+ switch (mDomainWarpType)
+ {
+@@ -777,7 +777,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y, FNfloat& z)
++ void TransformDomainWarpCoordinate(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ switch (mWarpTransformType3D)
+ {
+@@ -844,7 +844,7 @@ private:
+ // Fractal FBm
+
+ template <typename FNfloat>
+- float GenFractalFBm(FNfloat x, FNfloat y)
++ float GenFractalFBm(FNfloat x, FNfloat y) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -865,7 +865,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float GenFractalFBm(FNfloat x, FNfloat y, FNfloat z)
++ float GenFractalFBm(FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -890,7 +890,7 @@ private:
+ // Fractal Ridged
+
+ template <typename FNfloat>
+- float GenFractalRidged(FNfloat x, FNfloat y)
++ float GenFractalRidged(FNfloat x, FNfloat y) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -911,7 +911,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float GenFractalRidged(FNfloat x, FNfloat y, FNfloat z)
++ float GenFractalRidged(FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -936,7 +936,7 @@ private:
+ // Fractal PingPong
+
+ template <typename FNfloat>
+- float GenFractalPingPong(FNfloat x, FNfloat y)
++ float GenFractalPingPong(FNfloat x, FNfloat y) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -957,7 +957,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float GenFractalPingPong(FNfloat x, FNfloat y, FNfloat z)
++ float GenFractalPingPong(FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int seed = mSeed;
+ float sum = 0;
+@@ -982,7 +982,7 @@ private:
+ // Simplex/OpenSimplex2 Noise
+
+ template <typename FNfloat>
+- float SingleSimplex(int seed, FNfloat x, FNfloat y)
++ float SingleSimplex(int seed, FNfloat x, FNfloat y) const
+ {
+ // 2D OpenSimplex2 case uses the same algorithm as ordinary Simplex.
+
+@@ -1053,7 +1053,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SingleOpenSimplex2(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SingleOpenSimplex2(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ // 3D OpenSimplex2 case uses two offset rotated cube grids.
+
+@@ -1155,7 +1155,7 @@ private:
+ // OpenSimplex2S Noise
+
+ template <typename FNfloat>
+- float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y)
++ float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y) const
+ {
+ // 2D OpenSimplex2S case is a modified 2D simplex noise.
+
+@@ -1286,7 +1286,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SingleOpenSimplex2S(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ // 3D OpenSimplex2S case uses two offset rotated cube grids.
+
+@@ -1482,7 +1482,7 @@ private:
+ // Cellular Noise
+
+ template <typename FNfloat>
+- float SingleCellular(int seed, FNfloat x, FNfloat y)
++ float SingleCellular(int seed, FNfloat x, FNfloat y) const
+ {
+ int xr = FastRound(x);
+ int yr = FastRound(y);
+@@ -1612,7 +1612,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SingleCellular(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SingleCellular(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int xr = FastRound(x);
+ int yr = FastRound(y);
+@@ -1769,7 +1769,7 @@ private:
+ // Perlin Noise
+
+ template <typename FNfloat>
+- float SinglePerlin(int seed, FNfloat x, FNfloat y)
++ float SinglePerlin(int seed, FNfloat x, FNfloat y) const
+ {
+ int x0 = FastFloor(x);
+ int y0 = FastFloor(y);
+@@ -1794,7 +1794,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SinglePerlin(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SinglePerlin(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int x0 = FastFloor(x);
+ int y0 = FastFloor(y);
+@@ -1833,7 +1833,7 @@ private:
+ // Value Cubic Noise
+
+ template <typename FNfloat>
+- float SingleValueCubic(int seed, FNfloat x, FNfloat y)
++ float SingleValueCubic(int seed, FNfloat x, FNfloat y) const
+ {
+ int x1 = FastFloor(x);
+ int y1 = FastFloor(y);
+@@ -1863,7 +1863,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SingleValueCubic(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SingleValueCubic(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int x1 = FastFloor(x);
+ int y1 = FastFloor(y);
+@@ -1920,7 +1920,7 @@ private:
+ // Value Noise
+
+ template <typename FNfloat>
+- float SingleValue(int seed, FNfloat x, FNfloat y)
++ float SingleValue(int seed, FNfloat x, FNfloat y) const
+ {
+ int x0 = FastFloor(x);
+ int y0 = FastFloor(y);
+@@ -1940,7 +1940,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- float SingleValue(int seed, FNfloat x, FNfloat y, FNfloat z)
++ float SingleValue(int seed, FNfloat x, FNfloat y, FNfloat z) const
+ {
+ int x0 = FastFloor(x);
+ int y0 = FastFloor(y);
+@@ -1972,7 +1972,7 @@ private:
+ // Domain Warp
+
+ template <typename FNfloat>
+- void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr)
++ void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr) const
+ {
+ switch (mDomainWarpType)
+ {
+@@ -1989,7 +1989,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr)
++ void DoSingleDomainWarp(int seed, float amp, float freq, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr) const
+ {
+ switch (mDomainWarpType)
+ {
+@@ -2009,7 +2009,7 @@ private:
+ // Domain Warp Single Wrapper
+
+ template <typename FNfloat>
+- void DomainWarpSingle(FNfloat& x, FNfloat& y)
++ void DomainWarpSingle(FNfloat& x, FNfloat& y) const
+ {
+ int seed = mSeed;
+ float amp = mDomainWarpAmp * mFractalBounding;
+@@ -2023,7 +2023,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void DomainWarpSingle(FNfloat& x, FNfloat& y, FNfloat& z)
++ void DomainWarpSingle(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ int seed = mSeed;
+ float amp = mDomainWarpAmp * mFractalBounding;
+@@ -2041,7 +2041,7 @@ private:
+ // Domain Warp Fractal Progressive
+
+ template <typename FNfloat>
+- void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y)
++ void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y) const
+ {
+ int seed = mSeed;
+ float amp = mDomainWarpAmp * mFractalBounding;
+@@ -2062,7 +2062,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y, FNfloat& z)
++ void DomainWarpFractalProgressive(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ int seed = mSeed;
+ float amp = mDomainWarpAmp * mFractalBounding;
+@@ -2087,7 +2087,7 @@ private:
+ // Domain Warp Fractal Independant
+
+ template <typename FNfloat>
+- void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y)
++ void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y) const
+ {
+ FNfloat xs = x;
+ FNfloat ys = y;
+@@ -2108,7 +2108,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y, FNfloat& z)
++ void DomainWarpFractalIndependent(FNfloat& x, FNfloat& y, FNfloat& z) const
+ {
+ FNfloat xs = x;
+ FNfloat ys = y;
+@@ -2133,7 +2133,7 @@ private:
+ // Domain Warp Basic Grid
+
+ template <typename FNfloat>
+- void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr)
++ void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr) const
+ {
+ FNfloat xf = x * frequency;
+ FNfloat yf = y * frequency;
+@@ -2166,7 +2166,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr)
++ void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr) const
+ {
+ FNfloat xf = x * frequency;
+ FNfloat yf = y * frequency;
+@@ -2228,7 +2228,7 @@ private:
+ // Domain Warp Simplex/OpenSimplex2
+
+ template <typename FNfloat>
+- void SingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr, bool outGradOnly)
++ void SingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat& xr, FNfloat& yr, bool outGradOnly) const
+ {
+ const float SQRT3 = 1.7320508075688772935274463415059f;
+ const float G2 = (3 - SQRT3) / 6;
+@@ -2326,7 +2326,7 @@ private:
+ }
+
+ template <typename FNfloat>
+- void SingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr, bool outGradOnly)
++ void SingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, FNfloat x, FNfloat y, FNfloat z, FNfloat& xr, FNfloat& yr, FNfloat& zr, bool outGradOnly) const
+ {
+ x *= frequency;
+ y *= frequency;