summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--SConstruct28
-rw-r--r--core/config/project_settings.cpp19
-rw-r--r--core/core_bind.cpp10
-rw-r--r--core/core_bind.h10
-rw-r--r--core/doc_data.h340
-rw-r--r--core/extension/extension_api_dump.cpp39
-rw-r--r--core/extension/gdnative_interface.h13
-rw-r--r--core/extension/native_extension.cpp2
-rw-r--r--core/input/input.cpp2
-rw-r--r--core/input/input_event.cpp15
-rw-r--r--core/input/input_event.h4
-rw-r--r--core/input/input_map.cpp7
-rw-r--r--core/io/image.cpp57
-rw-r--r--core/io/image.h18
-rw-r--r--core/io/resource_format_binary.cpp7
-rw-r--r--core/io/resource_loader.cpp6
-rw-r--r--core/io/resource_loader.h1
-rw-r--r--core/io/resource_saver.cpp33
-rw-r--r--core/io/resource_saver.h2
-rw-r--r--core/io/zip_io.cpp12
-rw-r--r--core/math/aabb.cpp4
-rw-r--r--core/math/aabb.h1
-rw-r--r--core/math/basis.cpp4
-rw-r--r--core/math/basis.h1
-rw-r--r--core/math/convex_hull.cpp54
-rw-r--r--core/math/convex_hull.h6
-rw-r--r--core/math/geometry_3d.cpp50
-rw-r--r--core/math/geometry_3d.h12
-rw-r--r--core/math/math_funcs.h3
-rw-r--r--core/math/plane.cpp4
-rw-r--r--core/math/plane.h1
-rw-r--r--core/math/quaternion.cpp4
-rw-r--r--core/math/quaternion.h1
-rw-r--r--core/math/quick_hull.cpp19
-rw-r--r--core/math/random_number_generator.h2
-rw-r--r--core/math/rect2.cpp4
-rw-r--r--core/math/rect2.h1
-rw-r--r--core/math/transform_2d.cpp4
-rw-r--r--core/math/transform_2d.h1
-rw-r--r--core/math/transform_3d.cpp4
-rw-r--r--core/math/transform_3d.h1
-rw-r--r--core/math/vector2.cpp4
-rw-r--r--core/math/vector2.h1
-rw-r--r--core/math/vector3.cpp4
-rw-r--r--core/math/vector3.h1
-rw-r--r--core/math/vector4.cpp4
-rw-r--r--core/math/vector4.h1
-rw-r--r--core/object/class_db.cpp5
-rw-r--r--core/object/method_bind.cpp4
-rw-r--r--core/object/method_bind.h48
-rw-r--r--core/object/object.cpp44
-rw-r--r--core/object/object.h2
-rw-r--r--core/object/script_language_extension.h7
-rw-r--r--core/os/midi_driver.cpp5
-rw-r--r--core/os/os.h2
-rw-r--r--core/string/ustring.cpp79
-rw-r--r--core/variant/array.cpp8
-rw-r--r--core/variant/array.h1
-rw-r--r--core/variant/container_type_validate.h15
-rw-r--r--core/variant/variant.cpp348
-rw-r--r--core/variant/variant_call.cpp15
-rw-r--r--core/variant/variant_destruct.cpp5
-rw-r--r--core/variant/variant_destruct.h5
-rw-r--r--core/variant/variant_internal.h27
-rw-r--r--core/variant/variant_op.cpp6
-rw-r--r--core/variant/variant_utility.cpp5
-rw-r--r--doc/classes/@GlobalScope.xml480
-rw-r--r--doc/classes/AABB.xml7
-rw-r--r--doc/classes/AStar2D.xml2
-rw-r--r--doc/classes/AStar3D.xml2
-rw-r--r--doc/classes/Animation.xml16
-rw-r--r--doc/classes/AnimationPlayer.xml7
-rw-r--r--doc/classes/Area3D.xml6
-rw-r--r--doc/classes/Array.xml20
-rw-r--r--doc/classes/AudioStreamGeneratorPlayback.xml2
-rw-r--r--doc/classes/BaseButton.xml3
-rw-r--r--doc/classes/BaseMaterial3D.xml16
-rw-r--r--doc/classes/Basis.xml13
-rw-r--r--doc/classes/BoneMap.xml1
-rw-r--r--doc/classes/CPUParticles2D.xml36
-rw-r--r--doc/classes/CPUParticles3D.xml8
-rw-r--r--doc/classes/Camera2D.xml18
-rw-r--r--doc/classes/CanvasItem.xml10
-rw-r--r--doc/classes/CanvasLayer.xml1
-rw-r--r--doc/classes/CanvasTexture.xml11
-rw-r--r--doc/classes/CheckBox.xml2
-rw-r--r--doc/classes/CheckButton.xml2
-rw-r--r--doc/classes/ClassDB.xml2
-rw-r--r--doc/classes/Color.xml15
-rw-r--r--doc/classes/ColorPicker.xml3
-rw-r--r--doc/classes/Control.xml9
-rw-r--r--doc/classes/CylinderShape3D.xml1
-rw-r--r--doc/classes/Dictionary.xml3
-rw-r--r--doc/classes/DisplayServer.xml4
-rw-r--r--doc/classes/EditorFileDialog.xml3
-rw-r--r--doc/classes/EditorInterface.xml1
-rw-r--r--doc/classes/EditorPlugin.xml2
-rw-r--r--doc/classes/EditorProperty.xml1
-rw-r--r--doc/classes/EditorScript.xml1
-rw-r--r--doc/classes/EditorSettings.xml24
-rw-r--r--doc/classes/EditorSpinSlider.xml3
-rw-r--r--doc/classes/Engine.xml6
-rw-r--r--doc/classes/Environment.xml1
-rw-r--r--doc/classes/FogMaterial.xml1
-rw-r--r--doc/classes/GPUParticles2D.xml2
-rw-r--r--doc/classes/GPUParticles3D.xml2
-rw-r--r--doc/classes/Image.xml27
-rw-r--r--doc/classes/InputEventMIDI.xml2
-rw-r--r--doc/classes/InputEventScreenTouch.xml3
-rw-r--r--doc/classes/Light3D.xml2
-rw-r--r--doc/classes/MenuBar.xml3
-rw-r--r--doc/classes/Mesh.xml2
-rw-r--r--doc/classes/MultiMesh.xml2
-rw-r--r--doc/classes/MultiplayerPeer.xml20
-rw-r--r--doc/classes/NavigationAgent2D.xml2
-rw-r--r--doc/classes/Node.xml4
-rw-r--r--doc/classes/Node3D.xml1
-rw-r--r--doc/classes/NodePath.xml2
-rw-r--r--doc/classes/OS.xml17
-rw-r--r--doc/classes/Object.xml8
-rw-r--r--doc/classes/OmniLight3D.xml1
-rw-r--r--doc/classes/ParticleProcessMaterial.xml6
-rw-r--r--doc/classes/Plane.xml6
-rw-r--r--doc/classes/PopupMenu.xml2
-rw-r--r--doc/classes/ProjectSettings.xml36
-rw-r--r--doc/classes/Projection.xml62
-rw-r--r--doc/classes/PropertyTweener.xml2
-rw-r--r--doc/classes/Quaternion.xml6
-rw-r--r--doc/classes/RDPipelineRasterizationState.xml2
-rw-r--r--doc/classes/RandomNumberGenerator.xml3
-rw-r--r--doc/classes/Rect2.xml6
-rw-r--r--doc/classes/RenderingDevice.xml4
-rw-r--r--doc/classes/RenderingServer.xml6
-rw-r--r--doc/classes/Resource.xml58
-rw-r--r--doc/classes/ResourceFormatLoader.xml9
-rw-r--r--doc/classes/ResourceFormatSaver.xml9
-rw-r--r--doc/classes/RichTextLabel.xml4
-rw-r--r--doc/classes/Script.xml2
-rw-r--r--doc/classes/Shape2D.xml6
-rw-r--r--doc/classes/SkeletonProfile.xml1
-rw-r--r--doc/classes/SkeletonProfileHumanoid.xml1
-rw-r--r--doc/classes/SpotLight3D.xml2
-rw-r--r--doc/classes/StandardMaterial3D.xml2
-rw-r--r--doc/classes/String.xml2
-rw-r--r--doc/classes/SurfaceTool.xml1
-rw-r--r--doc/classes/TextEdit.xml18
-rw-r--r--doc/classes/TextLine.xml1
-rw-r--r--doc/classes/Texture2D.xml2
-rw-r--r--doc/classes/TileMap.xml2
-rw-r--r--doc/classes/Transform2D.xml6
-rw-r--r--doc/classes/Transform3D.xml6
-rw-r--r--doc/classes/TreeItem.xml9
-rw-r--r--doc/classes/VSlider.xml1
-rw-r--r--doc/classes/Vector2.xml6
-rw-r--r--doc/classes/Vector3.xml14
-rw-r--r--doc/classes/Vector4.xml6
-rw-r--r--doc/classes/Vector4i.xml8
-rw-r--r--doc/classes/Viewport.xml8
-rw-r--r--doc/classes/ViewportTexture.xml1
-rw-r--r--doc/classes/VisibleOnScreenEnabler2D.xml7
-rw-r--r--doc/classes/VisualInstance3D.xml9
-rw-r--r--doc/classes/XROrigin3D.xml3
-rw-r--r--doc/classes/XRPose.xml4
-rw-r--r--doc/classes/XRServer.xml6
-rw-r--r--doc/classes/float.xml8
-rw-r--r--doc/classes/int.xml12
-rw-r--r--drivers/SCsub2
-rw-r--r--drivers/gles3/effects/copy_effects.cpp2
-rw-r--r--drivers/gles3/effects/copy_effects.h2
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.cpp365
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.h47
-rw-r--r--drivers/gles3/rasterizer_gles3.cpp25
-rw-r--r--drivers/gles3/rasterizer_gles3.h2
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp62
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.h13
-rw-r--r--drivers/gles3/shader_gles3.cpp33
-rw-r--r--drivers/gles3/shader_gles3.h2
-rw-r--r--drivers/gles3/shaders/canvas.glsl172
-rw-r--r--drivers/gles3/shaders/canvas_uniforms_inc.glsl22
-rw-r--r--drivers/gles3/shaders/copy.glsl5
-rw-r--r--drivers/gles3/shaders/scene.glsl51
-rw-r--r--drivers/gles3/shaders/tonemap.glsl20
-rw-r--r--drivers/gles3/storage/config.cpp20
-rw-r--r--drivers/gles3/storage/config.h10
-rw-r--r--drivers/gles3/storage/material_storage.cpp4
-rw-r--r--drivers/gles3/storage/mesh_storage.cpp36
-rw-r--r--drivers/gles3/storage/mesh_storage.h11
-rw-r--r--drivers/gles3/storage/render_scene_buffers_gles3.cpp48
-rw-r--r--drivers/gles3/storage/render_scene_buffers_gles3.h2
-rw-r--r--drivers/gles3/storage/texture_storage.cpp333
-rw-r--r--drivers/gles3/storage/texture_storage.h52
-rw-r--r--drivers/gles3/storage/utilities.cpp10
-rw-r--r--drivers/gles3/storage/utilities.h2
-rw-r--r--drivers/png/png_driver_common.cpp2
-rw-r--r--drivers/unix/net_socket_posix.cpp4
-rw-r--r--drivers/unix/os_unix.cpp4
-rw-r--r--drivers/unix/os_unix.h2
-rw-r--r--drivers/unix/thread_posix.cpp4
-rw-r--r--drivers/vulkan/rendering_device_vulkan.cpp18
-rw-r--r--drivers/vulkan/vulkan_context.cpp152
-rw-r--r--drivers/vulkan/vulkan_context.h3
-rw-r--r--drivers/wasapi/audio_driver_wasapi.cpp23
-rw-r--r--drivers/wasapi/audio_driver_wasapi.h2
-rw-r--r--editor/animation_track_editor.cpp2
-rw-r--r--editor/code_editor.cpp97
-rw-r--r--editor/code_editor.h2
-rw-r--r--editor/connections_dialog.cpp131
-rw-r--r--editor/connections_dialog.h4
-rw-r--r--editor/create_dialog.cpp4
-rw-r--r--editor/debugger/debug_adapter/debug_adapter_protocol.cpp2
-rw-r--r--editor/debugger/editor_profiler.cpp4
-rw-r--r--editor/debugger/editor_visual_profiler.cpp4
-rw-r--r--editor/editor_build_profile.cpp3
-rw-r--r--editor/editor_file_system.cpp14
-rw-r--r--editor/editor_node.cpp20
-rw-r--r--editor/editor_properties.cpp9
-rw-r--r--editor/editor_properties_array_dict.cpp6
-rw-r--r--editor/editor_resource_picker.cpp1
-rw-r--r--editor/editor_settings.cpp3
-rw-r--r--editor/editor_spin_slider.cpp2
-rw-r--r--editor/editor_themes.cpp4
-rw-r--r--editor/editor_zoom_widget.cpp10
-rw-r--r--editor/editor_zoom_widget.h2
-rw-r--r--editor/event_listener_line_edit.cpp13
-rw-r--r--editor/event_listener_line_edit.h4
-rw-r--r--editor/export/editor_export_platform.h1
-rw-r--r--editor/export/editor_export_platform_pc.cpp6
-rw-r--r--editor/export/project_export.cpp4
-rw-r--r--editor/groups_editor.cpp144
-rw-r--r--editor/groups_editor.h11
-rw-r--r--editor/icons/BoneMapHumanBody.svg27
-rw-r--r--editor/icons/Line.svg1
-rw-r--r--editor/import/collada.cpp2
-rw-r--r--editor/import/editor_import_collada.cpp6
-rw-r--r--editor/import/resource_importer_layered_texture.cpp6
-rw-r--r--editor/import/resource_importer_scene.cpp237
-rw-r--r--editor/import/resource_importer_scene.h4
-rw-r--r--editor/import/resource_importer_texture.cpp3
-rw-r--r--editor/import/resource_importer_texture_atlas.cpp4
-rw-r--r--editor/input_event_configuration_dialog.cpp4
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp36
-rw-r--r--editor/plugins/animation_player_editor_plugin.h1
-rw-r--r--editor/plugins/bone_map_editor_plugin.h1
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp12
-rw-r--r--editor/plugins/canvas_item_editor_plugin.h3
-rw-r--r--editor/plugins/curve_editor_plugin.cpp2
-rw-r--r--editor/plugins/editor_preview_plugins.cpp12
-rw-r--r--editor/plugins/font_config_plugin.cpp4
-rw-r--r--editor/plugins/gpu_particles_2d_editor_plugin.cpp6
-rw-r--r--editor/plugins/node_3d_editor_gizmos.cpp6
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp62
-rw-r--r--editor/plugins/node_3d_editor_plugin.h10
-rw-r--r--editor/plugins/script_text_editor.cpp126
-rw-r--r--editor/plugins/script_text_editor.h1
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.cpp105
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.h10
-rw-r--r--editor/plugins/texture_editor_plugin.cpp2
-rw-r--r--editor/plugins/tiles/atlas_merging_dialog.cpp4
-rw-r--r--editor/plugins/tiles/tile_atlas_view.cpp2
-rw-r--r--editor/plugins/tiles/tile_data_editors.cpp1
-rw-r--r--editor/plugins/tiles/tile_map_editor.cpp39
-rw-r--r--editor/plugins/tiles/tiles_editor_plugin.cpp10
-rw-r--r--editor/plugins/tiles/tiles_editor_plugin.h2
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp132
-rw-r--r--editor/project_converter_3_to_4.cpp28
-rw-r--r--editor/project_manager.cpp12
-rw-r--r--editor/scene_tree_dock.cpp9
-rw-r--r--main/main.cpp14
-rw-r--r--misc/dist/html/editor.html1449
-rw-r--r--misc/dist/html/full-size.html472
-rw-r--r--misc/dist/html/offline-export.html71
-rw-r--r--misc/dist/html/offline.html74
-rwxr-xr-xmisc/scripts/dotnet_format.sh7
-rw-r--r--modules/basis_universal/register_types.cpp2
-rw-r--r--modules/bmp/image_loader_bmp.cpp4
-rw-r--r--modules/camera/camera_macos.mm4
-rw-r--r--modules/csg/doc_classes/CSGShape3D.xml5
-rw-r--r--modules/cvtt/image_compress_cvtt.cpp4
-rw-r--r--modules/denoise/lightmap_denoiser.cpp2
-rw-r--r--modules/enet/doc_classes/ENetMultiplayerPeer.xml3
-rw-r--r--modules/enet/enet_multiplayer_peer.cpp225
-rw-r--r--modules/enet/enet_multiplayer_peer.h20
-rw-r--r--modules/etcpak/image_compress_etcpak.cpp2
-rw-r--r--modules/gdscript/doc_classes/@GDScript.xml96
-rw-r--r--modules/gdscript/doc_classes/GDScript.xml2
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.cpp23
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.h3
-rw-r--r--modules/gdscript/gdscript.cpp5
-rw-r--r--modules/gdscript/gdscript.h1
-rw-r--r--modules/gdscript/gdscript_analyzer.cpp28
-rw-r--r--modules/gdscript/gdscript_analyzer.h2
-rw-r--r--modules/gdscript/gdscript_warning.cpp5
-rw-r--r--modules/gdscript/gdscript_warning.h1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd11
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out7
-rw-r--r--modules/glslang/register_types.cpp4
-rw-r--r--modules/gltf/doc_classes/GLTFNode.xml19
-rw-r--r--modules/gltf/doc_classes/GLTFState.xml17
-rw-r--r--modules/gltf/gltf_document.cpp11
-rw-r--r--modules/gltf/gltf_state.cpp10
-rw-r--r--modules/gltf/gltf_state.h4
-rw-r--r--modules/gltf/structures/gltf_node.cpp10
-rw-r--r--modules/gltf/structures/gltf_node.h4
-rw-r--r--modules/hdr/image_loader_hdr.cpp2
-rw-r--r--modules/jpg/image_loader_jpegd.cpp2
-rw-r--r--modules/lightmapper_rd/lightmapper_rd.cpp56
-rw-r--r--modules/mono/Directory.Build.targets6
-rw-r--r--modules/mono/class_db_api_json.cpp3
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs8
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs2
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs118
-rw-r--r--modules/mono/editor/bindings_generator.cpp17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs12
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj2
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj2
-rw-r--r--modules/mono/godotsharp_dirs.cpp152
-rw-r--r--modules/mono/godotsharp_dirs.h16
-rw-r--r--modules/multiplayer/doc_classes/SceneMultiplayer.xml4
-rw-r--r--modules/multiplayer/multiplayer_synchronizer.cpp4
-rw-r--r--modules/multiplayer/scene_cache_interface.cpp6
-rw-r--r--modules/multiplayer/scene_multiplayer.cpp163
-rw-r--r--modules/multiplayer/scene_multiplayer.h18
-rw-r--r--modules/multiplayer/scene_replication_interface.cpp9
-rw-r--r--modules/multiplayer/scene_rpc_interface.cpp9
-rw-r--r--modules/navigation/navigation_mesh_generator.cpp12
-rw-r--r--modules/noise/noise_texture_2d.cpp4
-rw-r--r--modules/openxr/SCsub1
-rw-r--r--modules/openxr/action_map/openxr_action_map.cpp20
-rw-r--r--modules/openxr/doc_classes/OpenXRInterface.xml13
-rw-r--r--modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp123
-rw-r--r--modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h (renamed from modules/websocket/websocket_client.h)63
-rw-r--r--modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp28
-rw-r--r--modules/openxr/openxr_api.cpp134
-rw-r--r--modules/openxr/openxr_api.h8
-rw-r--r--modules/openxr/openxr_interface.cpp88
-rw-r--r--modules/openxr/openxr_interface.h5
-rw-r--r--modules/regex/doc_classes/RegEx.xml2
-rw-r--r--modules/squish/image_decompress_squish.cpp2
-rw-r--r--modules/svg/SCsub43
-rw-r--r--modules/svg/image_loader_svg.cpp2
-rw-r--r--modules/text_server_adv/text_server_adv.cpp37
-rw-r--r--modules/text_server_fb/text_server_fb.cpp36
-rw-r--r--modules/tga/image_loader_tga.cpp2
-rw-r--r--modules/theora/video_stream_theora.cpp4
-rw-r--r--modules/tinyexr/image_loader_tinyexr.cpp2
-rw-r--r--modules/upnp/doc_classes/UPNP.xml2
-rw-r--r--modules/webp/webp_common.cpp2
-rw-r--r--modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml39
-rw-r--r--modules/webrtc/webrtc_multiplayer_peer.cpp85
-rw-r--r--modules/webrtc/webrtc_multiplayer_peer.h20
-rw-r--r--modules/websocket/doc_classes/WebSocketClient.xml94
-rw-r--r--modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml84
-rw-r--r--modules/websocket/doc_classes/WebSocketPeer.xml143
-rw-r--r--modules/websocket/doc_classes/WebSocketServer.xml127
-rw-r--r--modules/websocket/editor/editor_debugger_server_websocket.cpp58
-rw-r--r--modules/websocket/editor/editor_debugger_server_websocket.h9
-rw-r--r--modules/websocket/emws_client.cpp159
-rw-r--r--modules/websocket/emws_peer.cpp166
-rw-r--r--modules/websocket/emws_peer.h48
-rw-r--r--modules/websocket/packet_buffer.h58
-rw-r--r--modules/websocket/register_types.cpp33
-rw-r--r--modules/websocket/remote_debugger_peer_websocket.cpp44
-rw-r--r--modules/websocket/remote_debugger_peer_websocket.h7
-rw-r--r--modules/websocket/websocket_client.cpp141
-rw-r--r--modules/websocket/websocket_multiplayer_peer.cpp520
-rw-r--r--modules/websocket/websocket_multiplayer_peer.h85
-rw-r--r--modules/websocket/websocket_peer.cpp107
-rw-r--r--modules/websocket/websocket_peer.h67
-rw-r--r--modules/websocket/websocket_server.cpp167
-rw-r--r--modules/websocket/websocket_server.h90
-rw-r--r--modules/websocket/wsl_client.cpp407
-rw-r--r--modules/websocket/wsl_peer.cpp849
-rw-r--r--modules/websocket/wsl_peer.h130
-rw-r--r--modules/websocket/wsl_server.cpp329
-rw-r--r--modules/websocket/wsl_server.h98
-rw-r--r--modules/webxr/godot_webxr.h2
-rw-r--r--modules/webxr/native/library_godot_webxr.js41
-rw-r--r--modules/webxr/webxr_interface_js.cpp3
-rw-r--r--modules/zip/SCsub9
-rw-r--r--modules/zip/config.py17
-rw-r--r--modules/zip/doc_classes/ZIPPacker.xml72
-rw-r--r--modules/zip/doc_classes/ZIPReader.xml52
-rw-r--r--modules/zip/register_types.cpp (renamed from modules/websocket/wsl_client.h)75
-rw-r--r--modules/zip/register_types.h39
-rw-r--r--modules/zip/zip_packer.cpp108
-rw-r--r--modules/zip/zip_packer.h (renamed from modules/websocket/websocket_macros.h)64
-rw-r--r--modules/zip/zip_reader.cpp123
-rw-r--r--modules/zip/zip_reader.h (renamed from modules/websocket/emws_client.h)54
-rw-r--r--platform/android/android_input_handler.cpp9
-rw-r--r--platform/android/android_input_handler.h4
-rw-r--r--platform/android/api/jni_singleton.h5
-rw-r--r--platform/android/display_server_android.cpp6
-rw-r--r--platform/android/display_server_android.h4
-rw-r--r--platform/android/export/export_plugin.cpp31
-rw-r--r--platform/android/java/build.gradle12
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotLib.java2
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.kt25
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java26
-rw-r--r--platform/android/java_godot_lib_jni.cpp4
-rw-r--r--platform/android/java_godot_lib_jni.h2
-rw-r--r--platform/android/jni_utils.cpp5
-rw-r--r--platform/ios/display_server_ios.h4
-rw-r--r--platform/ios/display_server_ios.mm7
-rw-r--r--platform/ios/export/export_plugin.cpp6
-rw-r--r--platform/ios/view_controller.mm12
-rw-r--r--platform/linuxbsd/detect.py1
-rw-r--r--platform/linuxbsd/display_server_x11.cpp54
-rw-r--r--platform/linuxbsd/display_server_x11.h5
-rw-r--r--platform/linuxbsd/godot_linuxbsd.cpp1
-rw-r--r--platform/linuxbsd/os_linuxbsd.cpp203
-rw-r--r--platform/linuxbsd/os_linuxbsd.h5
-rw-r--r--platform/macos/display_server_macos.h6
-rw-r--r--platform/macos/display_server_macos.mm54
-rw-r--r--platform/macos/export/export_plugin.cpp131
-rw-r--r--platform/macos/export/export_plugin.h2
-rw-r--r--platform/macos/export/lipo.cpp6
-rw-r--r--platform/macos/export/lipo.h5
-rw-r--r--platform/macos/export/macho.cpp6
-rw-r--r--platform/macos/export/macho.h5
-rw-r--r--platform/macos/export/plist.cpp6
-rw-r--r--platform/macos/export/plist.h5
-rw-r--r--platform/macos/godot_button_view.h5
-rw-r--r--platform/macos/godot_button_view.mm22
-rw-r--r--platform/macos/joypad_macos.h6
-rw-r--r--platform/macos/os_macos.mm4
-rw-r--r--platform/uwp/os_uwp.cpp9
-rw-r--r--platform/web/.eslintrc.html.js19
-rw-r--r--platform/web/SCsub15
-rw-r--r--platform/web/display_server_web.cpp9
-rw-r--r--platform/web/display_server_web.h4
-rw-r--r--platform/web/export/export_plugin.cpp1
-rw-r--r--platform/web/godot_webgl2.h17
-rw-r--r--platform/web/js/libs/library_godot_javascript_singleton.js4
-rw-r--r--platform/web/js/libs/library_godot_webgl2.js52
-rw-r--r--platform/web/os_web.cpp8
-rw-r--r--platform/web/package-lock.json327
-rw-r--r--platform/web/package.json15
-rwxr-xr-xplatform/web/serve.py21
-rw-r--r--platform/windows/detect.py2
-rw-r--r--platform/windows/display_server_windows.cpp90
-rw-r--r--platform/windows/display_server_windows.h12
-rw-r--r--platform/windows/joypad_windows.h2
-rw-r--r--platform/windows/os_windows.cpp116
-rw-r--r--platform/windows/os_windows.h13
-rw-r--r--scene/2d/camera_2d.cpp46
-rw-r--r--scene/2d/camera_2d.h12
-rw-r--r--scene/2d/light_2d.cpp7
-rw-r--r--scene/2d/navigation_agent_2d.cpp4
-rw-r--r--scene/2d/skeleton_2d.cpp6
-rw-r--r--scene/2d/sprite_2d.cpp6
-rw-r--r--scene/2d/tile_map.cpp154
-rw-r--r--scene/2d/tile_map.h6
-rw-r--r--scene/3d/area_3d.cpp12
-rw-r--r--scene/3d/area_3d.h4
-rw-r--r--scene/3d/audio_stream_player_3d.cpp2
-rw-r--r--scene/3d/gpu_particles_collision_3d.cpp6
-rw-r--r--scene/3d/light_3d.cpp14
-rw-r--r--scene/3d/light_3d.h1
-rw-r--r--scene/3d/lightmap_gi.cpp9
-rw-r--r--scene/3d/navigation_agent_3d.cpp2
-rw-r--r--scene/3d/node_3d.cpp4
-rw-r--r--scene/3d/node_3d.h5
-rw-r--r--scene/3d/sprite_3d.cpp2
-rw-r--r--scene/3d/visible_on_screen_notifier_3d.cpp2
-rw-r--r--scene/3d/visual_instance_3d.cpp6
-rw-r--r--scene/3d/visual_instance_3d.h2
-rw-r--r--scene/3d/voxel_gi.cpp4
-rw-r--r--scene/3d/xr_nodes.cpp171
-rw-r--r--scene/3d/xr_nodes.h13
-rw-r--r--scene/animation/animation_player.cpp38
-rw-r--r--scene/gui/base_button.cpp38
-rw-r--r--scene/gui/base_button.h4
-rw-r--r--scene/gui/code_edit.cpp32
-rw-r--r--scene/gui/color_picker.cpp6
-rw-r--r--scene/gui/control.cpp51
-rw-r--r--scene/gui/control.h14
-rw-r--r--scene/gui/graph_edit.cpp8
-rw-r--r--scene/gui/item_list.cpp18
-rw-r--r--scene/gui/label.cpp32
-rw-r--r--scene/gui/label.h1
-rw-r--r--scene/gui/line_edit.cpp9
-rw-r--r--scene/gui/menu_bar.cpp40
-rw-r--r--scene/gui/menu_bar.h5
-rw-r--r--scene/gui/menu_button.cpp4
-rw-r--r--scene/gui/popup.cpp38
-rw-r--r--scene/gui/popup.h1
-rw-r--r--scene/gui/popup_menu.cpp10
-rw-r--r--scene/gui/rich_text_label.cpp65
-rw-r--r--scene/gui/rich_text_label.h2
-rw-r--r--scene/gui/scroll_bar.cpp14
-rw-r--r--scene/gui/slider.cpp4
-rw-r--r--scene/gui/text_edit.cpp88
-rw-r--r--scene/gui/text_edit.h4
-rw-r--r--scene/gui/tree.cpp17
-rw-r--r--scene/gui/view_panner.cpp4
-rw-r--r--scene/main/canvas_item.cpp56
-rw-r--r--scene/main/canvas_item.h23
-rw-r--r--scene/main/multiplayer_peer.cpp16
-rw-r--r--scene/main/multiplayer_peer.h8
-rw-r--r--scene/main/node.cpp84
-rw-r--r--scene/main/node.h11
-rw-r--r--scene/main/scene_tree.cpp28
-rw-r--r--scene/main/viewport.cpp14
-rw-r--r--scene/main/window.cpp78
-rw-r--r--scene/main/window.h2
-rw-r--r--scene/resources/animation.cpp16
-rw-r--r--scene/resources/bit_map.cpp4
-rw-r--r--scene/resources/convex_polygon_shape_3d.cpp6
-rw-r--r--scene/resources/environment.cpp2
-rw-r--r--scene/resources/material.cpp6
-rw-r--r--scene/resources/material.h2
-rw-r--r--scene/resources/mesh.cpp5
-rw-r--r--scene/resources/packed_scene.cpp6
-rw-r--r--scene/resources/packed_scene.h2
-rw-r--r--scene/resources/particle_process_material.cpp46
-rw-r--r--scene/resources/particle_process_material.h5
-rw-r--r--scene/resources/primitive_meshes.cpp3
-rw-r--r--scene/resources/resource_format_text.cpp7
-rw-r--r--scene/resources/shape_2d.cpp1
-rw-r--r--scene/resources/texture.cpp15
-rw-r--r--scene/resources/texture.h10
-rw-r--r--scene/resources/tile_set.cpp8
-rw-r--r--scene/resources/tile_set.h3
-rw-r--r--scene/resources/visual_shader.cpp5
-rw-r--r--scene/resources/visual_shader_nodes.cpp59
-rw-r--r--scene/resources/visual_shader_particle_nodes.cpp12
-rw-r--r--servers/display_server.cpp4
-rw-r--r--servers/display_server.h6
-rw-r--r--servers/display_server_headless.h2
-rw-r--r--servers/physics_3d/godot_body_3d.cpp2
-rw-r--r--servers/physics_3d/godot_collision_solver_3d_sat.cpp61
-rw-r--r--servers/physics_3d/godot_shape_3d.cpp134
-rw-r--r--servers/physics_3d/godot_shape_3d.h2
-rw-r--r--servers/rendering/dummy/storage/utilities.h2
-rw-r--r--servers/rendering/renderer_rd/effects/copy_effects.cpp4
-rw-r--r--servers/rendering/renderer_rd/environment/gi.cpp5
-rw-r--r--servers/rendering/renderer_rd/environment/sky.cpp4
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp26
-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.cpp24
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h4
-rw-r--r--servers/rendering/renderer_rd/pipeline_cache_rd.cpp5
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp54
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.h2
-rw-r--r--servers/rendering/renderer_rd/renderer_compositor_rd.cpp6
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_render_rd.cpp21
-rw-r--r--servers/rendering/renderer_rd/shader_rd.cpp1
-rw-r--r--servers/rendering/renderer_rd/shaders/canvas.glsl35
-rw-r--r--servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl2
-rw-r--r--servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl22
-rw-r--r--servers/rendering/renderer_rd/shaders/forward_mobile/scene_forward_mobile.glsl10
-rw-r--r--servers/rendering/renderer_rd/storage_rd/material_storage.cpp4
-rw-r--r--servers/rendering/renderer_rd/storage_rd/mesh_storage.h10
-rw-r--r--servers/rendering/renderer_rd/storage_rd/particles_storage.cpp6
-rw-r--r--servers/rendering/renderer_rd/storage_rd/render_scene_data_rd.h1
-rw-r--r--servers/rendering/renderer_rd/storage_rd/texture_storage.cpp30
-rw-r--r--servers/rendering/renderer_rd/storage_rd/utilities.cpp8
-rw-r--r--servers/rendering/renderer_rd/storage_rd/utilities.h2
-rw-r--r--servers/rendering/renderer_scene_cull.cpp7
-rw-r--r--servers/rendering/renderer_scene_occlusion_cull.cpp2
-rw-r--r--servers/rendering/rendering_device.cpp2
-rw-r--r--servers/rendering/rendering_device.h6
-rw-r--r--servers/rendering/rendering_device_binds.h4
-rw-r--r--servers/rendering/rendering_server_default.cpp8
-rw-r--r--servers/rendering/rendering_server_default.h2
-rw-r--r--servers/rendering/shader_language.cpp3
-rw-r--r--servers/rendering/storage/utilities.h2
-rw-r--r--servers/rendering_server.cpp12
-rw-r--r--servers/rendering_server.h5
-rw-r--r--servers/xr/xr_interface.cpp7
-rw-r--r--tests/core/math/test_aabb.h21
-rw-r--r--tests/core/math/test_basis.h37
-rw-r--r--tests/core/math/test_plane.h23
-rw-r--r--tests/core/math/test_quaternion.h65
-rw-r--r--tests/core/math/test_rect2.h21
-rw-r--r--tests/core/math/test_transform_2d.h34
-rw-r--r--tests/core/math/test_transform_3d.h23
-rw-r--r--tests/core/math/test_vector2.h26
-rw-r--r--tests/core/math/test_vector3.h45
-rw-r--r--tests/core/math/test_vector4.h78
-rw-r--r--tests/core/string/test_string.h22
-rw-r--r--tests/scene/test_bit_map.h8
-rw-r--r--tests/scene/test_text_edit.h173
-rw-r--r--tests/test_main.cpp2
-rw-r--r--thirdparty/README.md2
-rw-r--r--thirdparty/glad/KHR/khrplatform.h27
-rw-r--r--thirdparty/glad/glad.c20
-rw-r--r--thirdparty/glad/glad/glad.h25
-rw-r--r--thirdparty/thorvg/inc/config.h2
-rw-r--r--thirdparty/thorvg/src/lib/sw_engine/tvgSwCommon.h2
-rw-r--r--thirdparty/thorvg/src/lib/sw_engine/tvgSwFill.cpp2
-rw-r--r--thirdparty/thorvg/src/lib/sw_engine/tvgSwMath.cpp2
-rw-r--r--thirdparty/thorvg/src/lib/sw_engine/tvgSwRaster.cpp6
-rw-r--r--thirdparty/thorvg/src/lib/sw_engine/tvgSwStroke.cpp2
-rw-r--r--thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp164
-rw-r--r--thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h52
-rw-r--r--thirdparty/thorvg/src/loaders/png/tvgLodePng.cpp2647
-rw-r--r--thirdparty/thorvg/src/loaders/png/tvgLodePng.h174
-rw-r--r--thirdparty/thorvg/src/loaders/png/tvgPngLoader.cpp194
-rw-r--r--thirdparty/thorvg/src/loaders/png/tvgPngLoader.h54
-rw-r--r--thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp6
-rw-r--r--thirdparty/thorvg/src/loaders/tvg/tvgTvgBinInterpreter.cpp4
-rw-r--r--thirdparty/thorvg/src/savers/tvg/tvgTvgSaver.cpp4
-rwxr-xr-xthirdparty/thorvg/update-thorvg.sh8
613 files changed, 11659 insertions, 10289 deletions
diff --git a/.gitignore b/.gitignore
index 1a83e4707e..b939bb16d5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -154,6 +154,7 @@ gmon.out
# Jetbrains IDEs
.idea/
+.fleet/
# Kate
*.kate-swp
diff --git a/SConstruct b/SConstruct
index 1eb6bdcbfd..7009cb8fbe 100644
--- a/SConstruct
+++ b/SConstruct
@@ -182,8 +182,8 @@ opts.Add(BoolVariable("deprecated", "Enable compatibility code for deprecated an
opts.Add(EnumVariable("float", "Floating-point precision", "32", ("32", "64")))
opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver", False))
-opts.Add(BoolVariable("vulkan", "Enable the vulkan video driver", True))
-opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 video driver", True))
+opts.Add(BoolVariable("vulkan", "Enable the vulkan rendering driver", True))
+opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 rendering driver", True))
opts.Add(BoolVariable("openxr", "Enable the OpenXR driver", True))
opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True))
opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
@@ -687,6 +687,14 @@ if selected_platform in platform_list:
if methods.using_gcc(env):
common_warnings += ["-Wshadow-local", "-Wno-misleading-indentation"]
+ if cc_version_major == 7: # Bogus warning fixed in 8+.
+ common_warnings += ["-Wno-strict-overflow"]
+ if cc_version_major < 11:
+ # Regression in GCC 9/10, spams so much in our variadic templates
+ # that we need to outright disable it.
+ common_warnings += ["-Wno-type-limits"]
+ if cc_version_major >= 12: # False positives in our error macros, see GH-58747.
+ common_warnings += ["-Wno-return-type"]
elif methods.using_clang(env) or methods.using_emcc(env):
# We often implement `operator<` for structs of pointers as a requirement
# for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
@@ -702,13 +710,16 @@ if selected_platform in platform_list:
"-Wduplicated-branches",
"-Wduplicated-cond",
"-Wstringop-overflow=4",
- "-Wlogical-op",
]
)
- # -Wnoexcept was removed temporarily due to GH-36325.
env.Append(CXXFLAGS=["-Wplacement-new=1"])
+ # Need to fix a warning with AudioServer lambdas before enabling.
+ # if cc_version_major != 9: # GCC 9 had a regression (GH-36325).
+ # env.Append(CXXFLAGS=["-Wnoexcept"])
if cc_version_major >= 9:
env.Append(CCFLAGS=["-Wattribute-alias=2"])
+ if cc_version_major >= 11: # Broke on MethodBind templates before GCC 11.
+ env.Append(CCFLAGS=["-Wlogical-op"])
elif methods.using_clang(env) or methods.using_emcc(env):
env.Append(CCFLAGS=["-Wimplicit-fallthrough"])
elif env["warnings"] == "all":
@@ -720,15 +731,6 @@ if selected_platform in platform_list:
if env["werror"]:
env.Append(CCFLAGS=["-Werror"])
- # FIXME: Temporary workaround after the Vulkan merge, remove once warnings are fixed.
- if methods.using_gcc(env):
- env.Append(CXXFLAGS=["-Wno-error=cpp"])
- if cc_version_major == 7: # Bogus warning fixed in 8+.
- env.Append(CCFLAGS=["-Wno-error=strict-overflow"])
- if cc_version_major >= 12: # False positives in our error macros, see GH-58747.
- env.Append(CCFLAGS=["-Wno-error=return-type"])
- elif methods.using_clang(env) or methods.using_emcc(env):
- env.Append(CXXFLAGS=["-Wno-error=#warnings"])
if hasattr(detect, "get_program_suffix"):
suffix = "." + detect.get_program_suffix()
diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index 001a351e0b..beef773699 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -153,8 +153,23 @@ const PackedStringArray ProjectSettings::_trim_to_supported_features(const Packe
#endif // TOOLS_ENABLED
String ProjectSettings::localize_path(const String &p_path) const {
- if (resource_path.is_empty() || p_path.begins_with("res://") || p_path.begins_with("user://") ||
- (p_path.is_absolute_path() && !p_path.begins_with(resource_path))) {
+ if (resource_path.is_empty() || (p_path.is_absolute_path() && !p_path.begins_with(resource_path))) {
+ return p_path.simplify_path();
+ }
+
+ // Check if we have a special path (like res://) or a protocol identifier.
+ int p = p_path.find("://");
+ bool found = false;
+ if (p > 0) {
+ found = true;
+ for (int i = 0; i < p; i++) {
+ if (!is_ascii_alphanumeric_char(p_path[i])) {
+ found = false;
+ break;
+ }
+ }
+ }
+ if (found) {
return p_path.simplify_path();
}
diff --git a/core/core_bind.cpp b/core/core_bind.cpp
index 7496ba1979..87b36f7a21 100644
--- a/core/core_bind.cpp
+++ b/core/core_bind.cpp
@@ -334,6 +334,10 @@ String OS::get_version() const {
return ::OS::get_singleton()->get_version();
}
+Vector<String> OS::get_video_adapter_driver_info() const {
+ return ::OS::get_singleton()->get_video_adapter_driver_info();
+}
+
Vector<String> OS::get_cmdline_args() {
List<String> cmdline = ::OS::get_singleton()->get_cmdline_args();
Vector<String> cmdlinev;
@@ -549,6 +553,8 @@ void OS::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_cmdline_args"), &OS::get_cmdline_args);
ClassDB::bind_method(D_METHOD("get_cmdline_user_args"), &OS::get_cmdline_user_args);
+ ClassDB::bind_method(D_METHOD("get_video_adapter_driver_info"), &OS::get_video_adapter_driver_info);
+
ClassDB::bind_method(D_METHOD("set_restart_on_exit", "restart", "arguments"), &OS::set_restart_on_exit, DEFVAL(Vector<String>()));
ClassDB::bind_method(D_METHOD("is_restart_on_exit_set"), &OS::is_restart_on_exit_set);
ClassDB::bind_method(D_METHOD("get_restart_on_exit_arguments"), &OS::get_restart_on_exit_arguments);
@@ -599,8 +605,8 @@ void OS::_bind_methods() {
ADD_PROPERTY_DEFAULT("low_processor_usage_mode", false);
ADD_PROPERTY_DEFAULT("low_processor_usage_mode_sleep_usec", 6900);
- BIND_ENUM_CONSTANT(VIDEO_DRIVER_VULKAN);
- BIND_ENUM_CONSTANT(VIDEO_DRIVER_OPENGL_3);
+ BIND_ENUM_CONSTANT(RENDERING_DRIVER_VULKAN);
+ BIND_ENUM_CONSTANT(RENDERING_DRIVER_OPENGL3);
BIND_ENUM_CONSTANT(DAY_SUNDAY);
BIND_ENUM_CONSTANT(DAY_MONDAY);
diff --git a/core/core_bind.h b/core/core_bind.h
index 9261698076..784f3e63b1 100644
--- a/core/core_bind.h
+++ b/core/core_bind.h
@@ -124,9 +124,9 @@ protected:
static OS *singleton;
public:
- enum VideoDriver {
- VIDEO_DRIVER_VULKAN,
- VIDEO_DRIVER_OPENGL_3,
+ enum RenderingDriver {
+ RENDERING_DRIVER_VULKAN,
+ RENDERING_DRIVER_OPENGL3,
};
enum Weekday {
@@ -196,6 +196,8 @@ public:
Vector<String> get_cmdline_args();
Vector<String> get_cmdline_user_args();
+ Vector<String> get_video_adapter_driver_info() const;
+
String get_locale() const;
String get_locale_language() const;
@@ -576,7 +578,7 @@ VARIANT_ENUM_CAST(core_bind::ResourceLoader::CacheMode);
VARIANT_BITFIELD_CAST(core_bind::ResourceSaver::SaverFlags);
-VARIANT_ENUM_CAST(core_bind::OS::VideoDriver);
+VARIANT_ENUM_CAST(core_bind::OS::RenderingDriver);
VARIANT_ENUM_CAST(core_bind::OS::Weekday);
VARIANT_ENUM_CAST(core_bind::OS::Month);
VARIANT_ENUM_CAST(core_bind::OS::SystemDir);
diff --git a/core/doc_data.h b/core/doc_data.h
index bb356f027e..d5fbe37c96 100644
--- a/core/doc_data.h
+++ b/core/doc_data.h
@@ -57,6 +57,27 @@ public:
}
return name < p_arg.name;
}
+ static ArgumentDoc from_dict(const Dictionary &p_dict) {
+ ArgumentDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("type")) {
+ doc.type = p_dict["type"];
+ }
+
+ if (p_dict.has("enumeration")) {
+ doc.enumeration = p_dict["enumeration"];
+ }
+
+ if (p_dict.has("default_value")) {
+ doc.default_value = p_dict["default_value"];
+ }
+
+ return doc;
+ }
};
struct MethodDoc {
@@ -97,6 +118,55 @@ public:
}
return name < p_method.name;
}
+ static MethodDoc from_dict(const Dictionary &p_dict) {
+ MethodDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("return_type")) {
+ doc.return_type = p_dict["return_type"];
+ }
+
+ if (p_dict.has("return_enum")) {
+ doc.return_enum = p_dict["return_enum"];
+ }
+
+ if (p_dict.has("qualifiers")) {
+ doc.qualifiers = p_dict["qualifiers"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ if (p_dict.has("is_deprecated")) {
+ doc.is_deprecated = p_dict["is_deprecated"];
+ }
+
+ if (p_dict.has("is_experimental")) {
+ doc.is_experimental = p_dict["is_experimental"];
+ }
+
+ Array arguments;
+ if (p_dict.has("arguments")) {
+ arguments = p_dict["arguments"];
+ }
+ for (int i = 0; i < arguments.size(); i++) {
+ doc.arguments.push_back(ArgumentDoc::from_dict(arguments[i]));
+ }
+
+ Array errors_returned;
+ if (p_dict.has("errors_returned")) {
+ errors_returned = p_dict["errors_returned"];
+ }
+ for (int i = 0; i < errors_returned.size(); i++) {
+ doc.errors_returned.push_back(errors_returned[i]);
+ }
+
+ return doc;
+ }
};
struct ConstantDoc {
@@ -111,6 +181,43 @@ public:
bool operator<(const ConstantDoc &p_const) const {
return name < p_const.name;
}
+ static ConstantDoc from_dict(const Dictionary &p_dict) {
+ ConstantDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("value")) {
+ doc.value = p_dict["value"];
+ }
+
+ if (p_dict.has("is_value_valid")) {
+ doc.is_value_valid = p_dict["is_value_valid"];
+ }
+
+ if (p_dict.has("enumeration")) {
+ doc.enumeration = p_dict["enumeration"];
+ }
+
+ if (p_dict.has("is_bitfield")) {
+ doc.is_bitfield = p_dict["is_bitfield"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ if (p_dict.has("is_deprecated")) {
+ doc.is_deprecated = p_dict["is_deprecated"];
+ }
+
+ if (p_dict.has("is_experimental")) {
+ doc.is_experimental = p_dict["is_experimental"];
+ }
+
+ return doc;
+ }
};
struct EnumDoc {
@@ -118,6 +225,31 @@ public:
bool is_bitfield = false;
String description;
Vector<DocData::ConstantDoc> values;
+ static EnumDoc from_dict(const Dictionary &p_dict) {
+ EnumDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("is_bitfield")) {
+ doc.is_bitfield = p_dict["is_bitfield"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ Array values;
+ if (p_dict.has("values")) {
+ values = p_dict["values"];
+ }
+ for (int i = 0; i < values.size(); i++) {
+ doc.values.push_back(ConstantDoc::from_dict(values[i]));
+ }
+
+ return doc;
+ }
};
struct PropertyDoc {
@@ -134,6 +266,55 @@ public:
bool operator<(const PropertyDoc &p_prop) const {
return name < p_prop.name;
}
+ static PropertyDoc from_dict(const Dictionary &p_dict) {
+ PropertyDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("type")) {
+ doc.type = p_dict["type"];
+ }
+
+ if (p_dict.has("enumeration")) {
+ doc.enumeration = p_dict["enumeration"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ if (p_dict.has("setter")) {
+ doc.setter = p_dict["setter"];
+ }
+
+ if (p_dict.has("getter")) {
+ doc.getter = p_dict["getter"];
+ }
+
+ if (p_dict.has("default_value")) {
+ doc.default_value = p_dict["default_value"];
+ }
+
+ if (p_dict.has("overridden")) {
+ doc.overridden = p_dict["overridden"];
+ }
+
+ if (p_dict.has("overrides")) {
+ doc.overrides = p_dict["overrides"];
+ }
+
+ if (p_dict.has("is_deprecated")) {
+ doc.is_deprecated = p_dict["is_deprecated"];
+ }
+
+ if (p_dict.has("is_experimental")) {
+ doc.is_experimental = p_dict["is_experimental"];
+ }
+
+ return doc;
+ }
};
struct ThemeItemDoc {
@@ -149,11 +330,49 @@ public:
}
return data_type < p_theme_item.data_type;
}
+ static ThemeItemDoc from_dict(const Dictionary &p_dict) {
+ ThemeItemDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("type")) {
+ doc.type = p_dict["type"];
+ }
+
+ if (p_dict.has("data_type")) {
+ doc.data_type = p_dict["data_type"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ if (p_dict.has("default_value")) {
+ doc.default_value = p_dict["default_value"];
+ }
+
+ return doc;
+ }
};
struct TutorialDoc {
String link;
String title;
+ static TutorialDoc from_dict(const Dictionary &p_dict) {
+ TutorialDoc doc;
+
+ if (p_dict.has("link")) {
+ doc.link = p_dict["link"];
+ }
+
+ if (p_dict.has("title")) {
+ doc.title = p_dict["title"];
+ }
+
+ return doc;
+ }
};
struct ClassDoc {
@@ -179,6 +398,127 @@ public:
bool operator<(const ClassDoc &p_class) const {
return name < p_class.name;
}
+ static ClassDoc from_dict(const Dictionary &p_dict) {
+ ClassDoc doc;
+
+ if (p_dict.has("name")) {
+ doc.name = p_dict["name"];
+ }
+
+ if (p_dict.has("inherits")) {
+ doc.inherits = p_dict["inherits"];
+ }
+
+ if (p_dict.has("category")) {
+ doc.category = p_dict["category"];
+ }
+
+ if (p_dict.has("brief_description")) {
+ doc.brief_description = p_dict["brief_description"];
+ }
+
+ if (p_dict.has("description")) {
+ doc.description = p_dict["description"];
+ }
+
+ Array tutorials;
+ if (p_dict.has("tutorials")) {
+ tutorials = p_dict["tutorials"];
+ }
+ for (int i = 0; i < tutorials.size(); i++) {
+ doc.tutorials.push_back(TutorialDoc::from_dict(tutorials[i]));
+ }
+
+ Array constructors;
+ if (p_dict.has("constructors")) {
+ constructors = p_dict["constructors"];
+ }
+ for (int i = 0; i < constructors.size(); i++) {
+ doc.constructors.push_back(MethodDoc::from_dict(constructors[i]));
+ }
+
+ Array methods;
+ if (p_dict.has("methods")) {
+ methods = p_dict["methods"];
+ }
+ for (int i = 0; i < methods.size(); i++) {
+ doc.methods.push_back(MethodDoc::from_dict(methods[i]));
+ }
+
+ Array operators;
+ if (p_dict.has("operators")) {
+ operators = p_dict["operators"];
+ }
+ for (int i = 0; i < operators.size(); i++) {
+ doc.operators.push_back(MethodDoc::from_dict(operators[i]));
+ }
+
+ Array signals;
+ if (p_dict.has("signals")) {
+ signals = p_dict["signals"];
+ }
+ for (int i = 0; i < signals.size(); i++) {
+ doc.signals.push_back(MethodDoc::from_dict(signals[i]));
+ }
+
+ Array constants;
+ if (p_dict.has("constants")) {
+ constants = p_dict["constants"];
+ }
+ for (int i = 0; i < constants.size(); i++) {
+ doc.constants.push_back(ConstantDoc::from_dict(constants[i]));
+ }
+
+ Dictionary enums;
+ if (p_dict.has("enums")) {
+ enums = p_dict["enums"];
+ }
+ for (int i = 0; i < enums.size(); i++) {
+ doc.enums[enums.get_key_at_index(i)] = enums.get_value_at_index(i);
+ }
+
+ Array properties;
+ if (p_dict.has("properties")) {
+ properties = p_dict["properties"];
+ }
+ for (int i = 0; i < properties.size(); i++) {
+ doc.properties.push_back(PropertyDoc::from_dict(properties[i]));
+ }
+
+ Array annotations;
+ if (p_dict.has("annotations")) {
+ annotations = p_dict["annotations"];
+ }
+ for (int i = 0; i < annotations.size(); i++) {
+ doc.annotations.push_back(MethodDoc::from_dict(annotations[i]));
+ }
+
+ Array theme_properties;
+ if (p_dict.has("theme_properties")) {
+ theme_properties = p_dict["theme_properties"];
+ }
+ for (int i = 0; i < theme_properties.size(); i++) {
+ doc.theme_properties.push_back(ThemeItemDoc::from_dict(theme_properties[i]));
+ }
+
+ if (p_dict.has("is_deprecated")) {
+ doc.is_deprecated = p_dict["is_deprecated"];
+ }
+
+ if (p_dict.has("is_experimental")) {
+ doc.is_experimental = p_dict["is_experimental"];
+ }
+
+ if (p_dict.has("is_script_doc")) {
+ doc.is_script_doc = p_dict["is_script_doc"];
+ }
+
+ if (p_dict.has("script_path")) {
+ doc.script_path = p_dict["script_path"];
+ }
+
+ return doc;
+ }
};
static void return_doc_from_retinfo(DocData::MethodDoc &p_method, const PropertyInfo &p_retinfo);
diff --git a/core/extension/extension_api_dump.cpp b/core/extension/extension_api_dump.cpp
index e6e0fff266..96b396caa9 100644
--- a/core/extension/extension_api_dump.cpp
+++ b/core/extension/extension_api_dump.cpp
@@ -38,7 +38,15 @@
#ifdef TOOLS_ENABLED
-static String get_type_name(const PropertyInfo &p_info) {
+static String get_builtin_or_variant_type_name(const Variant::Type p_type) {
+ if (p_type == Variant::NIL) {
+ return "Variant";
+ } else {
+ return Variant::get_type_name(p_type);
+ }
+}
+
+static String get_property_info_type_name(const PropertyInfo &p_info) {
if (p_info.type == Variant::INT && (p_info.hint == PROPERTY_HINT_INT_IS_POINTER)) {
if (p_info.hint_string.is_empty()) {
return "void*";
@@ -70,7 +78,7 @@ static String get_type_name(const PropertyInfo &p_info) {
if (p_info.type == Variant::NIL) {
return "void";
}
- return Variant::get_type_name(p_info.type);
+ return get_builtin_or_variant_type_name(p_info.type);
}
Dictionary NativeExtensionAPIDump::generate_extension_api() {
@@ -430,8 +438,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
Dictionary arg;
String argname = vararg ? "arg" + itos(i + 1) : Variant::get_utility_function_argument_name(name, i);
arg["name"] = argname;
- Variant::Type argtype = Variant::get_utility_function_argument_type(name, i);
- arg["type"] = argtype == Variant::NIL ? String("Variant") : Variant::get_type_name(argtype);
+ arg["type"] = get_builtin_or_variant_type_name(Variant::get_utility_function_argument_type(name, i));
//no default value support in utility functions
arguments.push_back(arg);
}
@@ -461,8 +468,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
Dictionary d;
d["name"] = Variant::get_type_name(type);
if (Variant::has_indexing(type)) {
- Variant::Type index_type = Variant::get_indexed_element_type(type);
- d["indexing_return_type"] = index_type == Variant::NIL ? String("Variant") : Variant::get_type_name(index_type);
+ d["indexing_return_type"] = get_builtin_or_variant_type_name(Variant::get_indexed_element_type(type));
}
d["is_keyed"] = Variant::is_keyed(type);
@@ -476,7 +482,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
for (const StringName &member_name : member_names) {
Dictionary d2;
d2["name"] = String(member_name);
- d2["type"] = Variant::get_type_name(Variant::get_member_type(type, member_name));
+ d2["type"] = get_builtin_or_variant_type_name(Variant::get_member_type(type, member_name));
members.push_back(d2);
}
if (members.size()) {
@@ -493,7 +499,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
Dictionary d2;
d2["name"] = String(constant_name);
Variant constant = Variant::get_constant_value(type, constant_name);
- d2["type"] = Variant::get_type_name(constant.get_type());
+ d2["type"] = get_builtin_or_variant_type_name(constant.get_type());
d2["value"] = constant.get_construct_string();
constants.push_back(d2);
}
@@ -544,9 +550,9 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
Dictionary d2;
d2["name"] = Variant::get_operator_name(Variant::Operator(k));
if (k != Variant::OP_NEGATE && k != Variant::OP_POSITIVE && k != Variant::OP_NOT && k != Variant::OP_BIT_NEGATE) {
- d2["right_type"] = Variant::get_type_name(Variant::Type(j));
+ d2["right_type"] = get_builtin_or_variant_type_name(Variant::Type(j));
}
- d2["return_type"] = Variant::get_type_name(Variant::get_operator_return_type(Variant::Operator(k), type, Variant::Type(j)));
+ d2["return_type"] = get_builtin_or_variant_type_name(Variant::get_operator_return_type(Variant::Operator(k), type, Variant::Type(j)));
operators.push_back(d2);
}
}
@@ -580,8 +586,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
for (int j = 0; j < argcount; j++) {
Dictionary d3;
d3["name"] = Variant::get_builtin_method_argument_name(type, method_name, j);
- Variant::Type argtype = Variant::get_builtin_method_argument_type(type, method_name, j);
- d3["type"] = argtype == Variant::NIL ? String("Variant") : Variant::get_type_name(argtype);
+ d3["type"] = get_builtin_or_variant_type_name(Variant::get_builtin_method_argument_type(type, method_name, j));
if (j >= (argcount - default_args.size())) {
int dargidx = j - (argcount - default_args.size());
@@ -613,7 +618,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
for (int k = 0; k < argcount; k++) {
Dictionary d3;
d3["name"] = Variant::get_constructor_argument_name(type, j, k);
- d3["type"] = Variant::get_type_name(Variant::get_constructor_argument_type(type, j, k));
+ d3["type"] = get_builtin_or_variant_type_name(Variant::get_constructor_argument_type(type, j, k));
arguments.push_back(d3);
}
if (arguments.size()) {
@@ -741,7 +746,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
d3["name"] = pinfo.name;
}
- d3["type"] = get_type_name(pinfo);
+ d3["type"] = get_property_info_type_name(pinfo);
if (i == -1) {
d2["return_value"] = d3;
@@ -784,7 +789,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
if (i >= 0) {
d3["name"] = pinfo.name;
}
- d3["type"] = get_type_name(pinfo);
+ d3["type"] = get_property_info_type_name(pinfo);
if (method->get_argument_meta(i) > 0) {
static const char *argmeta[11] = { "none", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "float", "double" };
@@ -831,7 +836,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
for (int i = 0; i < F.arguments.size(); i++) {
Dictionary d3;
d3["name"] = F.arguments[i].name;
- d3["type"] = get_type_name(F.arguments[i]);
+ d3["type"] = get_property_info_type_name(F.arguments[i]);
arguments.push_back(d3);
}
if (arguments.size()) {
@@ -863,7 +868,7 @@ Dictionary NativeExtensionAPIDump::generate_extension_api() {
}
StringName property_name = F.name;
Dictionary d2;
- d2["type"] = get_type_name(F);
+ d2["type"] = get_property_info_type_name(F);
d2["name"] = String(property_name);
d2["setter"] = ClassDB::get_property_setter(class_name, F.name);
d2["getter"] = ClassDB::get_property_getter(class_name, F.name);
diff --git a/core/extension/gdnative_interface.h b/core/extension/gdnative_interface.h
index 39378d8261..1ce50bc186 100644
--- a/core/extension/gdnative_interface.h
+++ b/core/extension/gdnative_interface.h
@@ -201,18 +201,18 @@ typedef GDNativeBool (*GDNativeExtensionClassGet)(GDExtensionClassInstancePtr p_
typedef uint64_t (*GDNativeExtensionClassGetRID)(GDExtensionClassInstancePtr p_instance);
typedef struct {
- uint32_t type;
+ GDNativeVariantType type;
const char *name;
const char *class_name;
- uint32_t hint;
+ uint32_t hint; // Bitfield of `PropertyHint` (defined in `extension_api.json`)
const char *hint_string;
- uint32_t usage;
+ uint32_t usage; // Bitfield of `PropertyUsageFlags` (defined in `extension_api.json`)
} GDNativePropertyInfo;
typedef struct {
const char *name;
GDNativePropertyInfo return_value;
- uint32_t flags; // From GDNativeExtensionClassMethodFlags
+ uint32_t flags; // Bitfield of `GDNativeExtensionClassMethodFlags`
int32_t id;
GDNativePropertyInfo *arguments;
uint32_t argument_count;
@@ -231,10 +231,11 @@ typedef void (*GDNativeExtensionClassUnreference)(GDExtensionClassInstancePtr p_
typedef void (*GDNativeExtensionClassCallVirtual)(GDExtensionClassInstancePtr p_instance, const GDNativeTypePtr *p_args, GDNativeTypePtr r_ret);
typedef GDNativeObjectPtr (*GDNativeExtensionClassCreateInstance)(void *p_userdata);
typedef void (*GDNativeExtensionClassFreeInstance)(void *p_userdata, GDExtensionClassInstancePtr p_instance);
-typedef void (*GDNativeExtensionClassObjectInstance)(GDExtensionClassInstancePtr p_instance, GDNativeObjectPtr p_object_instance);
typedef GDNativeExtensionClassCallVirtual (*GDNativeExtensionClassGetVirtual)(void *p_userdata, const char *p_name);
typedef struct {
+ GDNativeBool is_virtual;
+ GDNativeBool is_abstract;
GDNativeExtensionClassSet set_func;
GDNativeExtensionClassGet get_func;
GDNativeExtensionClassGetPropertyList get_property_list_func;
@@ -293,7 +294,7 @@ typedef struct {
void *method_userdata;
GDNativeExtensionClassMethodCall call_func;
GDNativeExtensionClassMethodPtrCall ptrcall_func;
- uint32_t method_flags; /* GDNativeExtensionClassMethodFlags */
+ uint32_t method_flags; // Bitfield of `GDNativeExtensionClassMethodFlags`
uint32_t argument_count;
GDNativeBool has_return_value;
GDNativeExtensionClassMethodGetArgumentType get_argument_type_func;
diff --git a/core/extension/native_extension.cpp b/core/extension/native_extension.cpp
index 6418da2235..cc019584a5 100644
--- a/core/extension/native_extension.cpp
+++ b/core/extension/native_extension.cpp
@@ -152,6 +152,8 @@ void NativeExtension::_register_extension_class(const GDNativeExtensionClassLibr
extension->native_extension.parent_class_name = parent_class_name;
extension->native_extension.class_name = class_name;
extension->native_extension.editor_class = self->level_initialized == INITIALIZATION_LEVEL_EDITOR;
+ extension->native_extension.is_virtual = p_extension_funcs->is_virtual;
+ extension->native_extension.is_abstract = p_extension_funcs->is_abstract;
extension->native_extension.set = p_extension_funcs->set_func;
extension->native_extension.get = p_extension_funcs->get_func;
extension->native_extension.get_property_list = p_extension_funcs->get_property_list_func;
diff --git a/core/input/input.cpp b/core/input/input.cpp
index 889c2a92fa..1321e40795 100644
--- a/core/input/input.cpp
+++ b/core/input/input.cpp
@@ -519,6 +519,7 @@ void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_em
touch_event.instantiate();
touch_event->set_pressed(mb->is_pressed());
touch_event->set_position(mb->get_position());
+ touch_event->set_double_tap(mb->is_double_click());
event_dispatch_function(touch_event);
}
}
@@ -580,6 +581,7 @@ void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_em
button_event->set_global_position(st->get_position());
button_event->set_pressed(st->is_pressed());
button_event->set_button_index(MouseButton::LEFT);
+ button_event->set_double_click(st->is_double_tap());
if (st->is_pressed()) {
button_event->set_button_mask(MouseButton(mouse_button_mask | MouseButton::MASK_LEFT));
} else {
diff --git a/core/input/input_event.cpp b/core/input/input_event.cpp
index 38037eaf72..9dc071de9c 100644
--- a/core/input/input_event.cpp
+++ b/core/input/input_event.cpp
@@ -1162,6 +1162,13 @@ bool InputEventScreenTouch::is_pressed() const {
return pressed;
}
+void InputEventScreenTouch::set_double_tap(bool p_double_tap) {
+ double_tap = p_double_tap;
+}
+bool InputEventScreenTouch::is_double_tap() const {
+ return double_tap;
+}
+
Ref<InputEvent> InputEventScreenTouch::xformed_by(const Transform2D &p_xform, const Vector2 &p_local_ofs) const {
Ref<InputEventScreenTouch> st;
st.instantiate();
@@ -1170,6 +1177,7 @@ Ref<InputEvent> InputEventScreenTouch::xformed_by(const Transform2D &p_xform, co
st->set_index(index);
st->set_position(p_xform.xform(pos + p_local_ofs));
st->set_pressed(pressed);
+ st->set_double_tap(double_tap);
return st;
}
@@ -1182,7 +1190,8 @@ String InputEventScreenTouch::as_text() const {
String InputEventScreenTouch::to_string() {
String p = pressed ? "true" : "false";
- return vformat("InputEventScreenTouch: index=%d, pressed=%s, position=(%s)", index, p, String(get_position()));
+ String double_tap_string = double_tap ? "true" : "false";
+ return vformat("InputEventScreenTouch: index=%d, pressed=%s, position=(%s), double_tap=%s", index, p, String(get_position()), double_tap_string);
}
void InputEventScreenTouch::_bind_methods() {
@@ -1195,9 +1204,13 @@ void InputEventScreenTouch::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &InputEventScreenTouch::set_pressed);
//ClassDB::bind_method(D_METHOD("is_pressed"),&InputEventScreenTouch::is_pressed);
+ ClassDB::bind_method(D_METHOD("set_double_tap", "double_tap"), &InputEventScreenTouch::set_double_tap);
+ ClassDB::bind_method(D_METHOD("is_double_tap"), &InputEventScreenTouch::is_double_tap);
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "index"), "set_index", "get_index");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "position", PROPERTY_HINT_NONE, "suffix:px"), "set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "pressed"), "set_pressed", "is_pressed");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "double_tap"), "set_double_tap", "is_double_tap");
}
///////////////////////////////////
diff --git a/core/input/input_event.h b/core/input/input_event.h
index bc3ec3e7ac..adbcb7cf68 100644
--- a/core/input/input_event.h
+++ b/core/input/input_event.h
@@ -353,6 +353,7 @@ class InputEventScreenTouch : public InputEventFromWindow {
int index = 0;
Vector2 pos;
bool pressed = false;
+ bool double_tap = false;
protected:
static void _bind_methods();
@@ -367,6 +368,9 @@ public:
void set_pressed(bool p_pressed);
virtual bool is_pressed() const override;
+ void set_double_tap(bool p_double_tap);
+ bool is_double_tap() const;
+
virtual Ref<InputEvent> xformed_by(const Transform2D &p_xform, const Vector2 &p_local_ofs = Vector2()) const override;
virtual String as_text() const override;
virtual String to_string() override;
diff --git a/core/input/input_map.cpp b/core/input/input_map.cpp
index ce76d11b6e..0c765fe23c 100644
--- a/core/input/input_map.cpp
+++ b/core/input/input_map.cpp
@@ -337,6 +337,7 @@ static const _BuiltinActionDisplayName _builtin_action_display_names[] = {
{ "ui_text_scroll_down.macos", TTRC("Scroll Down") },
{ "ui_text_select_all", TTRC("Select All") },
{ "ui_text_select_word_under_caret", TTRC("Select Word Under Caret") },
+ { "ui_text_add_selection_for_next_occurrence", TTRC("Add Selection for Next Occurrence") },
{ "ui_text_toggle_insert_mode", TTRC("Toggle Insert Mode") },
{ "ui_text_submit", TTRC("Text Submitted") },
{ "ui_graph_duplicate", TTRC("Duplicate Nodes") },
@@ -641,10 +642,14 @@ const HashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
default_builtin_cache.insert("ui_text_select_all", inputs);
inputs = List<Ref<InputEvent>>();
- inputs.push_back(InputEventKey::create_reference(Key::D | KeyModifierMask::CMD_OR_CTRL));
+ inputs.push_back(InputEventKey::create_reference(Key::G | KeyModifierMask::ALT));
default_builtin_cache.insert("ui_text_select_word_under_caret", inputs);
inputs = List<Ref<InputEvent>>();
+ inputs.push_back(InputEventKey::create_reference(Key::D | KeyModifierMask::CMD_OR_CTRL));
+ default_builtin_cache.insert("ui_text_add_selection_for_next_occurrence", inputs);
+
+ inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(Key::INSERT));
default_builtin_cache.insert("ui_text_toggle_insert_mode", inputs);
diff --git a/core/io/image.cpp b/core/io/image.cpp
index 4be624a5a8..16dd66fc98 100644
--- a/core/io/image.cpp
+++ b/core/io/image.cpp
@@ -982,7 +982,7 @@ void Image::resize_to_po2(bool p_square, Interpolation p_interpolation) {
}
void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
- ERR_FAIL_COND_MSG(data.size() == 0, "Cannot resize image before creating it, use create() or create_from_data() first.");
+ ERR_FAIL_COND_MSG(data.size() == 0, "Cannot resize image before creating it, use set_data() first.");
ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */;
@@ -1017,7 +1017,7 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
}
bool interpolate_mipmaps = mipmap_aware && mip1 != mip2;
if (interpolate_mipmaps) {
- dst2.create(p_width, p_height, false, format);
+ dst2.initialize_data(p_width, p_height, false, format);
}
bool had_mipmaps = mipmaps;
@@ -2016,9 +2016,7 @@ Error Image::generate_mipmap_roughness(RoughnessChannel p_roughness_channel, con
uint8_t* wr = imgdata.ptrw();
memcpy(wr.ptr(), ptr, size);
wr = uint8_t*();
- Ref<Image> im;
- im.instantiate();
- im->create(w, h, false, format, imgdata);
+ Ref<Image> im = Image::create_from_data(w, h, false, format, imgdata);
im->save_png("res://mipmap_" + itos(i) + ".png");
}
#endif
@@ -2051,7 +2049,25 @@ Vector<uint8_t> Image::get_data() const {
return data;
}
-void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
+Ref<Image> Image::create_empty(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
+ Ref<Image> image;
+ image.instantiate();
+ image->initialize_data(p_width, p_height, p_use_mipmaps, p_format);
+ return image;
+}
+
+Ref<Image> Image::create_from_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
+ Ref<Image> image;
+ image.instantiate();
+ image->initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
+ return image;
+}
+
+void Image::set_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
+ initialize_data(p_width, p_height, p_use_mipmaps, p_format, p_data);
+}
+
+void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
ERR_FAIL_COND_MSG(p_width <= 0, "The Image width specified (" + itos(p_width) + " pixels) must be greater than 0 pixels.");
ERR_FAIL_COND_MSG(p_height <= 0, "The Image height specified (" + itos(p_height) + " pixels) must be greater than 0 pixels.");
ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
@@ -2077,7 +2093,7 @@ void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_forma
format = p_format;
}
-void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
+void Image::initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
ERR_FAIL_COND_MSG(p_width <= 0, "The Image width specified (" + itos(p_width) + " pixels) must be greater than 0 pixels.");
ERR_FAIL_COND_MSG(p_height <= 0, "The Image height specified (" + itos(p_height) + " pixels) must be greater than 0 pixels.");
ERR_FAIL_COND_MSG(p_width > MAX_WIDTH,
@@ -2115,7 +2131,7 @@ void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_forma
mipmaps = p_use_mipmaps;
}
-void Image::create(const char **p_xpm) {
+void Image::initialize_data(const char **p_xpm) {
int size_width = 0;
int size_height = 0;
int pixelchars = 0;
@@ -2230,7 +2246,7 @@ void Image::create(const char **p_xpm) {
}
if (line == colormap_size) {
status = READING_PIXELS;
- create(size_width, size_height, false, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
+ initialize_data(size_width, size_height, false, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
data_write = data.ptrw();
pixel_size = has_alpha ? 4 : 3;
}
@@ -2559,7 +2575,7 @@ Image::Image(const char **p_xpm) {
mipmaps = false;
format = FORMAT_L8;
- create(p_xpm);
+ initialize_data(p_xpm);
}
Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
@@ -2568,7 +2584,7 @@ Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
mipmaps = p_use_mipmaps;
format = FORMAT_L8;
- create(p_width, p_height, p_use_mipmaps, p_format);
+ initialize_data(p_width, p_height, p_use_mipmaps, p_format);
}
Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
@@ -2577,7 +2593,7 @@ Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const V
mipmaps = p_mipmaps;
format = FORMAT_L8;
- create(p_width, p_height, p_mipmaps, p_format, p_data);
+ initialize_data(p_width, p_height, p_mipmaps, p_format, p_data);
}
Rect2i Image::get_used_rect() const {
@@ -2846,6 +2862,9 @@ void Image::_repeat_pixel_over_subsequent_memory(uint8_t *p_pixel, int p_pixel_s
}
void Image::fill(const Color &p_color) {
+ if (data.size() == 0) {
+ return;
+ }
ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill in compressed or custom image formats.");
uint8_t *dst_data_ptr = data.ptrw();
@@ -2859,6 +2878,9 @@ void Image::fill(const Color &p_color) {
}
void Image::fill_rect(const Rect2i &p_rect, const Color &p_color) {
+ if (data.size() == 0) {
+ return;
+ }
ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill rect in compressed or custom image formats.");
Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect.abs());
@@ -2931,7 +2953,7 @@ void Image::_set_data(const Dictionary &p_data) {
ERR_FAIL_COND(ddformat == FORMAT_MAX);
- create(dwidth, dheight, dmipmaps, ddformat, ddata);
+ initialize_data(dwidth, dheight, dmipmaps, ddformat, ddata);
}
Dictionary Image::_get_data() const {
@@ -3294,8 +3316,9 @@ void Image::_bind_methods() {
ClassDB::bind_method(D_METHOD("generate_mipmaps", "renormalize"), &Image::generate_mipmaps, DEFVAL(false));
ClassDB::bind_method(D_METHOD("clear_mipmaps"), &Image::clear_mipmaps);
- ClassDB::bind_method(D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
- ClassDB::bind_method(D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
+ ClassDB::bind_static_method("Image", D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
+ ClassDB::bind_static_method("Image", D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
+ ClassDB::bind_method(D_METHOD("set_data", "width", "height", "use_mipmaps", "format", "data"), &Image::set_data);
ClassDB::bind_method(D_METHOD("is_empty"), &Image::is_empty);
@@ -3460,9 +3483,7 @@ Ref<Image> Image::rgbe_to_srgb() {
ERR_FAIL_COND_V(format != FORMAT_RGBE9995, Ref<Image>());
- Ref<Image> new_image;
- new_image.instantiate();
- new_image->create(width, height, false, Image::FORMAT_RGB8);
+ Ref<Image> new_image = create_empty(width, height, false, Image::FORMAT_RGB8);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
diff --git a/core/io/image.h b/core/io/image.h
index fd264a7a38..194ee05bc7 100644
--- a/core/io/image.h
+++ b/core/io/image.h
@@ -279,12 +279,12 @@ public:
void normalize(); //for normal maps
/**
- * Create a new image of a given size and format. Current image will be lost
+ * Creates new internal image data of a given size and format. Current image will be lost.
*/
- void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format);
- void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data);
+ void initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format);
+ void initialize_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data);
+ void initialize_data(const char **p_xpm);
- void create(const char **p_xpm);
/**
* returns true when the image is empty (0,0) in size
*/
@@ -303,13 +303,9 @@ public:
Error save_webp(const String &p_path, const bool p_lossy = false, const float p_quality = 0.75f) const;
Vector<uint8_t> save_webp_to_buffer(const bool p_lossy = false, const float p_quality = 0.75f) const;
- void create_empty(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
- create(p_width, p_height, p_use_mipmaps, p_format);
- }
-
- void create_from_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
- create(p_width, p_height, p_use_mipmaps, p_format, p_data);
- }
+ static Ref<Image> create_empty(int p_width, int p_height, bool p_use_mipmaps, Format p_format);
+ static Ref<Image> create_from_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data);
+ void set_data(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data);
/**
* create an empty image
diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp
index 2a79067e02..4611528db7 100644
--- a/core/io/resource_format_binary.cpp
+++ b/core/io/resource_format_binary.cpp
@@ -1042,7 +1042,14 @@ void ResourceLoaderBinary::open(Ref<FileAccess> p_f, bool p_no_resources, bool p
// If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
er.path = ResourceUID::get_singleton()->get_id_path(er.uid);
} else {
+#ifdef TOOLS_ENABLED
+ // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
+ if (ResourceLoader::get_resource_uid(res_path) != er.uid) {
+ WARN_PRINT(String(res_path + ": In external resource #" + itos(i) + ", invalid UUID: " + ResourceUID::get_singleton()->id_to_text(er.uid) + " - using text path instead: " + er.path).utf8().get_data());
+ }
+#else
WARN_PRINT(String(res_path + ": In external resource #" + itos(i) + ", invalid UUID: " + ResourceUID::get_singleton()->id_to_text(er.uid) + " - using text path instead: " + er.path).utf8().get_data());
+#endif
}
}
}
diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp
index a018221b7f..2fb357b520 100644
--- a/core/io/resource_loader.cpp
+++ b/core/io/resource_loader.cpp
@@ -49,6 +49,11 @@ Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
int ResourceLoader::loader_count = 0;
bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
+ bool ret = false;
+ if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
+ return ret;
+ }
+
String extension = p_path.get_extension();
List<String> extensions;
@@ -189,6 +194,7 @@ void ResourceFormatLoader::_bind_methods() {
BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
GDVIRTUAL_BIND(_get_recognized_extensions);
+ GDVIRTUAL_BIND(_recognize_path, "path", "type");
GDVIRTUAL_BIND(_handles_type, "type");
GDVIRTUAL_BIND(_get_resource_type, "path");
GDVIRTUAL_BIND(_get_resource_uid, "path");
diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h
index 91ba930176..243670b2d0 100644
--- a/core/io/resource_loader.h
+++ b/core/io/resource_loader.h
@@ -51,6 +51,7 @@ protected:
static void _bind_methods();
GDVIRTUAL0RC(Vector<String>, _get_recognized_extensions)
+ GDVIRTUAL2RC(bool, _recognize_path, String, StringName)
GDVIRTUAL1RC(bool, _handles_type, StringName)
GDVIRTUAL1RC(String, _get_resource_type, String)
GDVIRTUAL1RC(ResourceUID::ID, _get_resource_uid, String)
diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp
index 2f863baaac..6cda840604 100644
--- a/core/io/resource_saver.cpp
+++ b/core/io/resource_saver.cpp
@@ -69,10 +69,31 @@ void ResourceFormatSaver::get_recognized_extensions(const Ref<Resource> &p_resou
}
}
+bool ResourceFormatSaver::recognize_path(const Ref<Resource> &p_resource, const String &p_path) const {
+ bool ret = false;
+ if (GDVIRTUAL_CALL(_recognize_path, p_resource, p_path, ret)) {
+ return ret;
+ }
+
+ String extension = p_path.get_extension();
+
+ List<String> extensions;
+ get_recognized_extensions(p_resource, &extensions);
+
+ for (const String &E : extensions) {
+ if (E.nocasecmp_to(extension) == 0) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
void ResourceFormatSaver::_bind_methods() {
GDVIRTUAL_BIND(_save, "resource", "path", "flags");
GDVIRTUAL_BIND(_recognize, "resource");
GDVIRTUAL_BIND(_get_recognized_extensions, "resource");
+ GDVIRTUAL_BIND(_recognize_path, "resource", "path");
}
Error ResourceSaver::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
@@ -90,17 +111,7 @@ Error ResourceSaver::save(const Ref<Resource> &p_resource, const String &p_path,
continue;
}
- List<String> extensions;
- bool recognized = false;
- saver[i]->get_recognized_extensions(p_resource, &extensions);
-
- for (const String &E : extensions) {
- if (E.nocasecmp_to(extension) == 0) {
- recognized = true;
- }
- }
-
- if (!recognized) {
+ if (!saver[i]->recognize_path(p_resource, path)) {
continue;
}
diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h
index 4fee2bcfd1..5e48ce88c3 100644
--- a/core/io/resource_saver.h
+++ b/core/io/resource_saver.h
@@ -44,11 +44,13 @@ protected:
GDVIRTUAL3R(int64_t, _save, Ref<Resource>, String, uint32_t)
GDVIRTUAL1RC(bool, _recognize, Ref<Resource>)
GDVIRTUAL1RC(Vector<String>, _get_recognized_extensions, Ref<Resource>)
+ GDVIRTUAL2RC(bool, _recognize_path, Ref<Resource>, String)
public:
virtual Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0);
virtual bool recognize(const Ref<Resource> &p_resource) const;
virtual void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const;
+ virtual bool recognize_path(const Ref<Resource> &p_resource, const String &p_path) const;
virtual ~ResourceFormatSaver() {}
};
diff --git a/core/io/zip_io.cpp b/core/io/zip_io.cpp
index e573e8de19..200e5f5e83 100644
--- a/core/io/zip_io.cpp
+++ b/core/io/zip_io.cpp
@@ -37,11 +37,17 @@ void *zipio_open(voidpf opaque, const char *p_fname, int mode) {
String fname;
fname.parse_utf8(p_fname);
+ int file_access_mode = 0;
if (mode & ZLIB_FILEFUNC_MODE_WRITE) {
- (*fa) = FileAccess::open(fname, FileAccess::WRITE);
- } else {
- (*fa) = FileAccess::open(fname, FileAccess::READ);
+ file_access_mode |= FileAccess::WRITE;
}
+ if (mode & ZLIB_FILEFUNC_MODE_READ) {
+ file_access_mode |= FileAccess::READ;
+ }
+ if (mode & ZLIB_FILEFUNC_MODE_CREATE) {
+ file_access_mode |= FileAccess::WRITE_READ;
+ }
+ (*fa) = FileAccess::open(fname, file_access_mode);
if (fa->is_null()) {
return nullptr;
diff --git a/core/math/aabb.cpp b/core/math/aabb.cpp
index 026f179445..fcf245d2ad 100644
--- a/core/math/aabb.cpp
+++ b/core/math/aabb.cpp
@@ -76,6 +76,10 @@ bool AABB::is_equal_approx(const AABB &p_aabb) const {
return position.is_equal_approx(p_aabb.position) && size.is_equal_approx(p_aabb.size);
}
+bool AABB::is_finite() const {
+ return position.is_finite() && size.is_finite();
+}
+
AABB AABB::intersection(const AABB &p_aabb) const {
#ifdef MATH_CHECKS
if (unlikely(size.x < 0 || size.y < 0 || size.z < 0 || p_aabb.size.x < 0 || p_aabb.size.y < 0 || p_aabb.size.z < 0)) {
diff --git a/core/math/aabb.h b/core/math/aabb.h
index b9f777c6cf..9d5837ad37 100644
--- a/core/math/aabb.h
+++ b/core/math/aabb.h
@@ -63,6 +63,7 @@ struct _NO_DISCARD_ AABB {
bool operator!=(const AABB &p_rval) const;
bool is_equal_approx(const AABB &p_aabb) const;
+ bool is_finite() const;
_FORCE_INLINE_ bool intersects(const AABB &p_aabb) const; /// Both AABBs overlap
_FORCE_INLINE_ bool intersects_inclusive(const AABB &p_aabb) const; /// Both AABBs (or their faces) overlap
_FORCE_INLINE_ bool encloses(const AABB &p_aabb) const; /// p_aabb is completely inside this
diff --git a/core/math/basis.cpp b/core/math/basis.cpp
index 845686f339..9b8188eed8 100644
--- a/core/math/basis.cpp
+++ b/core/math/basis.cpp
@@ -691,6 +691,10 @@ bool Basis::is_equal_approx(const Basis &p_basis) const {
return rows[0].is_equal_approx(p_basis.rows[0]) && rows[1].is_equal_approx(p_basis.rows[1]) && rows[2].is_equal_approx(p_basis.rows[2]);
}
+bool Basis::is_finite() const {
+ return rows[0].is_finite() && rows[1].is_finite() && rows[2].is_finite();
+}
+
bool Basis::operator==(const Basis &p_matrix) const {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
diff --git a/core/math/basis.h b/core/math/basis.h
index cc2924f5ff..69bef5a7be 100644
--- a/core/math/basis.h
+++ b/core/math/basis.h
@@ -134,6 +134,7 @@ struct _NO_DISCARD_ Basis {
}
bool is_equal_approx(const Basis &p_basis) const;
+ bool is_finite() const;
bool operator==(const Basis &p_matrix) const;
bool operator!=(const Basis &p_matrix) const;
diff --git a/core/math/convex_hull.cpp b/core/math/convex_hull.cpp
index 996f4f4d67..561970d2ee 100644
--- a/core/math/convex_hull.cpp
+++ b/core/math/convex_hull.cpp
@@ -62,6 +62,7 @@ subject to the following restrictions:
#include "core/math/aabb.h"
#include "core/math/math_defs.h"
#include "core/os/memory.h"
+#include "core/templates/oa_hash_map.h"
#include "core/templates/paged_allocator.h"
#include <string.h>
@@ -2252,19 +2253,62 @@ Error ConvexHullComputer::convex_hull(const Vector<Vector3> &p_points, Geometry3
r_mesh.vertices = ch.vertices;
+ // Tag which face each edge belongs to
+ LocalVector<int32_t> edge_faces;
+ edge_faces.resize(ch.edges.size());
+
+ for (uint32_t i = 0; i < ch.edges.size(); i++) {
+ edge_faces[i] = -1;
+ }
+
+ for (uint32_t i = 0; i < ch.faces.size(); i++) {
+ const Edge *e_start = &ch.edges[ch.faces[i]];
+ const Edge *e = e_start;
+ do {
+ int64_t ofs = e - ch.edges.ptr();
+ edge_faces[ofs] = i;
+
+ e = e->get_next_edge_of_face();
+ } while (e != e_start);
+ }
+
// Copy the edges over. There's two "half-edges" for every edge, so we pick only one of them.
r_mesh.edges.resize(ch.edges.size() / 2);
+ OAHashMap<uint64_t, int32_t> edge_map;
+ edge_map.reserve(ch.edges.size() * 4); // The higher the capacity, the faster the insert
+
uint32_t edges_copied = 0;
for (uint32_t i = 0; i < ch.edges.size(); i++) {
+ ERR_CONTINUE(edge_faces[i] == -1); // Sanity check
+
uint32_t a = (&ch.edges[i])->get_source_vertex();
uint32_t b = (&ch.edges[i])->get_target_vertex();
if (a < b) { // Copy only the "canonical" edge. For the reverse edge, this will be false.
ERR_BREAK(edges_copied >= (uint32_t)r_mesh.edges.size());
- r_mesh.edges.write[edges_copied].a = a;
- r_mesh.edges.write[edges_copied].b = b;
+ r_mesh.edges[edges_copied].vertex_a = a;
+ r_mesh.edges[edges_copied].vertex_b = b;
+ r_mesh.edges[edges_copied].face_a = edge_faces[i];
+ r_mesh.edges[edges_copied].face_b = -1;
+
+ uint64_t key = a;
+ key <<= 32;
+ key |= b;
+ edge_map.insert(key, edges_copied);
+
edges_copied++;
+ } else {
+ uint64_t key = b;
+ key <<= 32;
+ key |= a;
+ int32_t index;
+ if (!edge_map.lookup(key, index)) {
+ ERR_PRINT("Invalid edge");
+ } else {
+ r_mesh.edges[index].face_b = edge_faces[i];
+ }
}
}
+
if (edges_copied != (uint32_t)r_mesh.edges.size()) {
ERR_PRINT("Invalid edge count.");
}
@@ -2273,7 +2317,7 @@ Error ConvexHullComputer::convex_hull(const Vector<Vector3> &p_points, Geometry3
for (uint32_t i = 0; i < ch.faces.size(); i++) {
const Edge *e_start = &ch.edges[ch.faces[i]];
const Edge *e = e_start;
- Geometry3D::MeshData::Face &face = r_mesh.faces.write[i];
+ Geometry3D::MeshData::Face &face = r_mesh.faces[i];
do {
face.indices.push_back(e->get_target_vertex());
@@ -2284,8 +2328,8 @@ Error ConvexHullComputer::convex_hull(const Vector<Vector3> &p_points, Geometry3
// reverse indices: Godot wants clockwise, but this is counter-clockwise
if (face.indices.size() > 2) {
// reverse all but the first index.
- int *indices = face.indices.ptrw();
- for (int c = 0; c < (face.indices.size() - 1) / 2; c++) {
+ int *indices = face.indices.ptr();
+ for (uint32_t c = 0; c < (face.indices.size() - 1) / 2; c++) {
SWAP(indices[c + 1], indices[face.indices.size() - 1 - c]);
}
}
diff --git a/core/math/convex_hull.h b/core/math/convex_hull.h
index cc41a794bd..ab6671a7d0 100644
--- a/core/math/convex_hull.h
+++ b/core/math/convex_hull.h
@@ -62,6 +62,10 @@ public:
friend class ConvexHullComputer;
public:
+ int32_t get_next_relative() const {
+ return next;
+ }
+
int32_t get_source_vertex() const {
return (this + reverse)->target_vertex;
}
@@ -86,7 +90,7 @@ public:
};
// Vertices of the output hull
- Vector<Vector3> vertices;
+ LocalVector<Vector3> vertices;
// Edges of the output hull
LocalVector<Edge> edges;
diff --git a/core/math/geometry_3d.cpp b/core/math/geometry_3d.cpp
index c5871358ed..548b9e4620 100644
--- a/core/math/geometry_3d.cpp
+++ b/core/math/geometry_3d.cpp
@@ -141,21 +141,21 @@ real_t Geometry3D::get_closest_distance_between_segments(const Vector3 &p_p0, co
void Geometry3D::MeshData::optimize_vertices() {
HashMap<int, int> vtx_remap;
- for (int i = 0; i < faces.size(); i++) {
- for (int j = 0; j < faces[i].indices.size(); j++) {
+ for (uint32_t i = 0; i < faces.size(); i++) {
+ for (uint32_t j = 0; j < faces[i].indices.size(); j++) {
int idx = faces[i].indices[j];
if (!vtx_remap.has(idx)) {
int ni = vtx_remap.size();
vtx_remap[idx] = ni;
}
- faces.write[i].indices.write[j] = vtx_remap[idx];
+ faces[i].indices[j] = vtx_remap[idx];
}
}
- for (int i = 0; i < edges.size(); i++) {
- int a = edges[i].a;
- int b = edges[i].b;
+ for (uint32_t i = 0; i < edges.size(); i++) {
+ int a = edges[i].vertex_a;
+ int b = edges[i].vertex_b;
if (!vtx_remap.has(a)) {
int ni = vtx_remap.size();
@@ -166,16 +166,16 @@ void Geometry3D::MeshData::optimize_vertices() {
vtx_remap[b] = ni;
}
- edges.write[i].a = vtx_remap[a];
- edges.write[i].b = vtx_remap[b];
+ edges[i].vertex_a = vtx_remap[a];
+ edges[i].vertex_b = vtx_remap[b];
}
- Vector<Vector3> new_vertices;
+ LocalVector<Vector3> new_vertices;
new_vertices.resize(vtx_remap.size());
- for (int i = 0; i < vertices.size(); i++) {
+ for (uint32_t i = 0; i < vertices.size(); i++) {
if (vtx_remap.has(i)) {
- new_vertices.write[vtx_remap[i]] = vertices[i];
+ new_vertices[vtx_remap[i]] = vertices[i];
}
}
vertices = new_vertices;
@@ -751,7 +751,7 @@ Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes
Vector3 center = p.center();
// make a quad clockwise
- Vector<Vector3> vertices = {
+ LocalVector<Vector3> vertices = {
center - up * subplane_size + right * subplane_size,
center - up * subplane_size - right * subplane_size,
center + up * subplane_size - right * subplane_size,
@@ -763,7 +763,7 @@ Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes
continue;
}
- Vector<Vector3> new_vertices;
+ LocalVector<Vector3> new_vertices;
Plane clip = p_planes[j];
if (clip.normal.dot(p.normal) > 0.95f) {
@@ -774,7 +774,7 @@ Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes
break;
}
- for (int k = 0; k < vertices.size(); k++) {
+ for (uint32_t k = 0; k < vertices.size(); k++) {
int k_n = (k + 1) % vertices.size();
Vector3 edge0_A = vertices[k];
@@ -816,9 +816,9 @@ Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes
MeshData::Face face;
// Add face indices.
- for (int j = 0; j < vertices.size(); j++) {
+ for (uint32_t j = 0; j < vertices.size(); j++) {
int idx = -1;
- for (int k = 0; k < mesh.vertices.size(); k++) {
+ for (uint32_t k = 0; k < mesh.vertices.size(); k++) {
if (mesh.vertices[k].distance_to(vertices[j]) < 0.001f) {
idx = k;
break;
@@ -837,28 +837,34 @@ Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes
// Add edge.
- for (int j = 0; j < face.indices.size(); j++) {
+ for (uint32_t j = 0; j < face.indices.size(); j++) {
int a = face.indices[j];
int b = face.indices[(j + 1) % face.indices.size()];
bool found = false;
- for (int k = 0; k < mesh.edges.size(); k++) {
- if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
+ int found_idx = -1;
+ for (uint32_t k = 0; k < mesh.edges.size(); k++) {
+ if (mesh.edges[k].vertex_a == a && mesh.edges[k].vertex_b == b) {
found = true;
+ found_idx = k;
break;
}
- if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
+ if (mesh.edges[k].vertex_b == a && mesh.edges[k].vertex_a == b) {
found = true;
+ found_idx = k;
break;
}
}
if (found) {
+ mesh.edges[found_idx].face_b = j;
continue;
}
MeshData::Edge edge;
- edge.a = a;
- edge.b = b;
+ edge.vertex_a = a;
+ edge.vertex_b = b;
+ edge.face_a = j;
+ edge.face_b = -1;
mesh.edges.push_back(edge);
}
}
diff --git a/core/math/geometry_3d.h b/core/math/geometry_3d.h
index e5ace9db72..4b4c173a1e 100644
--- a/core/math/geometry_3d.h
+++ b/core/math/geometry_3d.h
@@ -33,6 +33,7 @@
#include "core/math/face3.h"
#include "core/object/object.h"
+#include "core/templates/local_vector.h"
#include "core/templates/vector.h"
class Geometry3D {
@@ -539,18 +540,19 @@ public:
struct MeshData {
struct Face {
Plane plane;
- Vector<int> indices;
+ LocalVector<int> indices;
};
- Vector<Face> faces;
+ LocalVector<Face> faces;
struct Edge {
- int a, b;
+ int vertex_a, vertex_b;
+ int face_a, face_b;
};
- Vector<Edge> edges;
+ LocalVector<Edge> edges;
- Vector<Vector3> vertices;
+ LocalVector<Vector3> vertices;
void optimize_vertices();
};
diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h
index 7fa674a23d..0af529ad98 100644
--- a/core/math/math_funcs.h
+++ b/core/math/math_funcs.h
@@ -184,6 +184,9 @@ public:
#endif
}
+ static _ALWAYS_INLINE_ bool is_finite(double p_val) { return isfinite(p_val); }
+ static _ALWAYS_INLINE_ bool is_finite(float p_val) { return isfinite(p_val); }
+
static _ALWAYS_INLINE_ double abs(double g) { return absd(g); }
static _ALWAYS_INLINE_ float abs(float g) { return absf(g); }
static _ALWAYS_INLINE_ int abs(int g) { return g > 0 ? g : -g; }
diff --git a/core/math/plane.cpp b/core/math/plane.cpp
index 3b2eab4ae2..a5d2fe5628 100644
--- a/core/math/plane.cpp
+++ b/core/math/plane.cpp
@@ -176,6 +176,10 @@ bool Plane::is_equal_approx(const Plane &p_plane) const {
return normal.is_equal_approx(p_plane.normal) && Math::is_equal_approx(d, p_plane.d);
}
+bool Plane::is_finite() const {
+ return normal.is_finite() && Math::is_finite(d);
+}
+
Plane::operator String() const {
return "[N: " + normal.operator String() + ", D: " + String::num_real(d, false) + "]";
}
diff --git a/core/math/plane.h b/core/math/plane.h
index 73babfa496..77da59fb27 100644
--- a/core/math/plane.h
+++ b/core/math/plane.h
@@ -74,6 +74,7 @@ struct _NO_DISCARD_ Plane {
Plane operator-() const { return Plane(-normal, -d); }
bool is_equal_approx(const Plane &p_plane) const;
bool is_equal_approx_any_side(const Plane &p_plane) const;
+ bool is_finite() const;
_FORCE_INLINE_ bool operator==(const Plane &p_plane) const;
_FORCE_INLINE_ bool operator!=(const Plane &p_plane) const;
diff --git a/core/math/quaternion.cpp b/core/math/quaternion.cpp
index 4a8d29e402..6a5f29f3d8 100644
--- a/core/math/quaternion.cpp
+++ b/core/math/quaternion.cpp
@@ -79,6 +79,10 @@ bool Quaternion::is_equal_approx(const Quaternion &p_quaternion) const {
return Math::is_equal_approx(x, p_quaternion.x) && Math::is_equal_approx(y, p_quaternion.y) && Math::is_equal_approx(z, p_quaternion.z) && Math::is_equal_approx(w, p_quaternion.w);
}
+bool Quaternion::is_finite() const {
+ return Math::is_finite(x) && Math::is_finite(y) && Math::is_finite(z) && Math::is_finite(w);
+}
+
real_t Quaternion::length() const {
return Math::sqrt(length_squared());
}
diff --git a/core/math/quaternion.h b/core/math/quaternion.h
index 178cfaca70..7aa400aa8c 100644
--- a/core/math/quaternion.h
+++ b/core/math/quaternion.h
@@ -55,6 +55,7 @@ struct _NO_DISCARD_ Quaternion {
}
_FORCE_INLINE_ real_t length_squared() const;
bool is_equal_approx(const Quaternion &p_quaternion) const;
+ bool is_finite() const;
real_t length() const;
void normalize();
Quaternion normalized() const;
diff --git a/core/math/quick_hull.cpp b/core/math/quick_hull.cpp
index c7727a44a1..c194e1cc21 100644
--- a/core/math/quick_hull.cpp
+++ b/core/math/quick_hull.cpp
@@ -369,7 +369,7 @@ Error QuickHull::build(const Vector<Vector3> &p_points, Geometry3D::MeshData &r_
for (List<Geometry3D::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
Geometry3D::MeshData::Face &f = E->get();
- for (int i = 0; i < f.indices.size(); i++) {
+ for (uint32_t i = 0; i < f.indices.size(); i++) {
int a = E->get().indices[i];
int b = E->get().indices[(i + 1) % f.indices.size()];
Edge e(a, b);
@@ -436,17 +436,24 @@ Error QuickHull::build(const Vector<Vector3> &p_points, Geometry3D::MeshData &r_
r_mesh.faces.clear();
r_mesh.faces.resize(ret_faces.size());
+ HashMap<List<Geometry3D::MeshData::Face>::Element *, int> face_indices;
+
int idx = 0;
- for (const Geometry3D::MeshData::Face &E : ret_faces) {
- r_mesh.faces.write[idx++] = E;
+ for (List<Geometry3D::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
+ face_indices[E] = idx;
+ r_mesh.faces[idx++] = E->get();
}
r_mesh.edges.resize(ret_edges.size());
idx = 0;
for (const KeyValue<Edge, RetFaceConnect> &E : ret_edges) {
Geometry3D::MeshData::Edge e;
- e.a = E.key.vertices[0];
- e.b = E.key.vertices[1];
- r_mesh.edges.write[idx++] = e;
+ e.vertex_a = E.key.vertices[0];
+ e.vertex_b = E.key.vertices[1];
+ ERR_CONTINUE(!face_indices.has(E.value.left));
+ ERR_CONTINUE(!face_indices.has(E.value.right));
+ e.face_a = face_indices[E.value.left];
+ e.face_b = face_indices[E.value.right];
+ r_mesh.edges[idx++] = e;
}
r_mesh.vertices = p_points;
diff --git a/core/math/random_number_generator.h b/core/math/random_number_generator.h
index 9352bae0a6..bf67154cd6 100644
--- a/core/math/random_number_generator.h
+++ b/core/math/random_number_generator.h
@@ -57,7 +57,7 @@ public:
_FORCE_INLINE_ real_t randfn(real_t p_mean = 0.0, real_t p_deviation = 1.0) { return randbase.randfn(p_mean, p_deviation); }
_FORCE_INLINE_ int randi_range(int p_from, int p_to) { return randbase.random(p_from, p_to); }
- RandomNumberGenerator() {}
+ RandomNumberGenerator() { randbase.randomize(); }
};
#endif // RANDOM_NUMBER_GENERATOR_H
diff --git a/core/math/rect2.cpp b/core/math/rect2.cpp
index 9e78ead816..facf4eb3c4 100644
--- a/core/math/rect2.cpp
+++ b/core/math/rect2.cpp
@@ -38,6 +38,10 @@ bool Rect2::is_equal_approx(const Rect2 &p_rect) const {
return position.is_equal_approx(p_rect.position) && size.is_equal_approx(p_rect.size);
}
+bool Rect2::is_finite() const {
+ return position.is_finite() && size.is_finite();
+}
+
bool Rect2::intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos, Point2 *r_normal) const {
#ifdef MATH_CHECKS
if (unlikely(size.x < 0 || size.y < 0)) {
diff --git a/core/math/rect2.h b/core/math/rect2.h
index 50dd2dc1df..9863405d8e 100644
--- a/core/math/rect2.h
+++ b/core/math/rect2.h
@@ -207,6 +207,7 @@ struct _NO_DISCARD_ Rect2 {
}
bool is_equal_approx(const Rect2 &p_rect) const;
+ bool is_finite() const;
bool operator==(const Rect2 &p_rect) const { return position == p_rect.position && size == p_rect.size; }
bool operator!=(const Rect2 &p_rect) const { return position != p_rect.position || size != p_rect.size; }
diff --git a/core/math/transform_2d.cpp b/core/math/transform_2d.cpp
index 2bfefe979f..548a82d254 100644
--- a/core/math/transform_2d.cpp
+++ b/core/math/transform_2d.cpp
@@ -168,6 +168,10 @@ bool Transform2D::is_equal_approx(const Transform2D &p_transform) const {
return columns[0].is_equal_approx(p_transform.columns[0]) && columns[1].is_equal_approx(p_transform.columns[1]) && columns[2].is_equal_approx(p_transform.columns[2]);
}
+bool Transform2D::is_finite() const {
+ return columns[0].is_finite() && columns[1].is_finite() && columns[2].is_finite();
+}
+
Transform2D Transform2D::looking_at(const Vector2 &p_target) const {
Transform2D return_trans = Transform2D(get_rotation(), get_origin());
Vector2 target_position = affine_inverse().xform(p_target);
diff --git a/core/math/transform_2d.h b/core/math/transform_2d.h
index f23f32867a..2b11f36535 100644
--- a/core/math/transform_2d.h
+++ b/core/math/transform_2d.h
@@ -98,6 +98,7 @@ struct _NO_DISCARD_ Transform2D {
void orthonormalize();
Transform2D orthonormalized() const;
bool is_equal_approx(const Transform2D &p_transform) const;
+ bool is_finite() const;
Transform2D looking_at(const Vector2 &p_target) const;
diff --git a/core/math/transform_3d.cpp b/core/math/transform_3d.cpp
index 6741ef4034..3285cbd664 100644
--- a/core/math/transform_3d.cpp
+++ b/core/math/transform_3d.cpp
@@ -174,6 +174,10 @@ bool Transform3D::is_equal_approx(const Transform3D &p_transform) const {
return basis.is_equal_approx(p_transform.basis) && origin.is_equal_approx(p_transform.origin);
}
+bool Transform3D::is_finite() const {
+ return basis.is_finite() && origin.is_finite();
+}
+
bool Transform3D::operator==(const Transform3D &p_transform) const {
return (basis == p_transform.basis && origin == p_transform.origin);
}
diff --git a/core/math/transform_3d.h b/core/math/transform_3d.h
index 44d6d826f3..cb347aa1c1 100644
--- a/core/math/transform_3d.h
+++ b/core/math/transform_3d.h
@@ -75,6 +75,7 @@ struct _NO_DISCARD_ Transform3D {
void orthogonalize();
Transform3D orthogonalized() const;
bool is_equal_approx(const Transform3D &p_transform) const;
+ bool is_finite() const;
bool operator==(const Transform3D &p_transform) const;
bool operator!=(const Transform3D &p_transform) const;
diff --git a/core/math/vector2.cpp b/core/math/vector2.cpp
index 56dbba393a..5366587126 100644
--- a/core/math/vector2.cpp
+++ b/core/math/vector2.cpp
@@ -186,6 +186,10 @@ bool Vector2::is_zero_approx() const {
return Math::is_zero_approx(x) && Math::is_zero_approx(y);
}
+bool Vector2::is_finite() const {
+ return Math::is_finite(x) && Math::is_finite(y);
+}
+
Vector2::operator String() const {
return "(" + String::num_real(x, false) + ", " + String::num_real(y, false) + ")";
}
diff --git a/core/math/vector2.h b/core/math/vector2.h
index 75364f72f0..5775d8e735 100644
--- a/core/math/vector2.h
+++ b/core/math/vector2.h
@@ -121,6 +121,7 @@ struct _NO_DISCARD_ Vector2 {
bool is_equal_approx(const Vector2 &p_v) const;
bool is_zero_approx() const;
+ bool is_finite() const;
Vector2 operator+(const Vector2 &p_v) const;
void operator+=(const Vector2 &p_v);
diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp
index 55ba509144..b106200c4a 100644
--- a/core/math/vector3.cpp
+++ b/core/math/vector3.cpp
@@ -139,6 +139,10 @@ bool Vector3::is_zero_approx() const {
return Math::is_zero_approx(x) && Math::is_zero_approx(y) && Math::is_zero_approx(z);
}
+bool Vector3::is_finite() const {
+ return Math::is_finite(x) && Math::is_finite(y) && Math::is_finite(z);
+}
+
Vector3::operator String() const {
return "(" + String::num_real(x, false) + ", " + String::num_real(y, false) + ", " + String::num_real(z, false) + ")";
}
diff --git a/core/math/vector3.h b/core/math/vector3.h
index 62e810fb4d..19771eb312 100644
--- a/core/math/vector3.h
+++ b/core/math/vector3.h
@@ -136,6 +136,7 @@ struct _NO_DISCARD_ Vector3 {
bool is_equal_approx(const Vector3 &p_v) const;
bool is_zero_approx() const;
+ bool is_finite() const;
/* Operators */
diff --git a/core/math/vector4.cpp b/core/math/vector4.cpp
index 9fd980aaff..3b189f7ed4 100644
--- a/core/math/vector4.cpp
+++ b/core/math/vector4.cpp
@@ -64,6 +64,10 @@ bool Vector4::is_zero_approx() const {
return Math::is_zero_approx(x) && Math::is_zero_approx(y) && Math::is_zero_approx(z) && Math::is_zero_approx(w);
}
+bool Vector4::is_finite() const {
+ return Math::is_finite(x) && Math::is_finite(y) && Math::is_finite(z) && Math::is_finite(w);
+}
+
real_t Vector4::length() const {
return Math::sqrt(length_squared());
}
diff --git a/core/math/vector4.h b/core/math/vector4.h
index ac7b6c3aee..7c4bdc1788 100644
--- a/core/math/vector4.h
+++ b/core/math/vector4.h
@@ -71,6 +71,7 @@ struct _NO_DISCARD_ Vector4 {
_FORCE_INLINE_ real_t length_squared() const;
bool is_equal_approx(const Vector4 &p_vec4) const;
bool is_zero_approx() const;
+ bool is_finite() const;
real_t length() const;
void normalize();
Vector4 normalized() const;
diff --git a/core/object/class_db.cpp b/core/object/class_db.cpp
index ca56add2ab..41585943b3 100644
--- a/core/object/class_db.cpp
+++ b/core/object/class_db.cpp
@@ -1528,7 +1528,10 @@ void ClassDB::register_extension_class(ObjectNativeExtension *p_extension) {
c.api = p_extension->editor_class ? API_EDITOR_EXTENSION : API_EXTENSION;
c.native_extension = p_extension;
c.name = p_extension->class_name;
- c.creation_func = parent->creation_func;
+ c.is_virtual = p_extension->is_virtual;
+ if (!p_extension->is_abstract) {
+ c.creation_func = parent->creation_func;
+ }
c.inherits = parent->name;
c.class_ptr = parent->class_ptr;
c.inherits_ptr = parent;
diff --git a/core/object/method_bind.cpp b/core/object/method_bind.cpp
index 0edc7a90c2..5381c596ce 100644
--- a/core/object/method_bind.cpp
+++ b/core/object/method_bind.cpp
@@ -63,7 +63,9 @@ 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("_unnamed_arg" + itos(p_argument));
+ if (info.name.is_empty()) {
+ info.name = p_argument < arg_names.size() ? String(arg_names[p_argument]) : String("_unnamed_arg" + itos(p_argument));
+ }
#endif
return info;
}
diff --git a/core/object/method_bind.h b/core/object/method_bind.h
index 0d3e40f709..598e8a224d 100644
--- a/core/object/method_bind.h
+++ b/core/object/method_bind.h
@@ -292,11 +292,6 @@ class MethodBindT : public MethodBind {
void (MB_T::*method)(P...);
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -304,9 +299,6 @@ protected:
return Variant::NIL;
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
@@ -367,11 +359,6 @@ class MethodBindTC : public MethodBind {
void (MB_T::*method)(P...) const;
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -379,9 +366,6 @@ protected:
return Variant::NIL;
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
@@ -444,11 +428,6 @@ class MethodBindTR : public MethodBind {
(P...);
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -466,9 +445,6 @@ protected:
return GetTypeInfo<R>::get_class_info();
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
public:
#ifdef DEBUG_METHODS_ENABLED
@@ -531,11 +507,6 @@ class MethodBindTRC : public MethodBind {
(P...) const;
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -553,9 +524,6 @@ protected:
return GetTypeInfo<R>::get_class_info();
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
public:
#ifdef DEBUG_METHODS_ENABLED
@@ -615,11 +583,6 @@ class MethodBindTS : public MethodBind {
void (*function)(P...);
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -627,9 +590,6 @@ protected:
return Variant::NIL;
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
PropertyInfo pi;
@@ -678,11 +638,6 @@ class MethodBindTRS : public MethodBind {
(P...);
protected:
-// GCC raises warnings in the case P = {} as the comparison is always false...
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wlogical-op"
-#endif
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);
@@ -690,9 +645,6 @@ protected:
return GetTypeInfo<R>::VARIANT_TYPE;
}
}
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
if (p_arg >= 0 && p_arg < (int)sizeof...(P)) {
diff --git a/core/object/object.cpp b/core/object/object.cpp
index c275164b14..540b9a8f19 100644
--- a/core/object/object.cpp
+++ b/core/object/object.cpp
@@ -1468,8 +1468,8 @@ void Object::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
- ClassDB::bind_method(D_METHOD("set_indexed", "property", "value"), &Object::_set_indexed_bind);
- ClassDB::bind_method(D_METHOD("get_indexed", "property"), &Object::_get_indexed_bind);
+ ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
+ ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
@@ -1856,6 +1856,46 @@ void ObjectDB::debug_objects(DebugFunc p_func) {
}
void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
+ if (p_idx == 0) {
+ if (p_function == "connect" || p_function == "is_connected" || p_function == "disconnect" || p_function == "emit_signal" || p_function == "has_signal") {
+ List<MethodInfo> signals;
+ get_signal_list(&signals);
+ for (const MethodInfo &E : signals) {
+ r_options->push_back(E.name.quote());
+ }
+ } else if (p_function == "call" || p_function == "call_deferred" || p_function == "callv" || p_function == "has_method") {
+ List<MethodInfo> methods;
+ get_method_list(&methods);
+ for (const MethodInfo &E : methods) {
+ if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
+ continue;
+ }
+ r_options->push_back(E.name.quote());
+ }
+ } else if (p_function == "set" || p_function == "set_deferred" || p_function == "get") {
+ List<PropertyInfo> properties;
+ get_property_list(&properties);
+ for (const PropertyInfo &E : properties) {
+ if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
+ r_options->push_back(E.name.quote());
+ }
+ }
+ } else if (p_function == "set_meta" || p_function == "get_meta" || p_function == "has_meta" || p_function == "remove_meta") {
+ for (const KeyValue<StringName, Variant> &K : metadata) {
+ r_options->push_back(String(K.key).quote());
+ }
+ }
+ } else if (p_idx == 2) {
+ if (p_function == "connect") {
+ // Ideally, the constants should be inferred by the parameter.
+ // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
+ List<StringName> constants;
+ ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
+ for (const StringName &E : constants) {
+ r_options->push_back(String(E));
+ }
+ }
+ }
}
SpinLock ObjectDB::spin_lock;
diff --git a/core/object/object.h b/core/object/object.h
index 5ba5453b31..359ab0f211 100644
--- a/core/object/object.h
+++ b/core/object/object.h
@@ -295,6 +295,8 @@ struct ObjectNativeExtension {
StringName parent_class_name;
StringName class_name;
bool editor_class = false;
+ bool is_virtual = false;
+ bool is_abstract = false;
GDNativeExtensionClassSet set;
GDNativeExtensionClassGet get;
GDNativeExtensionClassGetPropertyList get_property_list;
diff --git a/core/object/script_language_extension.h b/core/object/script_language_extension.h
index 7e74f6a2be..c32fb9d85b 100644
--- a/core/object/script_language_extension.h
+++ b/core/object/script_language_extension.h
@@ -82,9 +82,10 @@ public:
GDVIRTUAL_REQUIRED_CALL(_get_documentation, doc);
Vector<DocData::ClassDoc> class_doc;
-#ifndef _MSC_VER
-#warning missing conversion from documentation to ClassDoc
-#endif
+ for (int i = 0; i < doc.size(); i++) {
+ class_doc.append(DocData::ClassDoc::from_dict(doc[i]));
+ }
+
return class_doc;
}
#endif // TOOLS_ENABLED
diff --git a/core/os/midi_driver.cpp b/core/os/midi_driver.cpp
index 410b62068a..79eef95ef2 100644
--- a/core/os/midi_driver.cpp
+++ b/core/os/midi_driver.cpp
@@ -86,11 +86,6 @@ void MIDIDriver::receive_input_packet(uint64_t timestamp, uint8_t *data, uint32_
if (length >= 2 + param_position) {
event->set_pitch(data[param_position]);
event->set_velocity(data[param_position + 1]);
-
- if (event->get_message() == MIDIMessage::NOTE_ON && event->get_velocity() == 0) {
- // https://www.midi.org/forum/228-writing-midi-software-send-note-off,-or-zero-velocity-note-on
- event->set_message(MIDIMessage::NOTE_OFF);
- }
}
break;
diff --git a/core/os/os.h b/core/os/os.h
index 1a5e45968d..af7b40f3ec 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -123,6 +123,8 @@ public:
int get_display_driver_id() const { return _display_driver_id; }
+ virtual Vector<String> get_video_adapter_driver_info() const = 0;
+
void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, Logger::ErrorType p_type = Logger::ERR_ERROR);
void print(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3;
void print_rich(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3;
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp
index 6218c21cde..c86c8316fe 100644
--- a/core/string/ustring.cpp
+++ b/core/string/ustring.cpp
@@ -1567,10 +1567,11 @@ String String::num_real(double p_num, bool p_trailing) {
#else
int decimals = 6;
#endif
- // We want to align the digits to the above sane default, so we only
- // need to subtract log10 for numbers with a positive power of ten.
- if (p_num > 10) {
- decimals -= (int)floor(log10(p_num));
+ // We want to align the digits to the above sane default, so we only need
+ // to subtract log10 for numbers with a positive power of ten magnitude.
+ double abs_num = Math::abs(p_num);
+ if (abs_num > 10) {
+ decimals -= (int)floor(log10(abs_num));
}
return num(p_num, decimals);
}
@@ -3667,29 +3668,43 @@ bool String::is_network_share_path() const {
String String::simplify_path() const {
String s = *this;
String drive;
- if (s.begins_with("local://")) {
- drive = "local://";
- s = s.substr(8, s.length());
- } else if (s.begins_with("res://")) {
- drive = "res://";
- s = s.substr(6, s.length());
- } else if (s.begins_with("user://")) {
- drive = "user://";
- s = s.substr(7, s.length());
- } else if (is_network_share_path()) {
- drive = s.substr(0, 2);
- s = s.substr(2, s.length() - 2);
- } else if (s.begins_with("/") || s.begins_with("\\")) {
- drive = s.substr(0, 1);
- s = s.substr(1, s.length() - 1);
- } else {
- int p = s.find(":/");
- if (p == -1) {
- p = s.find(":\\");
+
+ // Check if we have a special path (like res://) or a protocol identifier.
+ int p = s.find("://");
+ bool found = false;
+ if (p > 0) {
+ bool only_chars = true;
+ for (int i = 0; i < p; i++) {
+ if (!is_ascii_alphanumeric_char(s[i])) {
+ only_chars = false;
+ break;
+ }
+ }
+ if (only_chars) {
+ found = true;
+ drive = s.substr(0, p + 3);
+ s = s.substr(p + 3);
}
- if (p != -1 && p < s.find("/")) {
- drive = s.substr(0, p + 2);
- s = s.substr(p + 2, s.length());
+ }
+ if (!found) {
+ if (is_network_share_path()) {
+ // Network path, beginning with // or \\.
+ drive = s.substr(0, 2);
+ s = s.substr(2);
+ } else if (s.begins_with("/") || s.begins_with("\\")) {
+ // Absolute path.
+ drive = s.substr(0, 1);
+ s = s.substr(1);
+ } else {
+ // Windows-style drive path, like C:/ or C:\.
+ p = s.find(":/");
+ if (p == -1) {
+ p = s.find(":\\");
+ }
+ if (p != -1 && p < s.find("/")) {
+ drive = s.substr(0, p + 2);
+ s = s.substr(p + 2);
+ }
}
}
@@ -4651,10 +4666,10 @@ String String::sprintf(const Array &values, bool *error) const {
double value = values[value_index];
bool is_negative = (value < 0);
String str = String::num(ABS(value), min_decimals);
- bool not_numeric = isinf(value) || isnan(value);
+ const bool is_finite = Math::is_finite(value);
// Pad decimals out.
- if (!not_numeric) {
+ if (is_finite) {
str = str.pad_decimals(min_decimals);
}
@@ -4662,7 +4677,7 @@ String String::sprintf(const Array &values, bool *error) const {
// Padding. Leave room for sign later if required.
int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
- String pad_char = (pad_with_zeros && !not_numeric) ? String("0") : String(" "); // Never pad NaN or inf with zeros
+ String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
if (left_justified) {
str = str.rpad(pad_chars_count, pad_char);
} else {
@@ -4713,10 +4728,10 @@ String String::sprintf(const Array &values, bool *error) const {
for (int i = 0; i < count; i++) {
double val = vec[i];
String number_str = String::num(ABS(val), min_decimals);
- bool not_numeric = isinf(val) || isnan(val);
+ const bool is_finite = Math::is_finite(val);
// Pad decimals out.
- if (!not_numeric) {
+ if (is_finite) {
number_str = number_str.pad_decimals(min_decimals);
}
@@ -4724,7 +4739,7 @@ String String::sprintf(const Array &values, bool *error) const {
// Padding. Leave room for sign later if required.
int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
- String pad_char = (pad_with_zeros && !not_numeric) ? String("0") : String(" "); // Never pad NaN or inf with zeros
+ String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
if (left_justified) {
number_str = number_str.rpad(pad_chars_count, pad_char);
} else {
diff --git a/core/variant/array.cpp b/core/variant/array.cpp
index c1bdd6a6bc..c6bbd43dc4 100644
--- a/core/variant/array.cpp
+++ b/core/variant/array.cpp
@@ -31,6 +31,7 @@
#include "array.h"
#include "container_type_validate.h"
+#include "core/math/math_funcs.h"
#include "core/object/class_db.h"
#include "core/object/script_language.h"
#include "core/templates/hashfuncs.h"
@@ -299,6 +300,11 @@ Variant Array::back() const {
return operator[](_p->array.size() - 1);
}
+Variant Array::pick_random() const {
+ ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
+ return operator[](Math::rand() % _p->array.size());
+}
+
int Array::find(const Variant &p_value, int p_from) const {
ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
return _p->array.find(p_value, p_from);
@@ -402,6 +408,7 @@ Array Array::recursive_duplicate(bool p_deep, int recursion_count) const {
Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const {
Array result;
+ result._p->typed = _p->typed;
ERR_FAIL_COND_V_MSG(p_step == 0, result, "Slice step cannot be zero.");
@@ -433,6 +440,7 @@ Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const {
Array Array::filter(const Callable &p_callable) const {
Array new_arr;
new_arr.resize(size());
+ new_arr._p->typed = _p->typed;
int accepted_count = 0;
const Variant *argptrs[1];
diff --git a/core/variant/array.h b/core/variant/array.h
index 3d9a794969..ee265a9ffd 100644
--- a/core/variant/array.h
+++ b/core/variant/array.h
@@ -79,6 +79,7 @@ public:
Variant front() const;
Variant back() const;
+ Variant pick_random() const;
void sort();
void sort_custom(const Callable &p_callable);
diff --git a/core/variant/container_type_validate.h b/core/variant/container_type_validate.h
index 6171c8c88f..427a337aab 100644
--- a/core/variant/container_type_validate.h
+++ b/core/variant/container_type_validate.h
@@ -79,9 +79,12 @@ struct ContainerTypeValidate {
return true;
}
- ERR_FAIL_COND_V_MSG(type != p_variant.get_type(), false, "Attempted to " + String(p_operation) + " a variable of type '" + Variant::get_type_name(p_variant.get_type()) + "' into a " + where + " of type '" + Variant::get_type_name(type) + "'.");
if (type != p_variant.get_type()) {
- return false;
+ if (p_variant.get_type() == Variant::NIL && type == Variant::OBJECT) {
+ return true;
+ }
+
+ ERR_FAIL_V_MSG(false, "Attempted to " + String(p_operation) + " a variable of type '" + Variant::get_type_name(p_variant.get_type()) + "' into a " + where + " of type '" + Variant::get_type_name(type) + "'.");
}
if (type != Variant::OBJECT) {
@@ -90,7 +93,7 @@ struct ContainerTypeValidate {
#ifdef DEBUG_ENABLED
ObjectID object_id = p_variant;
if (object_id == ObjectID()) {
- return true; //fine its null;
+ return true; // This is fine, it's null.
}
Object *object = ObjectDB::get_instance(object_id);
ERR_FAIL_COND_V_MSG(object == nullptr, false, "Attempted to " + String(p_operation) + " an invalid (previously freed?) object instance into a '" + String(where) + ".");
@@ -101,7 +104,7 @@ struct ContainerTypeValidate {
}
#endif
if (class_name == StringName()) {
- return true; //all good, no class type requested
+ return true; // All good, no class type requested.
}
StringName obj_class = object->get_class_name();
@@ -110,12 +113,12 @@ struct ContainerTypeValidate {
}
if (script.is_null()) {
- return true; //all good
+ return true; // All good, no script requested.
}
Ref<Script> other_script = object->get_script();
- //check base script..
+ // Check base script..
ERR_FAIL_COND_V_MSG(other_script.is_null(), false, "Attempted to " + String(p_operation) + " an object into a " + String(where) + ", that does not inherit from '" + String(script->get_class_name()) + "'.");
ERR_FAIL_COND_V_MSG(!other_script->inherits_script(script), false, "Attempted to " + String(p_operation) + " an object into a " + String(where) + ", that does not inherit from '" + String(script->get_class_name()) + "'.");
diff --git a/core/variant/variant.cpp b/core/variant/variant.cpp
index 4eae23b0fb..b4528e67d1 100644
--- a/core/variant/variant.cpp
+++ b/core/variant/variant.cpp
@@ -47,146 +47,126 @@ String Variant::get_type_name(Variant::Type p_type) {
switch (p_type) {
case NIL: {
return "Nil";
- } break;
+ }
- // atomic types
+ // Atomic types.
case BOOL: {
return "bool";
- } break;
+ }
case INT: {
return "int";
-
- } break;
+ }
case FLOAT: {
return "float";
-
- } break;
+ }
case STRING: {
return "String";
- } break;
+ }
- // math types
+ // Math types.
case VECTOR2: {
return "Vector2";
- } break;
+ }
case VECTOR2I: {
return "Vector2i";
- } break;
+ }
case RECT2: {
return "Rect2";
- } break;
+ }
case RECT2I: {
return "Rect2i";
- } break;
+ }
case TRANSFORM2D: {
return "Transform2D";
- } break;
+ }
case VECTOR3: {
return "Vector3";
- } break;
+ }
case VECTOR3I: {
return "Vector3i";
- } break;
+ }
case VECTOR4: {
return "Vector4";
- } break;
+ }
case VECTOR4I: {
return "Vector4i";
- } break;
+ }
case PLANE: {
return "Plane";
-
- } break;
+ }
case AABB: {
return "AABB";
- } break;
+ }
case QUATERNION: {
return "Quaternion";
-
- } break;
+ }
case BASIS: {
return "Basis";
-
- } break;
+ }
case TRANSFORM3D: {
return "Transform3D";
-
- } break;
+ }
case PROJECTION: {
return "Projection";
+ }
- } break;
-
- // misc types
+ // Miscellaneous types.
case COLOR: {
return "Color";
-
- } break;
+ }
case RID: {
return "RID";
- } break;
+ }
case OBJECT: {
return "Object";
- } break;
+ }
case CALLABLE: {
return "Callable";
- } break;
+ }
case SIGNAL: {
return "Signal";
- } break;
+ }
case STRING_NAME: {
return "StringName";
-
- } break;
+ }
case NODE_PATH: {
return "NodePath";
-
- } break;
+ }
case DICTIONARY: {
return "Dictionary";
-
- } break;
+ }
case ARRAY: {
return "Array";
+ }
- } break;
-
- // arrays
+ // Arrays.
case PACKED_BYTE_ARRAY: {
return "PackedByteArray";
-
- } break;
+ }
case PACKED_INT32_ARRAY: {
return "PackedInt32Array";
-
- } break;
+ }
case PACKED_INT64_ARRAY: {
return "PackedInt64Array";
-
- } break;
+ }
case PACKED_FLOAT32_ARRAY: {
return "PackedFloat32Array";
-
- } break;
+ }
case PACKED_FLOAT64_ARRAY: {
return "PackedFloat64Array";
-
- } break;
+ }
case PACKED_STRING_ARRAY: {
return "PackedStringArray";
- } break;
+ }
case PACKED_VECTOR2_ARRAY: {
return "PackedVector2Array";
-
- } break;
+ }
case PACKED_VECTOR3_ARRAY: {
return "PackedVector3Array";
-
- } break;
+ }
case PACKED_COLOR_ARRAY: {
return "PackedColorArray";
-
- } break;
+ }
default: {
}
}
@@ -880,157 +860,126 @@ bool Variant::is_zero() const {
switch (type) {
case NIL: {
return true;
- } break;
+ }
- // atomic types
+ // Atomic types.
case BOOL: {
return !(_data._bool);
- } break;
+ }
case INT: {
return _data._int == 0;
-
- } break;
+ }
case FLOAT: {
return _data._float == 0;
-
- } break;
+ }
case STRING: {
return *reinterpret_cast<const String *>(_data._mem) == String();
+ }
- } break;
-
- // math types
+ // Math types.
case VECTOR2: {
return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2();
-
- } break;
+ }
case VECTOR2I: {
return *reinterpret_cast<const Vector2i *>(_data._mem) == Vector2i();
-
- } break;
+ }
case RECT2: {
return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2();
-
- } break;
+ }
case RECT2I: {
return *reinterpret_cast<const Rect2i *>(_data._mem) == Rect2i();
-
- } break;
+ }
case TRANSFORM2D: {
return *_data._transform2d == Transform2D();
-
- } break;
+ }
case VECTOR3: {
return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3();
-
- } break;
+ }
case VECTOR3I: {
return *reinterpret_cast<const Vector3i *>(_data._mem) == Vector3i();
-
- } break;
+ }
case VECTOR4: {
return *reinterpret_cast<const Vector4 *>(_data._mem) == Vector4();
-
- } break;
+ }
case VECTOR4I: {
return *reinterpret_cast<const Vector4i *>(_data._mem) == Vector4i();
-
- } break;
+ }
case PLANE: {
return *reinterpret_cast<const Plane *>(_data._mem) == Plane();
-
- } break;
+ }
case AABB: {
return *_data._aabb == ::AABB();
- } break;
+ }
case QUATERNION: {
return *reinterpret_cast<const Quaternion *>(_data._mem) == Quaternion();
-
- } break;
+ }
case BASIS: {
return *_data._basis == Basis();
-
- } break;
+ }
case TRANSFORM3D: {
return *_data._transform3d == Transform3D();
-
- } break;
+ }
case PROJECTION: {
return *_data._projection == Projection();
+ }
- } break;
-
- // misc types
+ // Miscellaneous types.
case COLOR: {
return *reinterpret_cast<const Color *>(_data._mem) == Color();
-
- } break;
+ }
case RID: {
return *reinterpret_cast<const ::RID *>(_data._mem) == ::RID();
- } break;
+ }
case OBJECT: {
return _get_obj().obj == nullptr;
- } break;
+ }
case CALLABLE: {
return reinterpret_cast<const Callable *>(_data._mem)->is_null();
- } break;
+ }
case SIGNAL: {
return reinterpret_cast<const Signal *>(_data._mem)->is_null();
- } break;
+ }
case STRING_NAME: {
return *reinterpret_cast<const StringName *>(_data._mem) != StringName();
-
- } break;
+ }
case NODE_PATH: {
return reinterpret_cast<const NodePath *>(_data._mem)->is_empty();
-
- } break;
+ }
case DICTIONARY: {
return reinterpret_cast<const Dictionary *>(_data._mem)->is_empty();
-
- } break;
+ }
case ARRAY: {
return reinterpret_cast<const Array *>(_data._mem)->is_empty();
+ }
- } break;
-
- // arrays
+ // Arrays.
case PACKED_BYTE_ARRAY: {
return PackedArrayRef<uint8_t>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_INT32_ARRAY: {
return PackedArrayRef<int32_t>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_INT64_ARRAY: {
return PackedArrayRef<int64_t>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_FLOAT32_ARRAY: {
return PackedArrayRef<float>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_FLOAT64_ARRAY: {
return PackedArrayRef<double>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_STRING_ARRAY: {
return PackedArrayRef<String>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_VECTOR2_ARRAY: {
return PackedArrayRef<Vector2>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_VECTOR3_ARRAY: {
return PackedArrayRef<Vector3>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
case PACKED_COLOR_ARRAY: {
return PackedArrayRef<Color>::get_array(_data.packed_array).size() == 0;
-
- } break;
+ }
default: {
}
}
@@ -1042,60 +991,49 @@ bool Variant::is_one() const {
switch (type) {
case NIL: {
return true;
- } break;
+ }
- // atomic types
case BOOL: {
return _data._bool;
- } break;
+ }
case INT: {
return _data._int == 1;
-
- } break;
+ }
case FLOAT: {
return _data._float == 1;
+ }
- } break;
case VECTOR2: {
return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(1, 1);
-
- } break;
+ }
case VECTOR2I: {
return *reinterpret_cast<const Vector2i *>(_data._mem) == Vector2i(1, 1);
-
- } break;
+ }
case RECT2: {
return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(1, 1, 1, 1);
-
- } break;
+ }
case RECT2I: {
return *reinterpret_cast<const Rect2i *>(_data._mem) == Rect2i(1, 1, 1, 1);
-
- } break;
+ }
case VECTOR3: {
return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(1, 1, 1);
-
- } break;
+ }
case VECTOR3I: {
return *reinterpret_cast<const Vector3i *>(_data._mem) == Vector3i(1, 1, 1);
-
- } break;
+ }
case VECTOR4: {
return *reinterpret_cast<const Vector4 *>(_data._mem) == Vector4(1, 1, 1, 1);
-
- } break;
+ }
case VECTOR4I: {
return *reinterpret_cast<const Vector4i *>(_data._mem) == Vector4i(1, 1, 1, 1);
-
- } break;
+ }
case PLANE: {
return *reinterpret_cast<const Plane *>(_data._mem) == Plane(1, 1, 1, 1);
+ }
- } break;
case COLOR: {
return *reinterpret_cast<const Color *>(_data._mem) == Color(1, 1, 1, 1);
-
- } break;
+ }
default: {
return !is_zero();
@@ -1133,10 +1071,10 @@ void Variant::reference(const Variant &p_variant) {
switch (p_variant.type) {
case NIL: {
- // none
+ // None.
} break;
- // atomic types
+ // Atomic types.
case BOOL: {
_data._bool = p_variant._data._bool;
} break;
@@ -1150,7 +1088,7 @@ void Variant::reference(const Variant &p_variant) {
memnew_placement(_data._mem, String(*reinterpret_cast<const String *>(p_variant._data._mem)));
} break;
- // math types
+ // Math types.
case VECTOR2: {
memnew_placement(_data._mem, Vector2(*reinterpret_cast<const Vector2 *>(p_variant._data._mem)));
} break;
@@ -1202,10 +1140,9 @@ void Variant::reference(const Variant &p_variant) {
memnew_placement(_data._projection, Projection(*p_variant._data._projection));
} break;
- // misc types
+ // Miscellaneous types.
case COLOR: {
memnew_placement(_data._mem, Color(*reinterpret_cast<const Color *>(p_variant._data._mem)));
-
} break;
case RID: {
memnew_placement(_data._mem, ::RID(*reinterpret_cast<const ::RID *>(p_variant._data._mem)));
@@ -1224,7 +1161,6 @@ void Variant::reference(const Variant &p_variant) {
_get_obj().obj = const_cast<Object *>(p_variant._get_obj().obj);
_get_obj().id = p_variant._get_obj().id;
-
} break;
case CALLABLE: {
memnew_placement(_data._mem, Callable(*reinterpret_cast<const Callable *>(p_variant._data._mem)));
@@ -1234,84 +1170,71 @@ void Variant::reference(const Variant &p_variant) {
} break;
case STRING_NAME: {
memnew_placement(_data._mem, StringName(*reinterpret_cast<const StringName *>(p_variant._data._mem)));
-
} break;
case NODE_PATH: {
memnew_placement(_data._mem, NodePath(*reinterpret_cast<const NodePath *>(p_variant._data._mem)));
-
} break;
case DICTIONARY: {
memnew_placement(_data._mem, Dictionary(*reinterpret_cast<const Dictionary *>(p_variant._data._mem)));
-
} break;
case ARRAY: {
memnew_placement(_data._mem, Array(*reinterpret_cast<const Array *>(p_variant._data._mem)));
-
} break;
- // arrays
+ // Arrays.
case PACKED_BYTE_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<uint8_t> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<uint8_t>::create();
}
-
} break;
case PACKED_INT32_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<int32_t> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<int32_t>::create();
}
-
} break;
case PACKED_INT64_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<int64_t> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<int64_t>::create();
}
-
} break;
case PACKED_FLOAT32_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<float> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<float>::create();
}
-
} break;
case PACKED_FLOAT64_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<double> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<double>::create();
}
-
} break;
case PACKED_STRING_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<String> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<String>::create();
}
-
} break;
case PACKED_VECTOR2_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<Vector2> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<Vector2>::create();
}
-
} break;
case PACKED_VECTOR3_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<Vector3> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<Vector3>::create();
}
-
} break;
case PACKED_COLOR_ARRAY: {
_data.packed_array = static_cast<PackedArrayRef<Color> *>(p_variant._data.packed_array)->reference();
if (!_data.packed_array) {
_data.packed_array = PackedArrayRef<Color>::create();
}
-
} break;
default: {
}
@@ -1331,6 +1254,7 @@ void Variant::zero() {
case FLOAT:
this->_data._float = 0;
break;
+
case VECTOR2:
*reinterpret_cast<Vector2 *>(this->_data._mem) = Vector2();
break;
@@ -1361,9 +1285,11 @@ void Variant::zero() {
case QUATERNION:
*reinterpret_cast<Quaternion *>(this->_data._mem) = Quaternion();
break;
+
case COLOR:
*reinterpret_cast<Color *>(this->_data._mem) = Color();
break;
+
default:
this->clear();
break;
@@ -1375,15 +1301,8 @@ void Variant::_clear_internal() {
case STRING: {
reinterpret_cast<String *>(_data._mem)->~String();
} break;
- /*
- // no point, they don't allocate memory
- VECTOR3,
- PLANE,
- QUATERNION,
- COLOR,
- VECTOR2,
- RECT2
- */
+
+ // Math types.
case TRANSFORM2D: {
if (_data._transform2d) {
_data._transform2d->~Transform2D();
@@ -1419,7 +1338,8 @@ void Variant::_clear_internal() {
_data._projection = nullptr;
}
} break;
- // misc types
+
+ // Miscellaneous types.
case STRING_NAME: {
reinterpret_cast<StringName *>(_data._mem)->~StringName();
} break;
@@ -1428,7 +1348,7 @@ void Variant::_clear_internal() {
} break;
case OBJECT: {
if (_get_obj().id.is_ref_counted()) {
- //we are safe that there is a reference here
+ // We are safe that there is a reference here.
RefCounted *ref_counted = static_cast<RefCounted *>(_get_obj().obj);
if (ref_counted->unreference()) {
memdelete(ref_counted);
@@ -1438,8 +1358,8 @@ void Variant::_clear_internal() {
_get_obj().id = ObjectID();
} break;
case RID: {
- // not much need probably
- // Can't seem to use destructor + scoping operator, so hack.
+ // Not much need probably.
+ // HACK: Can't seem to use destructor + scoping operator, so hack.
typedef ::RID RID_Class;
reinterpret_cast<RID_Class *>(_data._mem)->~RID_Class();
} break;
@@ -1455,7 +1375,8 @@ void Variant::_clear_internal() {
case ARRAY: {
reinterpret_cast<Array *>(_data._mem)->~Array();
} break;
- // arrays
+
+ // Arrays.
case PACKED_BYTE_ARRAY: {
PackedArrayRefBase::destroy(_data.packed_array);
} break;
@@ -1484,7 +1405,9 @@ void Variant::_clear_internal() {
PackedArrayRefBase::destroy(_data.packed_array);
} break;
default: {
- } /* not needed */
+ // Not needed, there is no point. The following do not allocate memory:
+ // VECTOR2, VECTOR3, RECT2, PLANE, QUATERNION, COLOR.
+ }
}
}
@@ -1863,34 +1786,34 @@ String Variant::stringify(int recursion_count) const {
str += " }";
return str;
- } break;
+ }
case PACKED_VECTOR2_ARRAY: {
return stringify_vector(operator Vector<Vector2>(), recursion_count);
- } break;
+ }
case PACKED_VECTOR3_ARRAY: {
return stringify_vector(operator Vector<Vector3>(), recursion_count);
- } break;
+ }
case PACKED_COLOR_ARRAY: {
return stringify_vector(operator Vector<Color>(), recursion_count);
- } break;
+ }
case PACKED_STRING_ARRAY: {
return stringify_vector(operator Vector<String>(), recursion_count);
- } break;
+ }
case PACKED_BYTE_ARRAY: {
return stringify_vector(operator Vector<uint8_t>(), recursion_count);
- } break;
+ }
case PACKED_INT32_ARRAY: {
return stringify_vector(operator Vector<int32_t>(), recursion_count);
- } break;
+ }
case PACKED_INT64_ARRAY: {
return stringify_vector(operator Vector<int64_t>(), recursion_count);
- } break;
+ }
case PACKED_FLOAT32_ARRAY: {
return stringify_vector(operator Vector<float>(), recursion_count);
- } break;
+ }
case PACKED_FLOAT64_ARRAY: {
return stringify_vector(operator Vector<double>(), recursion_count);
- } break;
+ }
case ARRAY: {
Array arr = operator Array();
if (recursion_count > MAX_RECURSION) {
@@ -1899,8 +1822,7 @@ String Variant::stringify(int recursion_count) const {
}
return stringify_vector(arr, recursion_count);
-
- } break;
+ }
case OBJECT: {
if (_get_obj().obj) {
if (!_get_obj().id.is_ref_counted() && ObjectDB::get_instance(_get_obj().id) == nullptr) {
@@ -1911,20 +1833,19 @@ String Variant::stringify(int recursion_count) const {
} else {
return "<Object#null>";
}
-
- } break;
+ }
case CALLABLE: {
const Callable &c = *reinterpret_cast<const Callable *>(_data._mem);
return c;
- } break;
+ }
case SIGNAL: {
const Signal &s = *reinterpret_cast<const Signal *>(_data._mem);
return s;
- } break;
+ }
case RID: {
const ::RID &s = *reinterpret_cast<const ::RID *>(_data._mem);
return "RID(" + itos(s.get_id()) + ")";
- } break;
+ }
default: {
return "<" + get_type_name(type) + ">";
}
@@ -1932,8 +1853,7 @@ String Variant::stringify(int recursion_count) const {
}
String Variant::to_json_string() const {
- JSON json;
- return json.stringify(*this);
+ return JSON::stringify(*this);
}
Variant::operator Vector2() const {
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index 1831f7b72a..688650f532 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -1606,6 +1606,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector2, is_normalized, sarray(), varray());
bind_method(Vector2, is_equal_approx, sarray("to"), varray());
bind_method(Vector2, is_zero_approx, sarray(), varray());
+ bind_method(Vector2, is_finite, sarray(), varray());
bind_method(Vector2, posmod, sarray("mod"), varray());
bind_method(Vector2, posmodv, sarray("modv"), varray());
bind_method(Vector2, project, sarray("b"), varray());
@@ -1653,6 +1654,7 @@ static void _register_variant_builtin_methods() {
bind_method(Rect2, has_area, sarray(), varray());
bind_method(Rect2, has_point, sarray("point"), varray());
bind_method(Rect2, is_equal_approx, sarray("rect"), varray());
+ bind_method(Rect2, is_finite, sarray(), varray());
bind_method(Rect2, intersects, sarray("b", "include_borders"), varray(false));
bind_method(Rect2, encloses, sarray("b"), varray());
bind_method(Rect2, intersection, sarray("b"), varray());
@@ -1695,6 +1697,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector3, is_normalized, sarray(), varray());
bind_method(Vector3, is_equal_approx, sarray("to"), varray());
bind_method(Vector3, is_zero_approx, sarray(), varray());
+ bind_method(Vector3, is_finite, sarray(), varray());
bind_method(Vector3, inverse, sarray(), varray());
bind_method(Vector3, clamp, sarray("min", "max"), varray());
bind_method(Vector3, snapped, sarray("step"), varray());
@@ -1759,6 +1762,7 @@ static void _register_variant_builtin_methods() {
bind_method(Vector4, inverse, sarray(), varray());
bind_method(Vector4, is_equal_approx, sarray("with"), varray());
bind_method(Vector4, is_zero_approx, sarray(), varray());
+ bind_method(Vector4, is_finite, sarray(), varray());
/* Vector4i */
@@ -1775,6 +1779,7 @@ static void _register_variant_builtin_methods() {
bind_method(Plane, normalized, sarray(), varray());
bind_method(Plane, center, sarray(), varray());
bind_method(Plane, is_equal_approx, sarray("to_plane"), varray());
+ bind_method(Plane, is_finite, sarray(), varray());
bind_method(Plane, is_point_over, sarray("point"), varray());
bind_method(Plane, distance_to, sarray("point"), varray());
bind_method(Plane, has_point, sarray("point", "tolerance"), varray(CMP_EPSILON));
@@ -1790,6 +1795,7 @@ static void _register_variant_builtin_methods() {
bind_method(Quaternion, normalized, sarray(), varray());
bind_method(Quaternion, is_normalized, sarray(), varray());
bind_method(Quaternion, is_equal_approx, sarray("to"), varray());
+ bind_method(Quaternion, is_finite, sarray(), varray());
bind_method(Quaternion, inverse, sarray(), varray());
bind_method(Quaternion, log, sarray(), varray());
bind_method(Quaternion, exp, sarray(), varray());
@@ -1909,6 +1915,7 @@ static void _register_variant_builtin_methods() {
bind_method(Transform2D, basis_xform_inv, sarray("v"), varray());
bind_method(Transform2D, interpolate_with, sarray("xform", "weight"), varray());
bind_method(Transform2D, is_equal_approx, sarray("xform"), varray());
+ bind_method(Transform2D, is_finite, sarray(), varray());
bind_method(Transform2D, set_rotation, sarray("rotation"), varray());
bind_method(Transform2D, set_scale, sarray("scale"), varray());
bind_method(Transform2D, set_skew, sarray("skew"), varray());
@@ -1923,16 +1930,17 @@ static void _register_variant_builtin_methods() {
bind_methodv(Basis, rotated, static_cast<Basis (Basis::*)(const Vector3 &, real_t) const>(&Basis::rotated), sarray("axis", "angle"), varray());
bind_method(Basis, scaled, sarray("scale"), varray());
bind_method(Basis, get_scale, sarray(), varray());
- bind_method(Basis, get_euler, sarray("order"), varray(Basis::EULER_ORDER_YXZ));
+ bind_method(Basis, get_euler, sarray("order"), varray((int64_t)Basis::EULER_ORDER_YXZ));
bind_method(Basis, tdotx, sarray("with"), varray());
bind_method(Basis, tdoty, sarray("with"), varray());
bind_method(Basis, tdotz, sarray("with"), varray());
bind_method(Basis, slerp, sarray("to", "weight"), varray());
bind_method(Basis, is_equal_approx, sarray("b"), varray());
+ bind_method(Basis, is_finite, sarray(), varray());
bind_method(Basis, get_rotation_quaternion, sarray(), varray());
bind_static_method(Basis, looking_at, sarray("target", "up"), varray(Vector3(0, 1, 0)));
bind_static_method(Basis, from_scale, sarray("scale"), varray());
- bind_static_method(Basis, from_euler, sarray("euler", "order"), varray(Basis::EULER_ORDER_YXZ));
+ bind_static_method(Basis, from_euler, sarray("euler", "order"), varray((int64_t)Basis::EULER_ORDER_YXZ));
/* AABB */
@@ -1943,6 +1951,7 @@ static void _register_variant_builtin_methods() {
bind_method(AABB, has_surface, sarray(), varray());
bind_method(AABB, has_point, sarray("point"), varray());
bind_method(AABB, is_equal_approx, sarray("aabb"), varray());
+ bind_method(AABB, is_finite, sarray(), varray());
bind_method(AABB, intersects, sarray("with"), varray());
bind_method(AABB, encloses, sarray("with"), varray());
bind_method(AABB, intersects_plane, sarray("plane"), varray());
@@ -1975,6 +1984,7 @@ static void _register_variant_builtin_methods() {
bind_method(Transform3D, looking_at, sarray("target", "up"), varray(Vector3(0, 1, 0)));
bind_method(Transform3D, interpolate_with, sarray("xform", "weight"), varray());
bind_method(Transform3D, is_equal_approx, sarray("xform"), varray());
+ bind_method(Transform3D, is_finite, sarray(), varray());
/* Projection */
@@ -2043,6 +2053,7 @@ static void _register_variant_builtin_methods() {
bind_method(Array, erase, sarray("value"), varray());
bind_method(Array, front, sarray(), varray());
bind_method(Array, back, sarray(), varray());
+ bind_method(Array, pick_random, sarray(), varray());
bind_method(Array, find, sarray("what", "from"), varray(0));
bind_method(Array, rfind, sarray("what", "from"), varray(-1));
bind_method(Array, find_last, sarray("value"), varray());
diff --git a/core/variant/variant_destruct.cpp b/core/variant/variant_destruct.cpp
index ab8303f3ae..5117c33e2b 100644
--- a/core/variant/variant_destruct.cpp
+++ b/core/variant/variant_destruct.cpp
@@ -41,13 +41,8 @@ static void add_destructor() {
void Variant::_register_variant_destructors() {
add_destructor<VariantDestruct<String>>();
- add_destructor<VariantDestruct<Transform2D>>();
- add_destructor<VariantDestruct<::AABB>>();
- add_destructor<VariantDestruct<Basis>>();
- add_destructor<VariantDestruct<Transform3D>>();
add_destructor<VariantDestruct<StringName>>();
add_destructor<VariantDestruct<NodePath>>();
- add_destructor<VariantDestruct<::RID>>();
add_destructor<VariantDestruct<Callable>>();
add_destructor<VariantDestruct<Signal>>();
add_destructor<VariantDestruct<Dictionary>>();
diff --git a/core/variant/variant_destruct.h b/core/variant/variant_destruct.h
index 5e3478635d..2730110c0f 100644
--- a/core/variant/variant_destruct.h
+++ b/core/variant/variant_destruct.h
@@ -50,13 +50,8 @@ struct VariantDestruct {};
}
MAKE_PTRDESTRUCT(String);
-MAKE_PTRDESTRUCT(Transform2D);
-MAKE_PTRDESTRUCT(AABB);
-MAKE_PTRDESTRUCT(Basis);
-MAKE_PTRDESTRUCT(Transform3D);
MAKE_PTRDESTRUCT(StringName);
MAKE_PTRDESTRUCT(NodePath);
-MAKE_PTRDESTRUCT(RID);
MAKE_PTRDESTRUCT(Callable);
MAKE_PTRDESTRUCT(Signal);
MAKE_PTRDESTRUCT(Dictionary);
diff --git a/core/variant/variant_internal.h b/core/variant/variant_internal.h
index 874a183d29..636710c934 100644
--- a/core/variant/variant_internal.h
+++ b/core/variant/variant_internal.h
@@ -826,7 +826,7 @@ VARIANT_ACCESSOR_NUMBER(Projection::Planes)
template <>
struct VariantInternalAccessor<Basis::EulerOrder> {
static _FORCE_INLINE_ Basis::EulerOrder get(const Variant *v) { return Basis::EulerOrder(*VariantInternal::get_int(v)); }
- static _FORCE_INLINE_ void set(Variant *v, Basis::EulerOrder p_value) { *VariantInternal::get_int(v) = p_value; }
+ static _FORCE_INLINE_ void set(Variant *v, Basis::EulerOrder p_value) { *VariantInternal::get_int(v) = (int64_t)p_value; }
};
template <>
@@ -1047,7 +1047,7 @@ struct VariantInternalAccessor<PackedColorArray> {
template <>
struct VariantInternalAccessor<Object *> {
static _FORCE_INLINE_ Object *get(const Variant *v) { return const_cast<Object *>(*VariantInternal::get_object(v)); }
- static _FORCE_INLINE_ void set(Variant *v, const Object *p_value) { *VariantInternal::get_object(v) = const_cast<Object *>(p_value); }
+ static _FORCE_INLINE_ void set(Variant *v, const Object *p_value) { VariantInternal::object_assign(v, p_value); }
};
template <>
@@ -1532,27 +1532,4 @@ struct VariantTypeConstructor {
}
};
-template <>
-struct VariantTypeConstructor<Object *> {
- _FORCE_INLINE_ static void variant_from_type(void *p_variant, void *p_value) {
- Variant *variant = reinterpret_cast<Variant *>(p_variant);
- VariantInitializer<Object *>::init(variant);
- Object *object = *(reinterpret_cast<Object **>(p_value));
- if (object) {
- if (object->is_ref_counted()) {
- if (!VariantInternal::initialize_ref(object)) {
- return;
- }
- }
- VariantInternalAccessor<Object *>::set(variant, object);
- VariantInternalAccessor<ObjectID>::set(variant, object->get_instance_id());
- }
- }
-
- _FORCE_INLINE_ static void type_from_variant(void *p_value, void *p_variant) {
- Object **value = reinterpret_cast<Object **>(p_value);
- *value = VariantInternalAccessor<Object *>::get(reinterpret_cast<Variant *>(p_variant));
- }
-};
-
#endif // VARIANT_INTERNAL_H
diff --git a/core/variant/variant_op.cpp b/core/variant/variant_op.cpp
index 6cca7955ae..301fd00d26 100644
--- a/core/variant/variant_op.cpp
+++ b/core/variant/variant_op.cpp
@@ -384,10 +384,6 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorDivNZ<Vector2, Vector2i, double>>(Variant::OP_DIVIDE, Variant::VECTOR2I, Variant::FLOAT);
register_op<OperatorEvaluatorDivNZ<Vector2i, Vector2i, int64_t>>(Variant::OP_DIVIDE, Variant::VECTOR2I, Variant::INT);
- register_op<OperatorEvaluatorDiv<Vector2, Vector2, Vector2>>(Variant::OP_DIVIDE, Variant::VECTOR2, Variant::VECTOR2);
- register_op<OperatorEvaluatorDiv<Vector2, Vector2, double>>(Variant::OP_DIVIDE, Variant::VECTOR2, Variant::FLOAT);
- register_op<OperatorEvaluatorDiv<Vector2, Vector2, int64_t>>(Variant::OP_DIVIDE, Variant::VECTOR2, Variant::INT);
-
register_op<OperatorEvaluatorDiv<Vector3, Vector3, Vector3>>(Variant::OP_DIVIDE, Variant::VECTOR3, Variant::VECTOR3);
register_op<OperatorEvaluatorDiv<Vector3, Vector3, double>>(Variant::OP_DIVIDE, Variant::VECTOR3, Variant::FLOAT);
register_op<OperatorEvaluatorDiv<Vector3, Vector3, int64_t>>(Variant::OP_DIVIDE, Variant::VECTOR3, Variant::INT);
@@ -498,8 +494,6 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorBitXor<int64_t, int64_t, int64_t>>(Variant::OP_BIT_XOR, Variant::INT, Variant::INT);
register_op<OperatorEvaluatorBitNeg<int64_t, int64_t>>(Variant::OP_BIT_NEGATE, Variant::INT, Variant::NIL);
- register_op<OperatorEvaluatorBitNeg<int64_t, int64_t>>(Variant::OP_BIT_NEGATE, Variant::INT, Variant::NIL);
-
register_op<OperatorEvaluatorAlwaysTrue<Variant::OP_EQUAL, Variant::NIL, Variant::NIL>>(Variant::OP_EQUAL, Variant::NIL, Variant::NIL);
register_op<OperatorEvaluatorEqual<bool, bool>>(Variant::OP_EQUAL, Variant::BOOL, Variant::BOOL);
register_op<OperatorEvaluatorEqual<int64_t, int64_t>>(Variant::OP_EQUAL, Variant::INT, Variant::INT);
diff --git a/core/variant/variant_utility.cpp b/core/variant/variant_utility.cpp
index 670b66d53e..3843c32bcc 100644
--- a/core/variant/variant_utility.cpp
+++ b/core/variant/variant_utility.cpp
@@ -310,6 +310,10 @@ struct VariantUtilityFunctions {
return Math::is_zero_approx(x);
}
+ static inline bool is_finite(double x) {
+ return Math::is_finite(x);
+ }
+
static inline double ease(float x, float curve) {
return Math::ease(x, curve);
}
@@ -1420,6 +1424,7 @@ void Variant::_register_variant_utility_functions() {
FUNCBINDR(is_equal_approx, sarray("a", "b"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(is_zero_approx, sarray("x"), Variant::UTILITY_FUNC_TYPE_MATH);
+ FUNCBINDR(is_finite, sarray("x"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(ease, sarray("x", "curve"), Variant::UTILITY_FUNC_TYPE_MATH);
FUNCBINDR(step_decimals, sarray("x"), Variant::UTILITY_FUNC_TYPE_MATH);
diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml
index 6e9e82bbf0..9eeb69d824 100644
--- a/doc/classes/@GlobalScope.xml
+++ b/doc/classes/@GlobalScope.xml
@@ -16,7 +16,7 @@
<return type="Variant" />
<param index="0" name="x" type="Variant" />
<description>
- Returns the absolute value of a [Variant] parameter [param x] (i.e. non-negative value). Variant types [int], [float] (real), [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
+ Returns the absolute value of a [Variant] parameter [param x] (i.e. non-negative value). Variant types [int], [float], [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
[codeblock]
var a = abs(-1)
# a is 1
@@ -114,7 +114,7 @@
<param index="3" name="end" type="float" />
<param index="4" name="t" type="float" />
<description>
- Returns the point at the given [param t] on a one-dimnesional [url=https://en.wikipedia.org/wiki/B%C3%A9zier_curve]Bezier curve[/url] defined by the given [param control_1], [param control_2], and [param end] points.
+ Returns the point at the given [param t] on a one-dimensional [url=https://en.wikipedia.org/wiki/B%C3%A9zier_curve]Bezier curve[/url] defined by the given [param control_1], [param control_2], and [param end] points.
</description>
</method>
<method name="bytes_to_var">
@@ -143,7 +143,7 @@
i = ceil(1.001) # i is 2.0
[/codeblock]
See also [method floor], [method round], and [method snapped].
- [b]Note:[/b] For better type safety, you can use [method ceilf], [method ceili], [method Vector2.ceil], [method Vector3.ceil] or [method Vector4.ceil] instead.
+ [b]Note:[/b] For better type safety, see [method ceilf], [method ceili], [method Vector2.ceil], [method Vector3.ceil] and [method Vector4.ceil].
</description>
</method>
<method name="ceilf">
@@ -151,7 +151,7 @@
<param index="0" name="x" type="float" />
<description>
Rounds [param x] upward (towards positive infinity), returning the smallest whole number that is not less than [param x].
- A type-safe version of [method ceil], specialzied in floats.
+ A type-safe version of [method ceil], returning a [float].
</description>
</method>
<method name="ceili">
@@ -159,7 +159,7 @@
<param index="0" name="x" type="float" />
<description>
Rounds [param x] upward (towards positive infinity), returning the smallest whole number that is not less than [param x].
- A type-safe version of [method ceil] that returns integer.
+ A type-safe version of [method ceil], returning an [int].
</description>
</method>
<method name="clamp">
@@ -168,7 +168,7 @@
<param index="1" name="min" type="Variant" />
<param index="2" name="max" type="Variant" />
<description>
- Clamps the [Variant] [param value] and returns a value not less than [param min] and not more than [param max]. Variant types [int], [float] (real), [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
+ Clamps the [param value], returning a [Variant] not less than [param min] and not more than [param max]. Variant types [int], [float], [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
[codeblock]
var a = clamp(-10, -1, 5)
# a is -1
@@ -196,15 +196,13 @@
<param index="1" name="min" type="float" />
<param index="2" name="max" type="float" />
<description>
- Clamps the float [param value] and returns a value not less than [param min] and not more than [param max].
+ Clamps the [param value], returning a [float] not less than [param min] and not more than [param max].
[codeblock]
var speed = 42.1
- # a is 20.0
- var a = clampf(speed, 1.0, 20.0)
+ var a = clampf(speed, 1.0, 20.5) # a is 20.5
speed = -10.0
- # a is -1.0
- a = clampf(speed, -1.0, 1.0)
+ var b = clampf(speed, -1.0, 1.0) # b is -1.0
[/codeblock]
</description>
</method>
@@ -214,15 +212,13 @@
<param index="1" name="min" type="int" />
<param index="2" name="max" type="int" />
<description>
- Clamps the integer [param value] and returns a value not less than [param min] and not more than [param max].
+ Clamps the [param value], returning an [int] not less than [param min] and not more than [param max].
[codeblock]
var speed = 42
- # a is 20
- var a = clampi(speed, 1, 20)
+ var a = clampi(speed, 1, 20) # a is 20
speed = -10
- # a is -1
- a = clampi(speed, -1, 1)
+ var b = clampi(speed, -1, 1) # b is -1
[/codeblock]
</description>
</method>
@@ -244,8 +240,7 @@
<description>
Returns the hyperbolic cosine of [param x] in radians.
[codeblock]
- # Prints 1.543081
- print(cosh(1))
+ print(cosh(1)) # Prints 1.543081
[/codeblock]
</description>
</method>
@@ -257,7 +252,7 @@
<param index="3" name="post" type="float" />
<param index="4" name="weight" type="float" />
<description>
- Cubic interpolates between two values by the factor defined in [param weight] with pre and post values.
+ Cubic interpolates between two values by the factor defined in [param weight] with [param pre] and [param post] values.
</description>
</method>
<method name="cubic_interpolate_angle">
@@ -268,7 +263,7 @@
<param index="3" name="post" type="float" />
<param index="4" name="weight" type="float" />
<description>
- Cubic interpolates between two rotation values with shortest path by the factor defined in [param weight] with pre and post values. See also [method lerp_angle].
+ Cubic interpolates between two rotation values with shortest path by the factor defined in [param weight] with [param pre] and [param post] values. See also [method lerp_angle].
</description>
</method>
<method name="cubic_interpolate_angle_in_time">
@@ -282,7 +277,7 @@
<param index="6" name="pre_t" type="float" />
<param index="7" name="post_t" type="float" />
<description>
- Cubic interpolates between two rotation values with shortest path by the factor defined in [param weight] with pre and post values. See also [method lerp_angle].
+ Cubic interpolates between two rotation values with shortest path by the factor defined in [param weight] with [param pre] and [param post] values. See also [method lerp_angle].
It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
</description>
</method>
@@ -297,8 +292,8 @@
<param index="6" name="pre_t" type="float" />
<param index="7" name="post_t" type="float" />
<description>
- Cubic interpolates between two values by the factor defined in [param weight] with pre and post values.
- It can perform smoother interpolation than [code]cubic_interpolate()[/code] by the time values.
+ Cubic interpolates between two values by the factor defined in [param weight] with [param pre] and [param post] values.
+ It can perform smoother interpolation than [method cubic_interpolate] by the time values.
</description>
</method>
<method name="db_to_linear">
@@ -314,8 +309,7 @@
<description>
Converts an angle expressed in degrees to radians.
[codeblock]
- # r is 3.141593
- var r = deg_to_rad(180)
+ var r = deg_to_rad(180) # r is 3.141593
[/codeblock]
</description>
</method>
@@ -342,7 +336,13 @@
<return type="String" />
<param index="0" name="error" type="int" />
<description>
- Returns a human-readable name for the given error code.
+ Returns a human-readable name for the given [enum Error] code.
+ [codeblock]
+ print(OK) # Prints 0
+ print(error_string(OK)) # Prints OK
+ print(error_string(ERR_BUSY)) # Prints Busy
+ print(error_string(ERR_OUT_OF_MEMORY)) # Prints Out of memory
+ [/codeblock]
</description>
</method>
<method name="exp">
@@ -363,13 +363,11 @@
<description>
Rounds [param x] downward (towards negative infinity), returning the largest whole number that is not more than [param x]. Supported types: [int], [float], [Vector2], [Vector3], [Vector4].
[codeblock]
- # a is 2.0
- var a = floor(2.99)
- # a is -3.0
- a = floor(-2.99)
+ var a = floor(2.99) # a is 2.0
+ a = floor(-2.99) # a is -3.0
[/codeblock]
See also [method ceil], [method round], and [method snapped].
- [b]Note:[/b] For better type safety, you can use [method floorf], [method floori], [method Vector2.floor], [method Vector3.floor] or [method Vector4.floor] instead.
+ [b]Note:[/b] For better type safety, see [method floorf], [method floori], [method Vector2.floor], [method Vector3.floor] and [method Vector4.floor].
</description>
</method>
<method name="floorf">
@@ -377,7 +375,7 @@
<param index="0" name="x" type="float" />
<description>
Rounds [param x] downward (towards negative infinity), returning the largest whole number that is not more than [param x].
- A type-safe version of [method floor], specialzied in floats.
+ A type-safe version of [method floor], returning a [float].
</description>
</method>
<method name="floori">
@@ -385,7 +383,8 @@
<param index="0" name="x" type="float" />
<description>
Rounds [param x] downward (towards negative infinity), returning the largest whole number that is not more than [param x].
- Equivalent of doing [code]int(x)[/code].
+ A type-safe version of [method floor], returning an [int].
+ [b]Note:[/b] This function is [i]not[/i] the same as [code]int(x)[/code], which rounds towards 0.
</description>
</method>
<method name="fmod">
@@ -393,10 +392,9 @@
<param index="0" name="x" type="float" />
<param index="1" name="y" type="float" />
<description>
- Returns the floating-point remainder of [code]x/y[/code], keeping the sign of [param x].
+ Returns the floating-point remainder of [param x] divided by [param y], keeping the sign of [param x].
[codeblock]
- # Remainder is 1.5
- var remainder = fmod(7, 5.5)
+ var remainder = fmod(7, 5.5) # remainder is 1.5
[/codeblock]
For the integer remainder operation, use the [code]%[/code] operator.
</description>
@@ -406,21 +404,23 @@
<param index="0" name="x" type="float" />
<param index="1" name="y" type="float" />
<description>
- Returns the floating-point modulus of [code]x/y[/code] that wraps equally in positive and negative.
+ Returns the floating-point modulus of [param x] divided by [param y], wrapping equally in positive and negative.
[codeblock]
+ print(" (x) (fmod(x, 1.5)) (fposmod(x, 1.5))")
for i in 7:
- var x = 0.5 * i - 1.5
- print("%4.1f %4.1f %4.1f" % [x, fmod(x, 1.5), fposmod(x, 1.5)])
+ var x = i * 0.5 - 1.5
+ print("%4.1f %4.1f | %4.1f" % [x, fmod(x, 1.5), fposmod(x, 1.5)])
[/codeblock]
Produces:
[codeblock]
- -1.5 -0.0 0.0
- -1.0 -1.0 0.5
- -0.5 -0.5 1.0
- 0.0 0.0 0.0
- 0.5 0.5 0.5
- 1.0 1.0 1.0
- 1.5 0.0 0.0
+ (x) (fmod(x, 1.5)) (fposmod(x, 1.5))
+ -1.5 -0.0 | 0.0
+ -1.0 -1.0 | 0.5
+ -0.5 -0.5 | 1.0
+ 0.0 0.0 | 0.0
+ 0.5 0.5 | 0.5
+ 1.0 1.0 | 1.0
+ 1.5 0.0 | 0.0
[/codeblock]
</description>
</method>
@@ -428,7 +428,7 @@
<return type="int" />
<param index="0" name="variable" type="Variant" />
<description>
- Returns the integer hash of the variable passed.
+ Returns the integer hash of the passed [param variable].
[codeblock]
print(hash("a")) # Prints 177670
[/codeblock]
@@ -438,7 +438,7 @@
<return type="Object" />
<param index="0" name="instance_id" type="int" />
<description>
- Returns the Object that corresponds to [param instance_id]. All Objects have a unique instance ID.
+ Returns the [Object] that corresponds to [param instance_id]. All Objects have a unique instance ID. See also [method Object.get_instance_id].
[codeblock]
var foo = "bar"
func _ready():
@@ -458,12 +458,13 @@
[codeblock]
# The interpolation ratio in the `lerp()` call below is 0.75.
var middle = lerp(20, 30, 0.75)
- # `middle` is now 27.5.
+ # middle is now 27.5.
+
# Now, we pretend to have forgotten the original ratio and want to get it back.
var ratio = inverse_lerp(20, 30, 27.5)
- # `ratio` is now 0.75.
+ # ratio is now 0.75.
[/codeblock]
- See also [method lerp] which performs the reverse of this operation, and [method remap] to map a continuous series of values to another.
+ See also [method lerp], which performs the reverse of this operation, and [method remap] to map a continuous series of values to another.
</description>
</method>
<method name="is_equal_approx">
@@ -472,15 +473,22 @@
<param index="1" name="b" type="float" />
<description>
Returns [code]true[/code] if [param a] and [param b] are approximately equal to each other.
- Here, approximately equal means that [param a] and [param b] are within a small internal epsilon of each other, which scales with the magnitude of the numbers.
+ Here, "approximately equal" means that [param a] and [param b] are within a small internal epsilon of each other, which scales with the magnitude of the numbers.
Infinity values of the same sign are considered equal.
</description>
</method>
+ <method name="is_finite">
+ <return type="bool" />
+ <param index="0" name="x" type="float" />
+ <description>
+ Returns whether [code]x[/code] is a finite value, i.e. it is not [constant @GDScript.NAN], positive infinity, or negative infinity.
+ </description>
+ </method>
<method name="is_inf">
<return type="bool" />
<param index="0" name="x" type="float" />
<description>
- Returns whether [param x] is an infinity value (either positive infinity or negative infinity).
+ Returns [code]true[/code] if [param x] is either positive infinity or negative infinity.
</description>
</method>
<method name="is_instance_id_valid">
@@ -494,14 +502,14 @@
<return type="bool" />
<param index="0" name="instance" type="Variant" />
<description>
- Returns whether [param instance] is a valid object (e.g. has not been deleted from memory).
+ Returns [code]true[/code] if [param instance] is a valid Object (e.g. has not been deleted from memory).
</description>
</method>
<method name="is_nan">
<return type="bool" />
<param index="0" name="x" type="float" />
<description>
- Returns whether [param x] is a NaN ("Not a Number" or invalid) value.
+ Returns [code]true[/code] if [param x] is a NaN ("Not a Number" or invalid) value.
</description>
</method>
<method name="is_zero_approx">
@@ -509,7 +517,7 @@
<param index="0" name="x" type="float" />
<description>
Returns [code]true[/code] if [param x] is zero or almost zero.
- This method is faster than using [method is_equal_approx] with one value as zero.
+ This function is faster than using [method is_equal_approx] with one value as zero.
</description>
</method>
<method name="lerp">
@@ -518,13 +526,13 @@
<param index="1" name="to" type="Variant" />
<param index="2" name="weight" type="Variant" />
<description>
- Linearly interpolates between two values by the factor defined in [param weight]. To perform interpolation, [param weight] should be between [code]0.0[/code] and [code]1.0[/code] (inclusive). However, values outside this range are allowed and can be used to perform [i]extrapolation[/i]. Use [method clamp] on the result of [method lerp] if this is not desired.
- Both [param from] and [param to] must have matching types. Supported types: [float], [Vector2], [Vector3], [Vector4], [Color], [Quaternion], [Basis].
+ Linearly interpolates between two values by the factor defined in [param weight]. To perform interpolation, [param weight] should be between [code]0.0[/code] and [code]1.0[/code] (inclusive). However, values outside this range are allowed and can be used to perform [i]extrapolation[/i]. If this is not desired, use [method clamp] on the result of this function.
+ Both [param from] and [param to] must be the same type. Supported types: [float], [Vector2], [Vector3], [Vector4], [Color], [Quaternion], [Basis].
[codeblock]
lerp(0, 4, 0.75) # Returns 3.0
[/codeblock]
See also [method inverse_lerp] which performs the reverse of this operation. To perform eased interpolation with [method lerp], combine it with [method ease] or [method smoothstep]. See also [method remap] to map a continuous series of values to another.
- [b]Note:[/b] For better type safety, you can use [method lerpf], [method Vector2.lerp], [method Vector3.lerp], [method Vector4.lerp], [method Color.lerp], [method Quaternion.slerp] or [method Basis.slerp] instead.
+ [b]Note:[/b] For better type safety, use [method lerpf], [method Vector2.lerp], [method Vector3.lerp], [method Vector4.lerp], [method Color.lerp], [method Quaternion.slerp] or [method Basis.slerp].
</description>
</method>
<method name="lerp_angle">
@@ -533,7 +541,7 @@
<param index="1" name="to" type="float" />
<param index="2" name="weight" type="float" />
<description>
- Linearly interpolates between two angles (in radians) by a normalized value.
+ Linearly interpolates between two angles (in radians) by a [param weight] value between 0.0 and 1.0.
Similar to [method lerp], but interpolates correctly when the angles wrap around [constant @GDScript.TAU]. To perform eased interpolation with [method lerp_angle], combine it with [method ease] or [method smoothstep].
[codeblock]
extends Sprite
@@ -544,7 +552,7 @@
rotation = lerp_angle(min_angle, max_angle, elapsed)
elapsed += delta
[/codeblock]
- [b]Note:[/b] This method lerps through the shortest path between [param from] and [param to]. However, when these two angles are approximately [code]PI + k * TAU[/code] apart for any integer [code]k[/code], it's not obvious which way they lerp due to floating-point precision errors. For example, [code]lerp_angle(0, PI, weight)[/code] lerps counter-clockwise, while [code]lerp_angle(0, PI + 5 * TAU, weight)[/code] lerps clockwise.
+ [b]Note:[/b] This function lerps through the shortest path between [param from] and [param to]. However, when these two angles are approximately [code]PI + k * TAU[/code] apart for any integer [code]k[/code], it's not obvious which way they lerp due to floating-point precision errors. For example, [code]lerp_angle(0, PI, weight)[/code] lerps counter-clockwise, while [code]lerp_angle(0, PI + 5 * TAU, weight)[/code] lerps clockwise.
</description>
</method>
<method name="lerpf">
@@ -553,7 +561,7 @@
<param index="1" name="to" type="float" />
<param index="2" name="weight" type="float" />
<description>
- Linearly interpolates between two values by the factor defined in [param weight]. To perform interpolation, [param weight] should be between [code]0.0[/code] and [code]1.0[/code] (inclusive). However, values outside this range are allowed and can be used to perform [i]extrapolation[/i].
+ Linearly interpolates between two values by the factor defined in [param weight]. To perform interpolation, [param weight] should be between [code]0.0[/code] and [code]1.0[/code] (inclusive). However, values outside this range are allowed and can be used to perform [i]extrapolation[/i]. If this is not desired, use [method clampf] on the result of this function.
[codeblock]
lerp(0, 4, 0.75) # Returns 3.0
[/codeblock]
@@ -577,7 +585,7 @@
<return type="float" />
<param index="0" name="x" type="float" />
<description>
- Natural logarithm. The amount of time needed to reach a certain level of continuous growth.
+ Returns the natural logarithm of [param x]. This is the amount of time needed to reach a certain level of continuous growth.
[b]Note:[/b] This is not the same as the "log" function on most calculators, which uses a base 10 logarithm.
[codeblock]
log(10) # Returns 2.302585
@@ -588,7 +596,7 @@
<method name="max" qualifiers="vararg">
<return type="Variant" />
<description>
- Returns the maximum of the given values. This method can take any number of arguments.
+ Returns the maximum of the given values. This function can take any number of arguments.
[codeblock]
max(1, 7, 3, -6, 5) # Returns 7
[/codeblock]
@@ -599,9 +607,9 @@
<param index="0" name="a" type="float" />
<param index="1" name="b" type="float" />
<description>
- Returns the maximum of two float values.
+ Returns the maximum of two [float] values.
[codeblock]
- maxf(3.6, 24) # Returns 24.0
+ maxf(3.6, 24) # Returns 24.0
maxf(-3.99, -4) # Returns -3.99
[/codeblock]
</description>
@@ -611,9 +619,9 @@
<param index="0" name="a" type="int" />
<param index="1" name="b" type="int" />
<description>
- Returns the maximum of two int values.
+ Returns the maximum of two [int] values.
[codeblock]
- maxi(1, 2) # Returns 2
+ maxi(1, 2) # Returns 2
maxi(-3, -4) # Returns -3
[/codeblock]
</description>
@@ -621,7 +629,7 @@
<method name="min" qualifiers="vararg">
<return type="Variant" />
<description>
- Returns the minimum of the given values. This method can take any number of arguments.
+ Returns the minimum of the given values. This function can take any number of arguments.
[codeblock]
min(1, 7, 3, -6, 5) # Returns -6
[/codeblock]
@@ -632,9 +640,9 @@
<param index="0" name="a" type="float" />
<param index="1" name="b" type="float" />
<description>
- Returns the minimum of two float values.
+ Returns the minimum of two [float] values.
[codeblock]
- minf(3.6, 24) # Returns 3.6
+ minf(3.6, 24) # Returns 3.6
minf(-3.99, -4) # Returns -4.0
[/codeblock]
</description>
@@ -644,9 +652,9 @@
<param index="0" name="a" type="int" />
<param index="1" name="b" type="int" />
<description>
- Returns the minimum of two int values.
+ Returns the minimum of two [int] values.
[codeblock]
- mini(1, 2) # Returns 1
+ mini(1, 2) # Returns 1
mini(-3, -4) # Returns -4
[/codeblock]
</description>
@@ -660,8 +668,8 @@
Moves [param from] toward [param to] by the [param delta] value.
Use a negative [param delta] value to move away.
[codeblock]
- move_toward(5, 10, 4) # Returns 9
- move_toward(10, 5, 4) # Returns 6
+ move_toward(5, 10, 4) # Returns 9
+ move_toward(10, 5, 4) # Returns 6
move_toward(10, 5, -1.5) # Returns 11.5
[/codeblock]
</description>
@@ -670,17 +678,17 @@
<return type="int" />
<param index="0" name="value" type="int" />
<description>
- Returns the nearest equal or larger power of 2 for integer [param value].
+ Returns the nearest equal or larger power of 2 for the integer [param value].
In other words, returns the smallest value [code]a[/code] where [code]a = pow(2, n)[/code] such that [code]value &lt;= a[/code] for some non-negative integer [code]n[/code].
[codeblock]
nearest_po2(3) # Returns 4
nearest_po2(4) # Returns 4
nearest_po2(5) # Returns 8
- nearest_po2(0) # Returns 0 (this may not be what you expect)
- nearest_po2(-1) # Returns 0 (this may not be what you expect)
+ nearest_po2(0) # Returns 0 (this may not be expected)
+ nearest_po2(-1) # Returns 0 (this may not be expected)
[/codeblock]
- [b]Warning:[/b] Due to the way it is implemented, this function returns [code]0[/code] rather than [code]1[/code] for non-positive values of [param value] (in reality, 1 is the smallest integer power of 2).
+ [b]Warning:[/b] Due to the way it is implemented, this function returns [code]0[/code] rather than [code]1[/code] for negative values of [param value] (in reality, 1 is the smallest integer power of 2).
</description>
</method>
<method name="pingpong">
@@ -688,18 +696,18 @@
<param index="0" name="value" type="float" />
<param index="1" name="length" type="float" />
<description>
- Returns the [param value] wrapped between [code]0[/code] and the [param length]. If the limit is reached, the next value the function returned is decreased to the [code]0[/code] side or increased to the [param length] side (like a triangle wave). If [param length] is less than zero, it becomes positive.
+ Wraps [param value] between [code]0[/code] and the [param length]. If the limit is reached, the next value the function returns is decreased to the [code]0[/code] side or increased to the [param length] side (like a triangle wave). If [param length] is less than zero, it becomes positive.
[codeblock]
- pingpong(-3.0, 3.0) # Returns 3
- pingpong(-2.0, 3.0) # Returns 2
- pingpong(-1.0, 3.0) # Returns 1
- pingpong(0.0, 3.0) # Returns 0
- pingpong(1.0, 3.0) # Returns 1
- pingpong(2.0, 3.0) # Returns 2
- pingpong(3.0, 3.0) # Returns 3
- pingpong(4.0, 3.0) # Returns 2
- pingpong(5.0, 3.0) # Returns 1
- pingpong(6.0, 3.0) # Returns 0
+ pingpong(-3.0, 3.0) # Returns 3.0
+ pingpong(-2.0, 3.0) # Returns 2.0
+ pingpong(-1.0, 3.0) # Returns 1.0
+ pingpong(0.0, 3.0) # Returns 0.0
+ pingpong(1.0, 3.0) # Returns 1.0
+ pingpong(2.0, 3.0) # Returns 2.0
+ pingpong(3.0, 3.0) # Returns 3.0
+ pingpong(4.0, 3.0) # Returns 2.0
+ pingpong(5.0, 3.0) # Returns 1.0
+ pingpong(6.0, 3.0) # Returns 0.0
[/codeblock]
</description>
</method>
@@ -708,20 +716,22 @@
<param index="0" name="x" type="int" />
<param index="1" name="y" type="int" />
<description>
- Returns the integer modulus of [code]x/y[/code] that wraps equally in positive and negative.
+ Returns the integer modulus of [param x] divided by [param y] that wraps equally in positive and negative.
[codeblock]
+ print("#(i) (i % 3) (posmod(i, 3))")
for i in range(-3, 4):
- print("%2d %2d %2d" % [i, i % 3, posmod(i, 3)])
+ print("%2d %2d | %2d" % [i, i % 3, posmod(i, 3)])
[/codeblock]
Produces:
[codeblock]
- -3 0 0
- -2 -2 1
- -1 -1 2
- 0 0 0
- 1 1 1
- 2 2 2
- 3 0 0
+ (i) (i % 3) (posmod(i, 3))
+ -3 0 | 0
+ -2 -2 | 1
+ -1 -1 | 2
+ 0 0 | 0
+ 1 1 | 1
+ 2 2 | 2
+ 3 0 | 0
[/codeblock]
</description>
</method>
@@ -731,6 +741,7 @@
<param index="1" name="exp" type="float" />
<description>
Returns the result of [param base] raised to the power of [param exp].
+ In GDScript, this is the equivalent of the [code]**[/code] operator.
[codeblock]
pow(2, 5) # Returns 32
[/codeblock]
@@ -743,7 +754,7 @@
var a = [1, 2, 3]
print("a", "b", a) # Prints ab[1, 2, 3]
[/codeblock]
- [b]Note:[/b] Consider using [method push_error] and [method push_warning] to print error and warning messages instead of [method print]. This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed.
+ [b]Note:[/b] Consider using [method push_error] and [method push_warning] to print error and warning messages instead of [method print] or [method print_rich]. This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed.
</description>
</method>
<method name="print_rich" qualifiers="vararg">
@@ -771,11 +782,12 @@
</method>
<method name="printraw" qualifiers="vararg">
<description>
- Prints one or more arguments to strings in the best way possible to console. No newline is added at the end.
+ Prints one or more arguments to strings in the best way possible to console. Unlike [method print], no newline is automatically added at the end.
[codeblock]
printraw("A")
printraw("B")
- # Prints AB
+ printraw("C")
+ # Prints ABC
[/codeblock]
[b]Note:[/b] Due to limitations with Godot's built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as [method print].
</description>
@@ -802,7 +814,7 @@
[codeblock]
push_error("test error") # Prints "test error" to debugger and terminal as error call
[/codeblock]
- [b]Note:[/b] Errors printed this way will not pause project execution. To print an error message and pause project execution in debug builds, use [code]assert(false, "test error")[/code] instead.
+ [b]Note:[/b] This function does not pause project execution. To print an error message and pause project execution in debug builds, use [code]assert(false, "test error")[/code] instead.
</description>
</method>
<method name="push_warning" qualifiers="vararg">
@@ -820,6 +832,8 @@
Converts an angle expressed in radians to degrees.
[codeblock]
rad_to_deg(0.523599) # Returns 30
+ rad_to_deg(PI) # Returns 180
+ rad_to_deg(PI * 2) # Returns 360
[/codeblock]
</description>
</method>
@@ -827,7 +841,14 @@
<return type="PackedInt64Array" />
<param index="0" name="seed" type="int" />
<description>
- Random from seed: pass a [param seed], and an array with both number and new seed is returned. "Seed" here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits.
+ Given a [param seed], returns a [PackedInt64Array] of size [code]2[/code], where its first element is the randomised [int] value, and the second element is the same as [param seed]. Passing the same [param seed] consistently returns the same array.
+ [b]Note:[/b] "Seed" here refers to the internal state of the pseudo random number generator, currently implemented as a 64 bit integer.
+ [codeblock]
+ var a = rand_from_seed(4)
+
+ print(a[0]) # Prints 2879024997
+ print(a[1]) # Prints 4
+ [/codeblock]
</description>
</method>
<method name="randf">
@@ -844,9 +865,10 @@
<param index="0" name="from" type="float" />
<param index="1" name="to" type="float" />
<description>
- Returns a random floating point value on the interval between [param from] and [param to] (inclusive).
+ Returns a random floating point value between [param from] and [param to] (inclusive).
[codeblock]
- prints(randf_range(-10, 10), randf_range(-10, 10)) # Prints e.g. -3.844535 7.45315
+ randf_range(0, 20.5) # Returns e.g. 7.45315
+ randf_range(-10, 10) # Returns e.g. -3.844535
[/codeblock]
</description>
</method>
@@ -877,15 +899,15 @@
<description>
Returns a random signed 32-bit integer between [param from] and [param to] (inclusive). If [param to] is lesser than [param from], they are swapped.
[codeblock]
- print(randi_range(0, 1)) # Prints 0 or 1
- print(randi_range(-10, 1000)) # Prints any number from -10 to 1000
+ randi_range(0, 1) # Returns either 0 or 1
+ randi_range(-10, 1000) # Returns random integer between -10 and 1000
[/codeblock]
</description>
</method>
<method name="randomize">
<description>
- Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time.
- [b]Note:[/b] This method is called automatically when the project is run. If you need to fix the seed to have reproducible results, use [method seed] to initialize the random number generator.
+ Randomizes the seed (or the internal state) of the random number generator. The current implementation uses a number based on the device's time.
+ [b]Note:[/b] This function is called automatically when the project is run. If you need to fix the seed to have consistent, reproducible results, use [method seed] to initialize the random number generator.
</description>
</method>
<method name="remap">
@@ -896,63 +918,67 @@
<param index="3" name="ostart" type="float" />
<param index="4" name="ostop" type="float" />
<description>
- Maps a [param value] from range [code][istart, istop][/code] to [code][ostart, ostop][/code]. See also [method lerp] and [method inverse_lerp]. If [param value] is outside [code][istart, istop][/code], then the resulting value will also be outside [code][ostart, ostop][/code]. Use [method clamp] on the result of [method remap] if this is not desired.
+ Maps a [param value] from range [code][istart, istop][/code] to [code][ostart, ostop][/code]. See also [method lerp] and [method inverse_lerp]. If [param value] is outside [code][istart, istop][/code], then the resulting value will also be outside [code][ostart, ostop][/code]. If this is not desired, use [method clamp] on the result of this function.
[codeblock]
remap(75, 0, 100, -1, 1) # Returns 0.5
[/codeblock]
- For complex use cases where you need multiple ranges, consider using [Curve] or [Gradient] instead.
+ For complex use cases where multiple ranges are needed, consider using [Curve] or [Gradient] instead.
</description>
</method>
<method name="rid_allocate_id">
<return type="int" />
<description>
- Allocate a unique ID which can be used by the implementation to construct a RID. This is used mainly from native extensions to implement servers.
+ Allocates a unique ID which can be used by the implementation to construct a RID. This is used mainly from native extensions to implement servers.
</description>
</method>
<method name="rid_from_int64">
<return type="RID" />
<param index="0" name="base" type="int" />
<description>
- Create a RID from an int64. This is used mainly from native extensions to build servers.
+ Creates a RID from a [param base]. This is used mainly from native extensions to build servers.
</description>
</method>
<method name="round">
<return type="Variant" />
<param index="0" name="x" type="Variant" />
<description>
- Rounds [param x] to the nearest whole number, with halfway cases rounded away from zero. Supported types: [int], [float], [Vector2], [Vector3], [Vector4].
+ Rounds [param x] to the nearest whole number, with halfway cases rounded away from 0. Supported types: [int], [float], [Vector2], [Vector3], [Vector4].
[codeblock]
round(2.4) # Returns 2
round(2.5) # Returns 3
round(2.6) # Returns 3
[/codeblock]
See also [method floor], [method ceil], and [method snapped].
- [b]Note:[/b] For better type safety, you can use [method roundf], [method roundi], [method Vector2.round], [method Vector3.round] or [method Vector4.round] instead.
+ [b]Note:[/b] For better type safety, use [method roundf], [method roundi], [method Vector2.round], [method Vector3.round] or [method Vector4.round], instead.
</description>
</method>
<method name="roundf">
<return type="float" />
<param index="0" name="x" type="float" />
<description>
- Rounds [param x] to the nearest whole number, with halfway cases rounded away from zero.
- A type-safe version of [method round], specialzied in floats.
+ Rounds [param x] to the nearest whole number, with halfway cases rounded away from 0.
+ A type-safe version of [method round], returning a [float].
</description>
</method>
<method name="roundi">
<return type="int" />
<param index="0" name="x" type="float" />
<description>
- Rounds [param x] to the nearest whole number, with halfway cases rounded away from zero.
- A type-safe version of [method round] that returns integer.
+ Rounds [param x] to the nearest whole number, with halfway cases rounded away from 0.
+ A type-safe version of [method round], returning an [int].
</description>
</method>
<method name="seed">
<param index="0" name="base" type="int" />
<description>
- Sets seed for the random number generator.
+ Sets the seed for the random number generator to [param base]. Setting the seed manually can ensure consistent, repeatable results for most random functions.
[codeblock]
- var my_seed = "Godot Rocks"
- seed(my_seed.hash())
+ var my_seed = "Godot Rocks".hash()
+ seed(my_seed)
+ var a = randf() + randi()
+ seed(my_seed)
+ var b = randf() + randi()
+ # a and b are now identical
[/codeblock]
</description>
</method>
@@ -960,7 +986,7 @@
<return type="Variant" />
<param index="0" name="x" type="Variant" />
<description>
- Returns the sign of [param x] as same type of [Variant] as [param x] with each component being -1, 0 and 1 for each negative, zero and positive values respectivelu. Variant types [int], [float] (real), [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
+ Returns the sign of [param x] as same type of [Variant] as [param x] with each component being -1, 0 and 1 for each negative, zero and positive values respectively. Variant types [int], [float], [Vector2], [Vector2i], [Vector3] and [Vector3i] are supported.
[codeblock]
sign(-6.0) # Returns -1
sign(0.0) # Returns 0
@@ -974,11 +1000,11 @@
<return type="float" />
<param index="0" name="x" type="float" />
<description>
- Returns the sign of [param x] as a float: -1.0 or 1.0. Returns 0.0 if [param x] is 0.
+ Returns the sign of [param x] as a [float]: -1.0 or 1.0. Returns 0.0 if [param x] is 0.0.
[codeblock]
- sign(-6.0) # Returns -1.0
+ sign(-6.5) # Returns -1.0
sign(0.0) # Returns 0.0
- sign(6.0) # Returns 1.0
+ sign(6.5) # Returns 1.0
[/codeblock]
</description>
</method>
@@ -986,7 +1012,7 @@
<return type="int" />
<param index="0" name="x" type="int" />
<description>
- Returns the sign of [param x] as an integer: -1 or 1. Returns 0 if [param x] is 0.
+ Returns the sign of [param x] as an [int]: -1 or 1. Returns 0 if [param x] is 0.
[codeblock]
sign(-6) # Returns -1
sign(0) # Returns 0
@@ -1040,7 +1066,7 @@
<param index="0" name="x" type="float" />
<param index="1" name="step" type="float" />
<description>
- Snaps float value [param x] to a given [param step]. This can also be used to round a floating point number to an arbitrary number of decimals.
+ Snaps the float value [param x] to a given [param step]. This can also be used to round a floating point number to an arbitrary number of decimals.
[codeblock]
snapped(100, 32) # Returns 96
snapped(3.14159, 0.01) # Returns 3.14
@@ -1054,9 +1080,11 @@
<description>
Returns the square root of [param x], where [param x] is a non-negative number.
[codeblock]
- sqrt(9) # Returns 3
+ sqrt(9) # Returns 3
+ sqrt(10.24) # Returns 3.2
+ sqrt(-1) # Returns NaN
[/codeblock]
- [b]Note:[/b] Negative values of [param x] return NaN. If you need negative inputs, use [code]System.Numerics.Complex[/code] in C#.
+ [b]Note:[/b] Negative values of [param x] return NaN ("Not a Number"). in C#, if you need negative inputs, use [code]System.Numerics.Complex[/code].
</description>
</method>
<method name="step_decimals">
@@ -1065,30 +1093,27 @@
<description>
Returns the position of the first non-zero digit, after the decimal point. Note that the maximum return value is 10, which is a design decision in the implementation.
[codeblock]
- # n is 0
- var n = step_decimals(5)
- # n is 4
- n = step_decimals(1.0005)
- # n is 9
- n = step_decimals(0.000000005)
+ var n = step_decimals(5) # n is 0
+ n = step_decimals(1.0005) # n is 4
+ n = step_decimals(0.000000005) # n is 9
[/codeblock]
</description>
</method>
<method name="str" qualifiers="vararg">
<return type="String" />
<description>
- Converts one or more arguments of any type to string in the best way possible.
+ Converts one or more arguments of any [Variant] type to [String] in the best way possible.
</description>
</method>
<method name="str_to_var">
<return type="Variant" />
<param index="0" name="string" type="String" />
<description>
- Converts a formatted [param string] that was returned by [method var_to_str] to the original value.
+ Converts a formatted [param string] that was returned by [method var_to_str] to the original [Variant].
[codeblock]
- var a = '{ "a": 1, "b": 2 }'
- var b = str_to_var(a)
- print(b["a"]) # Prints 1
+ var a = '{ "a": 1, "b": 2 }' # a is a String
+ var b = str_to_var(a) # b is a Dictionary
+ print(b["a"]) # Prints 1
[/codeblock]
</description>
</method>
@@ -1109,7 +1134,7 @@
Returns the hyperbolic tangent of [param x].
[codeblock]
var a = log(2.0) # Returns 0.693147
- tanh(a) # Returns 0.6
+ tanh(a) # Returns 0.6
[/codeblock]
</description>
</method>
@@ -1117,7 +1142,7 @@
<return type="int" />
<param index="0" name="variable" type="Variant" />
<description>
- Returns the internal type of the given Variant object, using the [enum Variant.Type] values.
+ Returns the internal type of the given [param variable], using the [enum Variant.Type] values.
[codeblock]
var json = JSON.new()
json.parse('["a", "b", "c"]')
@@ -1141,19 +1166,19 @@
<return type="PackedByteArray" />
<param index="0" name="variable" type="Variant" />
<description>
- Encodes a [Variant] value to a byte array. Encoding objects is allowed (and can potentially include code). Deserialization can be done with [method bytes_to_var_with_objects].
+ Encodes a [Variant] value to a byte array. Encoding objects is allowed (and can potentially include executable code). Deserialization can be done with [method bytes_to_var_with_objects].
</description>
</method>
<method name="var_to_str">
<return type="String" />
<param index="0" name="variable" type="Variant" />
<description>
- Converts a Variant [param variable] to a formatted string that can later be parsed using [method str_to_var].
+ Converts a [Variant] [param variable] to a formatted [String] that can then be parsed using [method str_to_var].
[codeblock]
a = { "a": 1, "b": 2 }
print(var_to_str(a))
[/codeblock]
- prints
+ Prints:
[codeblock]
{
"a": 1,
@@ -1166,7 +1191,7 @@
<return type="Variant" />
<param index="0" name="obj" type="Variant" />
<description>
- Returns a weak reference to an object, or [code]null[/code] if the argument is invalid.
+ Returns a weak reference to an object, or [code]null[/code] if [param obj] is invalid.
A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
</description>
</method>
@@ -1176,9 +1201,8 @@
<param index="1" name="min" type="Variant" />
<param index="2" name="max" type="Variant" />
<description>
- Wraps the [Variant] [param value] between [param min] and [param max].
- Usable for creating loop-alike behavior or infinite surfaces.
- Variant types [int] and [float] (real) are supported. If any of the argument is [float] the result will be [float], otherwise it is [int].
+ Wraps the [Variant] [param value] between [param min] and [param max]. Can be used for creating loop-alike behavior or infinite surfaces.
+ Variant types [int] and [float] are supported. If any of the arguments is [float] this function returns a [float], otherwise it returns an [int].
[codeblock]
var a = wrap(4, 5, 10)
# a is 9 (int)
@@ -1197,8 +1221,7 @@
<param index="1" name="min" type="float" />
<param index="2" name="max" type="float" />
<description>
- Wraps float [param value] between [param min] and [param max].
- Usable for creating loop-alike behavior or infinite surfaces.
+ Wraps the float [param value] between [param min] and [param max]. Can be used for creating loop-alike behavior or infinite surfaces.
[codeblock]
# Infinite loop between 5.0 and 9.9
value = wrapf(value + 0.1, 5.0, 10.0)
@@ -1221,8 +1244,7 @@
<param index="1" name="min" type="int" />
<param index="2" name="max" type="int" />
<description>
- Wraps integer [param value] between [param min] and [param max].
- Usable for creating loop-alike behavior or infinite surfaces.
+ Wraps the integer [param value] between [param min] and [param max]. Can be used for creating loop-alike behavior or infinite surfaces.
[codeblock]
# Infinite loop between 5 and 9
frame = wrapi(frame + 1, 5, 10)
@@ -1283,6 +1305,7 @@
The [Marshalls] singleton.
</member>
<member name="NativeExtensionManager" type="NativeExtensionManager" setter="" getter="">
+ The [NativeExtensionManager] singleton.
</member>
<member name="NavigationMeshGenerator" type="NavigationMeshGenerator" setter="" getter="">
The [NavigationMeshGenerator] singleton.
@@ -1377,8 +1400,10 @@
General horizontal alignment, usually used for [Separator], [ScrollBar], [Slider], etc.
</constant>
<constant name="CLOCKWISE" value="0" enum="ClockDirection">
+ Clockwise rotation. Used by some methods (e.g. [method Image.rotate_90]).
</constant>
<constant name="COUNTERCLOCKWISE" value="1" enum="ClockDirection">
+ Counter-clockwise rotation. Used by some methods (e.g. [method Image.rotate_90]).
</constant>
<constant name="HORIZONTAL_ALIGNMENT_LEFT" value="0" enum="HorizontalAlignment">
Horizontal left alignment, usually for text-derived classes.
@@ -1873,34 +1898,34 @@
/ key.
</constant>
<constant name="KEY_0" value="48" enum="Key">
- Number 0.
+ Number 0 key.
</constant>
<constant name="KEY_1" value="49" enum="Key">
- Number 1.
+ Number 1 key.
</constant>
<constant name="KEY_2" value="50" enum="Key">
- Number 2.
+ Number 2 key.
</constant>
<constant name="KEY_3" value="51" enum="Key">
- Number 3.
+ Number 3 key.
</constant>
<constant name="KEY_4" value="52" enum="Key">
- Number 4.
+ Number 4 key.
</constant>
<constant name="KEY_5" value="53" enum="Key">
- Number 5.
+ Number 5 key.
</constant>
<constant name="KEY_6" value="54" enum="Key">
- Number 6.
+ Number 6 key.
</constant>
<constant name="KEY_7" value="55" enum="Key">
- Number 7.
+ Number 7 key.
</constant>
<constant name="KEY_8" value="56" enum="Key">
- Number 8.
+ Number 8 key.
</constant>
<constant name="KEY_9" value="57" enum="Key">
- Number 9.
+ Number 9 key.
</constant>
<constant name="KEY_COLON" value="58" enum="Key">
: key.
@@ -2260,10 +2285,10 @@
Enum value which doesn't correspond to any mouse button. This is used to initialize [enum MouseButton] properties with a generic state.
</constant>
<constant name="MOUSE_BUTTON_LEFT" value="1" enum="MouseButton">
- Primary mouse button, usually the left button.
+ Primary mouse button, usually assigned to the left button.
</constant>
<constant name="MOUSE_BUTTON_RIGHT" value="2" enum="MouseButton">
- Secondary mouse button, usually the right button.
+ Secondary mouse button, usually assigned to the right button.
</constant>
<constant name="MOUSE_BUTTON_MIDDLE" value="3" enum="MouseButton">
Middle mouse button.
@@ -2281,10 +2306,10 @@
Mouse wheel right button (only present on some mice).
</constant>
<constant name="MOUSE_BUTTON_XBUTTON1" value="8" enum="MouseButton">
- Extra mouse button 1 (only present on some mice).
+ Extra mouse button 1. This is sometimes present, usually to the sides of the mouse.
</constant>
<constant name="MOUSE_BUTTON_XBUTTON2" value="9" enum="MouseButton">
- Extra mouse button 2 (only present on some mice).
+ Extra mouse button 2. This is sometimes present, usually to the sides of the mouse.
</constant>
<constant name="MOUSE_BUTTON_MASK_LEFT" value="1" enum="MouseButton">
Primary mouse button mask, usually for the left button.
@@ -2350,7 +2375,7 @@
Game controller D-pad right button.
</constant>
<constant name="JOY_BUTTON_MISC1" value="15" enum="JoyButton">
- Game controller SDL miscellaneous button. Corresponds to Xbox share button, PS5 microphone button, Nintendo capture button.
+ Game controller SDL miscellaneous button. Corresponds to Xbox share button, PS5 microphone button, Nintendo Switch capture button.
</constant>
<constant name="JOY_BUTTON_PADDLE1" value="16" enum="JoyButton">
Game controller SDL paddle 1 button.
@@ -2372,9 +2397,9 @@
</constant>
<constant name="JOY_BUTTON_MAX" value="128" enum="JoyButton">
The maximum number of game controller buttons supported by the engine. The actual limit may be lower on specific platforms:
- - Android: Up to 36 buttons.
- - Linux: Up to 80 buttons.
- - Windows and macOS: Up to 128 buttons.
+ - [b]Android:[/b] Up to 36 buttons.
+ - [b]Linux:[/b] Up to 80 buttons.
+ - [b]Windows[/b] and [b]macOS:[/b] Up to 128 buttons.
</constant>
<constant name="JOY_AXIS_INVALID" value="-1" enum="JoyAxis">
An invalid game controller axis.
@@ -2461,16 +2486,18 @@
MIDI system reset message. Reset all receivers in the system to power-up status. It should not be sent on power-up itself.
</constant>
<constant name="OK" value="0" enum="Error">
- Methods that return [enum Error] return [constant OK] when no error occurred. Note that many functions don't return an error code but will print error messages to standard output.
- Since [constant OK] has value 0, and all other failure codes are positive integers, it can also be used in boolean checks, e.g.:
+ Methods that return [enum Error] return [constant OK] when no error occurred.
+ Since [constant OK] has value 0, and all other error constants are positive integers, it can also be used in boolean checks. For example:
[codeblock]
- var err = method_that_returns_error()
- if err != OK:
- print("Failure!")
- # Or, equivalent:
- if err:
- print("Still failing!")
+ var error = method_that_returns_error()
+ if error != OK:
+ printerr("Failure!")
+
+ # Or, alternatively:
+ if error:
+ printerr("Still failing!")
[/codeblock]
+ [b]Note:[/b] Many functions do not return an error code, but will print error messages to standard output.
</constant>
<constant name="FAILED" value="1" enum="Error">
Generic error.
@@ -2608,100 +2635,101 @@
Skip error.
</constant>
<constant name="ERR_HELP" value="46" enum="Error">
- Help error.
+ Help error. Used internally when passing [code]--version[/code] or [code]--help[/code] as executable options.
</constant>
<constant name="ERR_BUG" value="47" enum="Error">
- Bug error.
+ Bug error, caused by an implementation issue in the method.
+ [b]Note:[/b] If a built-in method returns this code, please open an issue on [url=https://github.com/godotengine/godot/issues]the GitHub Issue Tracker[/url].
</constant>
<constant name="ERR_PRINTER_ON_FIRE" value="48" enum="Error">
- Printer on fire error. (This is an easter egg, no engine methods return this error code.)
+ Printer on fire error (This is an easter egg, no built-in methods return this error code).
</constant>
<constant name="PROPERTY_HINT_NONE" value="0" enum="PropertyHint">
- No hint for the edited property.
+ The property has no hint for the editor.
</constant>
<constant name="PROPERTY_HINT_RANGE" value="1" enum="PropertyHint">
- Hints that an integer or float property should be within a range specified via the hint string [code]"min,max"[/code] or [code]"min,max,step"[/code]. The hint string can optionally include [code]"or_greater"[/code] and/or [code]"or_less"[/code] to allow manual input going respectively above the max or below the min values. Example: [code]"-360,360,1,or_greater,or_less"[/code].
+ Hints that an [int] or [float] property should be within a range specified via the hint string [code]"min,max"[/code] or [code]"min,max,step"[/code]. The hint string can optionally include [code]"or_greater"[/code] and/or [code]"or_less"[/code] to allow manual input going respectively above the max or below the min values. Example: [code]"-360,360,1,or_greater,or_less"[/code].
Additionally, other keywords can be included: [code]"exp"[/code] for exponential range editing, [code]"radians"[/code] for editing radian angles in degrees, [code]"degrees"[/code] to hint at an angle and [code]"hide_slider"[/code] to hide the slider.
</constant>
<constant name="PROPERTY_HINT_ENUM" value="2" enum="PropertyHint">
- Hints that an integer, float or string property is an enumerated value to pick in a list specified via a hint string.
+ Hints that an [int], [float], or [String] property is an enumerated value to pick in a list specified via a hint string.
The hint string is a comma separated list of names such as [code]"Hello,Something,Else"[/code]. Whitespaces are [b]not[/b] removed from either end of a name. For integer and float properties, the first name in the list has value 0, the next 1, and so on. Explicit values can also be specified by appending [code]:integer[/code] to the name, e.g. [code]"Zero,One,Three:3,Four,Six:6"[/code].
</constant>
<constant name="PROPERTY_HINT_ENUM_SUGGESTION" value="3" enum="PropertyHint">
- Hints that a string property can be an enumerated value to pick in a list specified via a hint string such as [code]"Hello,Something,Else"[/code].
- Unlike [constant PROPERTY_HINT_ENUM] a property with this hint still accepts arbitrary values and can be empty. The list of values serves to suggest possible values.
+ Hints that a [String] property can be an enumerated value to pick in a list specified via a hint string such as [code]"Hello,Something,Else"[/code].
+ Unlike [constant PROPERTY_HINT_ENUM], a property with this hint still accepts arbitrary values and can be empty. The list of values serves to suggest possible values.
</constant>
<constant name="PROPERTY_HINT_EXP_EASING" value="4" enum="PropertyHint">
- Hints that a float property should be edited via an exponential easing function. The hint string can include [code]"attenuation"[/code] to flip the curve horizontally and/or [code]"positive_only"[/code] to exclude in/out easing and limit values to be greater than or equal to zero.
+ Hints that a [float] property should be edited via an exponential easing function. The hint string can include [code]"attenuation"[/code] to flip the curve horizontally and/or [code]"positive_only"[/code] to exclude in/out easing and limit values to be greater than or equal to zero.
</constant>
<constant name="PROPERTY_HINT_LINK" value="5" enum="PropertyHint">
- Hints that a vector property should allow linking values (e.g. to edit both [code]x[/code] and [code]y[/code] together).
+ Hints that a vector property should allow its components to be linked. For example, this allows [member Vector2.x] and [member Vector2.y] to be edited together.
</constant>
<constant name="PROPERTY_HINT_FLAGS" value="6" enum="PropertyHint">
- Hints that an integer property is a bitmask with named bit flags. For example, to allow toggling bits 0, 1, 2 and 4, the hint could be something like [code]"Bit0,Bit1,Bit2,,Bit4"[/code].
+ Hints that an [int] property is a bitmask with named bit flags. For example, to allow toggling bits 0, 1, 2 and 4, the hint could be something like [code]"Bit0,Bit1,Bit2,,Bit4"[/code].
</constant>
<constant name="PROPERTY_HINT_LAYERS_2D_RENDER" value="7" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 2D render layers.
+ Hints that an [int] property is a bitmask using the optionally named 2D render layers.
</constant>
<constant name="PROPERTY_HINT_LAYERS_2D_PHYSICS" value="8" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 2D physics layers.
+ Hints that an [int] property is a bitmask using the optionally named 2D physics layers.
</constant>
<constant name="PROPERTY_HINT_LAYERS_2D_NAVIGATION" value="9" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 2D navigation layers.
+ Hints that an [int] property is a bitmask using the optionally named 2D navigation layers.
</constant>
<constant name="PROPERTY_HINT_LAYERS_3D_RENDER" value="10" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 3D render layers.
+ Hints that an [int] property is a bitmask using the optionally named 3D render layers.
</constant>
<constant name="PROPERTY_HINT_LAYERS_3D_PHYSICS" value="11" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 3D physics layers.
+ Hints that an [int] property is a bitmask using the optionally named 3D physics layers.
</constant>
<constant name="PROPERTY_HINT_LAYERS_3D_NAVIGATION" value="12" enum="PropertyHint">
- Hints that an integer property is a bitmask using the optionally named 3D navigation layers.
+ Hints that an [int] property is a bitmask using the optionally named 3D navigation layers.
</constant>
<constant name="PROPERTY_HINT_FILE" value="13" enum="PropertyHint">
- Hints that a string property is a path to a file. Editing it will show a file dialog for picking the path. The hint string can be a set of filters with wildcards like [code]"*.png,*.jpg"[/code].
+ Hints that a [String] property is a path to a file. Editing it will show a file dialog for picking the path. The hint string can be a set of filters with wildcards like [code]"*.png,*.jpg"[/code].
</constant>
<constant name="PROPERTY_HINT_DIR" value="14" enum="PropertyHint">
- Hints that a string property is a path to a directory. Editing it will show a file dialog for picking the path.
+ Hints that a [String] property is a path to a directory. Editing it will show a file dialog for picking the path.
</constant>
<constant name="PROPERTY_HINT_GLOBAL_FILE" value="15" enum="PropertyHint">
- Hints that a string property is an absolute path to a file outside the project folder. Editing it will show a file dialog for picking the path. The hint string can be a set of filters with wildcards like [code]"*.png,*.jpg"[/code].
+ Hints that a [String] property is an absolute path to a file outside the project folder. Editing it will show a file dialog for picking the path. The hint string can be a set of filters with wildcards, like [code]"*.png,*.jpg"[/code].
</constant>
<constant name="PROPERTY_HINT_GLOBAL_DIR" value="16" enum="PropertyHint">
- Hints that a string property is an absolute path to a directory outside the project folder. Editing it will show a file dialog for picking the path.
+ Hints that a [String] property is an absolute path to a directory outside the project folder. Editing it will show a file dialog for picking the path.
</constant>
<constant name="PROPERTY_HINT_RESOURCE_TYPE" value="17" enum="PropertyHint">
Hints that a property is an instance of a [Resource]-derived type, optionally specified via the hint string (e.g. [code]"Texture2D"[/code]). Editing it will show a popup menu of valid resource types to instantiate.
</constant>
<constant name="PROPERTY_HINT_MULTILINE_TEXT" value="18" enum="PropertyHint">
- Hints that a string property is text with line breaks. Editing it will show a text input field where line breaks can be typed.
+ Hints that a [String] property is text with line breaks. Editing it will show a text input field where line breaks can be typed.
</constant>
<constant name="PROPERTY_HINT_EXPRESSION" value="19" enum="PropertyHint">
- Hints that a string property is an [Expression].
+ Hints that a [String] property is an [Expression].
</constant>
<constant name="PROPERTY_HINT_PLACEHOLDER_TEXT" value="20" enum="PropertyHint">
- Hints that a string property should have a placeholder text visible on its input field, whenever the property is empty. The hint string is the placeholder text to use.
+ Hints that a [String] property should show a placeholder text on its input field, if empty. The hint string is the placeholder text to use.
</constant>
<constant name="PROPERTY_HINT_COLOR_NO_ALPHA" value="21" enum="PropertyHint">
- Hints that a color property should be edited without changing its alpha component, i.e. only R, G and B channels are edited.
+ Hints that a [Color] property should be edited without affecting its transparency ([member Color.a] is not editable).
</constant>
<constant name="PROPERTY_HINT_IMAGE_COMPRESS_LOSSY" value="22" enum="PropertyHint">
- Hints that an image is compressed using lossy compression.
+ Hints that an image is compressed using lossy compression. The editor does not internally use this property hint.
</constant>
<constant name="PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS" value="23" enum="PropertyHint">
- Hints that an image is compressed using lossless compression.
+ Hints that an image is compressed using lossless compression. The editor does not internally use this property hint.
</constant>
<constant name="PROPERTY_HINT_OBJECT_ID" value="24" enum="PropertyHint">
</constant>
<constant name="PROPERTY_HINT_TYPE_STRING" value="25" enum="PropertyHint">
- Hint that a property represents a particular type. If a property is [constant TYPE_STRING], allows to set a type from the create dialog. If you need to create an [Array] to contain elements of a specific type, the [code]hint_string[/code] must encode nested types using [code]":"[/code] and [code]"/"[/code] for specifying [Resource] types. For instance:
+ Hints that a property represents a particular type. If a property is [constant TYPE_STRING], allows to set a type from the create dialog. If you need to create an [Array] to contain elements of a specific type, the [code]hint_string[/code] must encode nested types using [code]":"[/code] and [code]"/"[/code] for specifying [Resource] types. For example:
[codeblock]
- hint_string = "%s:" % [TYPE_INT] # Array of inteters.
+ hint_string = "%s:" % [TYPE_INT] # Array of integers.
hint_string = "%s:%s:" % [TYPE_ARRAY, TYPE_REAL] # Two-dimensional array of floats.
hint_string = "%s/%s:Resource" % [TYPE_OBJECT, TYPE_OBJECT] # Array of resources.
hint_string = "%s:%s/%s:Resource" % [TYPE_ARRAY, TYPE_OBJECT, TYPE_OBJECT] # Two-dimensional array of resources.
[/codeblock]
- [b]Note:[/b] The final colon is required to specify for properly detecting built-in types.
+ [b]Note:[/b] The final colon is required for properly detecting built-in types.
</constant>
<constant name="PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE" value="26" enum="PropertyHint">
</constant>
@@ -2722,6 +2750,7 @@
<constant name="PROPERTY_HINT_PROPERTY_OF_SCRIPT" value="34" enum="PropertyHint">
</constant>
<constant name="PROPERTY_HINT_OBJECT_TOO_BIG" value="35" enum="PropertyHint">
+ Hints that a property's size (in bytes) is too big to be displayed, when debugging a running project. The debugger uses this hint internally.
</constant>
<constant name="PROPERTY_HINT_NODE_PATH_VALID_TYPES" value="36" enum="PropertyHint">
</constant>
@@ -2736,28 +2765,31 @@
<constant name="PROPERTY_HINT_ARRAY_TYPE" value="40" enum="PropertyHint">
</constant>
<constant name="PROPERTY_HINT_LOCALE_ID" value="42" enum="PropertyHint">
- Hints that a string property is a locale code. Editing it will show a locale dialog for picking language and country.
+ Hints that a [String] property is a locale code. Editing it will show a locale dialog for picking language and country.
</constant>
<constant name="PROPERTY_HINT_LOCALIZABLE_STRING" value="43" enum="PropertyHint">
- Hints that a dictionary property is string translation map. Dictionary keys are locale codes and, values are translated strings.
+ Hints that a [Dictionary] property is string translation map. Dictionary keys are locale codes and, values are translated strings.
</constant>
<constant name="PROPERTY_HINT_NODE_TYPE" value="44" enum="PropertyHint">
</constant>
<constant name="PROPERTY_HINT_HIDE_QUATERNION_EDIT" value="45" enum="PropertyHint">
- Hints that a quaternion property should disable the temporary euler editor.
+ Hints that a [Quaternion] property should disable the temporary euler editor.
</constant>
<constant name="PROPERTY_HINT_PASSWORD" value="46" enum="PropertyHint">
- Hints that a string property is a password, and every character is replaced with the secret character.
+ Hints that a [String] property is a password. Every character of the string is displayed as the secret character (typically [code]*[/code]).
+ An optional placeholder text can be shown on its input field, similarly to [constant PROPERTY_HINT_PLACEHOLDER_TEXT].
</constant>
<constant name="PROPERTY_HINT_MAX" value="47" enum="PropertyHint">
+ Represents the size of the [enum PropertyHint] enum.
</constant>
<constant name="PROPERTY_USAGE_NONE" value="0" enum="PropertyUsageFlags">
+ The property is not stored, and does not display in the editor. This is the default for non-exported properties.
</constant>
<constant name="PROPERTY_USAGE_STORAGE" value="2" enum="PropertyUsageFlags">
The property is serialized and saved in the scene file (default).
</constant>
<constant name="PROPERTY_USAGE_EDITOR" value="4" enum="PropertyUsageFlags">
- The property is shown in the editor inspector (default).
+ The property is shown in the editor Inspector (default).
</constant>
<constant name="PROPERTY_USAGE_CHECKABLE" value="8" enum="PropertyUsageFlags">
The property can be checked in the editor inspector.
@@ -2803,8 +2835,10 @@
<constant name="PROPERTY_USAGE_INTERNAL" value="524288" enum="PropertyUsageFlags">
</constant>
<constant name="PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE" value="1048576" enum="PropertyUsageFlags">
+ If the property is a [Resource], a new copy of it is always created when calling [method Node.duplicate] or [method Resource.duplicate].
</constant>
<constant name="PROPERTY_USAGE_HIGH_END_GFX" value="2097152" enum="PropertyUsageFlags">
+ The property is only shown in the editor if modern renderers are supported (GLES3 is excluded).
</constant>
<constant name="PROPERTY_USAGE_NODE_PATH_FROM_SCENE_ROOT" value="4194304" enum="PropertyUsageFlags">
</constant>
@@ -2819,9 +2853,10 @@
<constant name="PROPERTY_USAGE_EDITOR_BASIC_SETTING" value="134217728" enum="PropertyUsageFlags">
</constant>
<constant name="PROPERTY_USAGE_READ_ONLY" value="268435456" enum="PropertyUsageFlags">
- The property is read-only in the editor inspector.
+ The property is read-only in the editor Inspector.
</constant>
<constant name="PROPERTY_USAGE_ARRAY" value="536870912" enum="PropertyUsageFlags">
+ The property is an array.
</constant>
<constant name="PROPERTY_USAGE_DEFAULT" value="6" enum="PropertyUsageFlags">
Default usage (storage, editor and network).
@@ -2845,14 +2880,16 @@
Flag for a virtual method.
</constant>
<constant name="METHOD_FLAG_VARARG" value="16" enum="MethodFlags">
+ Flag for a method with a variable number of arguments.
</constant>
<constant name="METHOD_FLAG_STATIC" value="32" enum="MethodFlags">
+ Flag for a static method.
</constant>
<constant name="METHOD_FLAG_OBJECT_CORE" value="64" enum="MethodFlags">
- Used internally. Allows to not dump core virtuals such as [code]_notification[/code] to the JSON API.
+ Used internally. Allows to not dump core virtual methods (such as [method Object._notification]) to the JSON API.
</constant>
<constant name="METHOD_FLAGS_DEFAULT" value="1" enum="MethodFlags">
- Default method flags.
+ Default method flags (normal).
</constant>
<constant name="TYPE_NIL" value="0" enum="Variant.Type">
Variable is [code]null[/code].
@@ -2864,7 +2901,7 @@
Variable is of type [int].
</constant>
<constant name="TYPE_FLOAT" value="3" enum="Variant.Type">
- Variable is of type [float] (real).
+ Variable is of type [float].
</constant>
<constant name="TYPE_STRING" value="4" enum="Variant.Type">
Variable is of type [String].
@@ -2891,8 +2928,10 @@
Variable is of type [Transform2D].
</constant>
<constant name="TYPE_VECTOR4" value="12" enum="Variant.Type">
+ Variable is of type [Vector4].
</constant>
<constant name="TYPE_VECTOR4I" value="13" enum="Variant.Type">
+ Variable is of type [Vector4i].
</constant>
<constant name="TYPE_PLANE" value="14" enum="Variant.Type">
Variable is of type [Plane].
@@ -2910,6 +2949,7 @@
Variable is of type [Transform3D].
</constant>
<constant name="TYPE_PROJECTION" value="19" enum="Variant.Type">
+ Variable is of type [Projection].
</constant>
<constant name="TYPE_COLOR" value="20" enum="Variant.Type">
Variable is of type [Color].
diff --git a/doc/classes/AABB.xml b/doc/classes/AABB.xml
index 23dd41f275..ca454cafa3 100644
--- a/doc/classes/AABB.xml
+++ b/doc/classes/AABB.xml
@@ -188,6 +188,7 @@
<param index="0" name="from" type="Vector3" />
<param index="1" name="dir" type="Vector3" />
<description>
+ Returns [code]true[/code] if the given ray intersects with this [AABB]. Ray length is infinite.
</description>
</method>
<method name="intersects_segment" qualifiers="const">
@@ -205,6 +206,12 @@
Returns [code]true[/code] if this [AABB] and [param aabb] are approximately equal, by calling [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this [AABB] is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="merge" qualifiers="const">
<return type="AABB" />
<param index="0" name="with" type="AABB" />
diff --git a/doc/classes/AStar2D.xml b/doc/classes/AStar2D.xml
index 6e76df647e..2414b068e6 100644
--- a/doc/classes/AStar2D.xml
+++ b/doc/classes/AStar2D.xml
@@ -271,7 +271,7 @@
<return type="void" />
<param index="0" name="num_nodes" type="int" />
<description>
- Reserves space internally for [param num_nodes] points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity.
+ Reserves space internally for [param num_nodes] points, useful if you're adding a known large number of points at once, such as points on a grid. New capacity must be greater or equals to old capacity.
</description>
</method>
<method name="set_point_disabled">
diff --git a/doc/classes/AStar3D.xml b/doc/classes/AStar3D.xml
index 45b1019bab..4e8394195d 100644
--- a/doc/classes/AStar3D.xml
+++ b/doc/classes/AStar3D.xml
@@ -298,7 +298,7 @@
<return type="void" />
<param index="0" name="num_nodes" type="int" />
<description>
- Reserves space internally for [param num_nodes] points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity.
+ Reserves space internally for [param num_nodes] points. Useful if you're adding a known large number of points at once, such as points on a grid. New capacity must be greater or equals to old capacity.
</description>
</method>
<method name="set_point_disabled">
diff --git a/doc/classes/Animation.xml b/doc/classes/Animation.xml
index df0fb11ac7..008296713d 100644
--- a/doc/classes/Animation.xml
+++ b/doc/classes/Animation.xml
@@ -26,6 +26,7 @@
[/csharp]
[/codeblocks]
Animations are just data containers, and must be added to nodes such as an [AnimationPlayer] to be played back. Animation tracks have different types, each with its own set of dedicated methods. Check [enum TrackType] to see available types.
+ [b]Note:[/b] For 3D position/rotation/scale, using the dedicated [constant TYPE_POSITION_3D], [constant TYPE_ROTATION_3D] and [constant TYPE_SCALE_3D] track types instead of [constant TYPE_VALUE] is recommended for performance reasons.
</description>
<tutorials>
<link title="Animation documentation index">$DOCS_URL/tutorials/animation/index.html</link>
@@ -209,6 +210,7 @@
<param index="1" name="time" type="float" />
<param index="2" name="amount" type="float" />
<description>
+ Inserts a key in a given blend shape track. Returns the key index.
</description>
</method>
<method name="clear">
@@ -223,6 +225,8 @@
<param index="1" name="fps" type="int" default="120" />
<param index="2" name="split_tolerance" type="float" default="4.0" />
<description>
+ Compress the animation and all its tracks in-place. This will make [method track_is_compressed] return [code]true[/code] once called on this [Animation]. Compressed tracks require less memory to be played, and are designed to be used for complex 3D animations (such as cutscenes) imported from external 3D software. Compression is lossy, but the difference is usually not noticeable in real world conditions.
+ [b]Note:[/b] Compressed tracks have various limitations (such as not being editable from the editor), so only use compressed animations if you actually need them.
</description>
</method>
<method name="copy_track">
@@ -278,6 +282,7 @@
<param index="1" name="time" type="float" />
<param index="2" name="position" type="Vector3" />
<description>
+ Inserts a key in a given 3D position track. Returns the key index.
</description>
</method>
<method name="remove_track">
@@ -293,6 +298,7 @@
<param index="1" name="time" type="float" />
<param index="2" name="rotation" type="Quaternion" />
<description>
+ Inserts a key in a given 3D rotation track. Returns the key index.
</description>
</method>
<method name="scale_track_insert_key">
@@ -301,6 +307,7 @@
<param index="1" name="time" type="float" />
<param index="2" name="scale" type="Vector3" />
<description>
+ Inserts a key in a given 3D scale track. Returns the key index.
</description>
</method>
<method name="track_find_key" qualifiers="const">
@@ -385,6 +392,7 @@
<return type="bool" />
<param index="0" name="track_idx" type="int" />
<description>
+ Returns [code]true[/code] if the track is compressed, [code]false[/code] otherwise. See also [method compress].
</description>
</method>
<method name="track_is_enabled" qualifiers="const">
@@ -569,15 +577,19 @@
</signals>
<constants>
<constant name="TYPE_VALUE" value="0" enum="TrackType">
- Value tracks set values in node properties, but only those which can be Interpolated.
+ Value tracks set values in node properties, but only those which can be interpolated. For 3D position/rotation/scale, using the dedicated [constant TYPE_POSITION_3D], [constant TYPE_ROTATION_3D] and [constant TYPE_SCALE_3D] track types instead of [constant TYPE_VALUE] is recommended for performance reasons.
</constant>
<constant name="TYPE_POSITION_3D" value="1" enum="TrackType">
+ 3D position track (values are stored in [Vector3]s).
</constant>
<constant name="TYPE_ROTATION_3D" value="2" enum="TrackType">
+ 3D rotation track (values are stored in [Quaternion]s).
</constant>
<constant name="TYPE_SCALE_3D" value="3" enum="TrackType">
+ 3D scale track (values are stored in [Vector3]s).
</constant>
<constant name="TYPE_BLEND_SHAPE" value="4" enum="TrackType">
+ Blend shape track.
</constant>
<constant name="TYPE_METHOD" value="5" enum="TrackType">
Method tracks call functions with given arguments per key.
@@ -598,7 +610,7 @@
Linear interpolation.
</constant>
<constant name="INTERPOLATION_CUBIC" value="2" enum="InterpolationType">
- Cubic interpolation.
+ Cubic interpolation. This looks smoother than linear interpolation, but is more expensive to interpolate. Stick to [constant INTERPOLATION_LINEAR] for complex 3D animations imported from external software, even if it requires using a higher animation framerate in return.
</constant>
<constant name="INTERPOLATION_LINEAR_ANGLE" value="3" enum="InterpolationType">
Linear interpolation with shortest path rotation.
diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml
index b7ac1ff7f8..bf5ac7fa9e 100644
--- a/doc/classes/AnimationPlayer.xml
+++ b/doc/classes/AnimationPlayer.xml
@@ -242,7 +242,7 @@
The process notification in which to update animations.
</member>
<member name="playback_speed" type="float" setter="set_speed_scale" getter="get_speed_scale" default="1.0">
- The speed scaling ratio. For instance, if this value is 1, then the animation plays at normal speed. If it's 0.5, then it plays at half speed. If it's 2, then it plays at double speed.
+ The speed scaling ratio. For example, if this value is 1, then the animation plays at normal speed. If it's 0.5, then it plays at half speed. If it's 2, then it plays at double speed.
</member>
<member name="reset_on_save" type="bool" setter="set_reset_on_save_enabled" getter="is_reset_on_save_enabled" default="true">
This is used by the editor. If set to [code]true[/code], the scene will be saved with the effects of the reset animation (the animation with the key [code]"RESET"[/code]) applied as if it had been seeked to time 0, with the editor keeping the values that the scene had before saving.
@@ -268,6 +268,11 @@
[b]Note:[/b] This signal is not emitted if an animation is looping.
</description>
</signal>
+ <signal name="animation_libraries_updated">
+ <description>
+ Notifies when the animation libraries have changed.
+ </description>
+ </signal>
<signal name="animation_list_changed">
<description>
Notifies when an animation list is changed.
diff --git a/doc/classes/Area3D.xml b/doc/classes/Area3D.xml
index ce49be9bc1..ea8cab324d 100644
--- a/doc/classes/Area3D.xml
+++ b/doc/classes/Area3D.xml
@@ -110,11 +110,11 @@
<member name="reverb_bus_amount" type="float" setter="set_reverb_amount" getter="get_reverb_amount" default="0.0">
The degree to which this area applies reverb to its associated audio. Ranges from [code]0[/code] to [code]1[/code] with [code]0.1[/code] precision.
</member>
- <member name="reverb_bus_enable" type="bool" setter="set_use_reverb_bus" getter="is_using_reverb_bus" default="false">
+ <member name="reverb_bus_enabled" type="bool" setter="set_use_reverb_bus" getter="is_using_reverb_bus" default="false">
If [code]true[/code], the area applies reverb to its associated audio.
</member>
- <member name="reverb_bus_name" type="StringName" setter="set_reverb_bus" getter="get_reverb_bus" default="&amp;&quot;Master&quot;">
- The reverb bus name to use for this area's associated audio.
+ <member name="reverb_bus_name" type="StringName" setter="set_reverb_bus_name" getter="get_reverb_bus_name" default="&amp;&quot;Master&quot;">
+ The name of the reverb bus to use for this area's associated audio.
</member>
<member name="reverb_bus_uniformity" type="float" setter="set_reverb_uniformity" getter="get_reverb_uniformity" default="0.0">
The degree to which this area's reverb is a uniform effect. Ranges from [code]0[/code] to [code]1[/code] with [code]0.1[/code] precision.
diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml
index 047089c917..0f76639caf 100644
--- a/doc/classes/Array.xml
+++ b/doc/classes/Array.xml
@@ -58,6 +58,7 @@
<param index="2" name="class_name" type="StringName" />
<param index="3" name="script" type="Variant" />
<description>
+ Creates a typed array from the [param base] array. The base array can't be already typed. See [method set_typed] for more details.
</description>
</constructor>
<constructor name="Array">
@@ -315,16 +316,19 @@
<method name="get_typed_builtin" qualifiers="const">
<return type="int" />
<description>
+ Returns the [code]TYPE[/code] constant for a typed array. If the [Array] is not typed, returns [constant @GlobalScope.TYPE_NIL].
</description>
</method>
<method name="get_typed_class_name" qualifiers="const">
<return type="StringName" />
<description>
+ Returns a class name of a typed [Array] of type [constant @GlobalScope.TYPE_OBJECT].
</description>
</method>
<method name="get_typed_script" qualifiers="const">
<return type="Variant" />
<description>
+ Returns the script associated with a typed array tied to a class name.
</description>
</method>
<method name="has" qualifiers="const">
@@ -393,11 +397,13 @@
<method name="is_read_only" qualifiers="const">
<return type="bool" />
<description>
+ Returns [code]true[/code] if the array is read-only. See [method set_read_only]. Arrays are automatically read-only if declared with [code]const[/code] keyword.
</description>
</method>
<method name="is_typed" qualifiers="const">
<return type="bool" />
<description>
+ Returns [code]true[/code] if the array is typed. Typed arrays can only store elements of their associated type and provide type safety for the [code][][/code] operator. Methods of typed array still return [Variant].
</description>
</method>
<method name="map" qualifiers="const">
@@ -429,6 +435,16 @@
Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, [code]null[/code] is returned.
</description>
</method>
+ <method name="pick_random" qualifiers="const">
+ <return type="Variant" />
+ <description>
+ Returns a random value from the target array.
+ [codeblock]
+ var array: Array[int] = [1, 2, 3, 4]
+ print(array.pick_random()) # Prints either of the four numbers.
+ [/codeblock]
+ </description>
+ </method>
<method name="pop_at">
<return type="Variant" />
<param index="0" name="position" type="int" />
@@ -517,6 +533,7 @@
<return type="void" />
<param index="0" name="enable" type="bool" />
<description>
+ Makes the [Array] read-only, i.e. disabled modifying of the array's elements. Does not apply to nested content, e.g. content of nested arrays.
</description>
</method>
<method name="set_typed">
@@ -525,6 +542,8 @@
<param index="1" name="class_name" type="StringName" />
<param index="2" name="script" type="Variant" />
<description>
+ Makes the [Array] typed. The [param type] should be one of the [@GlobalScope] [code]TYPE[/code] constants. [param class_name] is optional and can only be provided for [constant @GlobalScope.TYPE_OBJECT]. [param script] can only be provided if [param class_name] is not empty.
+ The method fails if an array is already typed.
</description>
</method>
<method name="shuffle">
@@ -610,6 +629,7 @@
<return type="bool" />
<param index="0" name="array" type="Array" />
<description>
+ Assigns a different [Array] to this array reference. It the array is typed, the new array's type must be compatible and its elements will be automatically converted.
</description>
</method>
</methods>
diff --git a/doc/classes/AudioStreamGeneratorPlayback.xml b/doc/classes/AudioStreamGeneratorPlayback.xml
index 1c02dbd3ce..c16198c5c6 100644
--- a/doc/classes/AudioStreamGeneratorPlayback.xml
+++ b/doc/classes/AudioStreamGeneratorPlayback.xml
@@ -27,7 +27,7 @@
<method name="get_frames_available" qualifiers="const">
<return type="int" />
<description>
- Returns the number of audio data frames left to play. If this returned number reaches [code]0[/code], the audio will stop playing until frames are added again. Therefore, make sure your script can always generate and push new audio frames fast enough to avoid audio cracking.
+ Returns the number of frames that can be pushed to the audio sample data buffer without overflowing it. If the result is [code]0[/code], the buffer is full.
</description>
</method>
<method name="get_skips" qualifiers="const">
diff --git a/doc/classes/BaseButton.xml b/doc/classes/BaseButton.xml
index 629675132a..47e1f85c97 100644
--- a/doc/classes/BaseButton.xml
+++ b/doc/classes/BaseButton.xml
@@ -68,9 +68,6 @@
<member name="shortcut" type="Shortcut" setter="set_shortcut" getter="get_shortcut">
[Shortcut] associated to the button.
</member>
- <member name="shortcut_context" type="Node" setter="set_shortcut_context" getter="get_shortcut_context">
- The [Node] which must be a parent of the focused GUI [Control] for the shortcut to be activated. If [code]null[/code], the shortcut can be activated when any control is focused (a global shortcut). This allows shortcuts to be accepted only when the user has a certain area of the GUI focused.
- </member>
<member name="shortcut_in_tooltip" type="bool" setter="set_shortcut_in_tooltip" getter="is_shortcut_in_tooltip_enabled">
If [code]true[/code], the button will add information about its shortcut in the tooltip.
</member>
diff --git a/doc/classes/BaseMaterial3D.xml b/doc/classes/BaseMaterial3D.xml
index cbb58a3e1e..de980eab0c 100644
--- a/doc/classes/BaseMaterial3D.xml
+++ b/doc/classes/BaseMaterial3D.xml
@@ -115,7 +115,7 @@
The color used by the backlight effect. Represents the light passing through an object.
</member>
<member name="backlight_enabled" type="bool" setter="set_feature" getter="get_feature" default="false">
- If [code]true[/code], the backlight effect is enabled.
+ If [code]true[/code], the backlight effect is enabled. See also [member subsurf_scatter_transmittance_enabled].
</member>
<member name="backlight_texture" type="Texture2D" setter="set_texture" getter="get_texture">
Texture used to control the backlight effect per-pixel. Added to [member backlight].
@@ -289,6 +289,7 @@
[b]Note:[/b] If [member detail_enabled] is [code]true[/code], the [member detail_albedo] texture is drawn [i]below[/i] the [member normal_texture]. To display a normal map [i]above[/i] the [member detail_albedo] texture, use [member detail_normal] instead.
</member>
<member name="orm_texture" type="Texture2D" setter="set_texture" getter="get_texture">
+ The Occlusion/Roughness/Metallic texture to use. This is a more efficient replacement of [member ao_texture], [member roughness_texture] and [member metallic_texture] in [ORMMaterial3D]. Ambient occlusion is stored in the red channel. Roughness map is stored in the green channel. Metallic map is stored in the blue channel. The alpha channel is ignored.
</member>
<member name="particles_anim_h_frames" type="int" setter="set_particles_anim_h_frames" getter="get_particles_anim_h_frames">
The number of horizontal frames in the particle sprite sheet. Only enabled when using [constant BILLBOARD_PARTICLES]. See [member billboard_mode].
@@ -305,7 +306,7 @@
<member name="proximity_fade_distance" type="float" setter="set_proximity_fade_distance" getter="get_proximity_fade_distance" default="1.0">
Distance over which the fade effect takes place. The larger the distance the longer it takes for an object to fade.
</member>
- <member name="proximity_fade_enable" type="bool" setter="set_proximity_fade" getter="is_proximity_fade_enabled" default="false">
+ <member name="proximity_fade_enabled" type="bool" setter="set_proximity_fade_enabled" getter="is_proximity_fade_enabled" default="false">
If [code]true[/code], the proximity fade effect is enabled. The proximity fade effect fades out each pixel based on its distance to another object.
</member>
<member name="refraction_enabled" type="bool" setter="set_feature" getter="get_feature" default="false">
@@ -350,13 +351,13 @@
</member>
<member name="specular_mode" type="int" setter="set_specular_mode" getter="get_specular_mode" enum="BaseMaterial3D.SpecularMode" default="0">
The method for rendering the specular blob. See [enum SpecularMode].
- [b]Note:[/b] Only applies to the specular blob. Does not affect specular reflections from the Sky, SSR, or ReflectionProbes.
+ [b]Note:[/b] [member specular_mode] only applies to the specular blob. It does not affect specular reflections from the sky, screen-space reflections, [VoxelGI], SDFGI or [ReflectionProbe]s. To disable reflections from these sources as well, set [member metallic_specular] to [code]0.0[/code] instead.
</member>
<member name="subsurf_scatter_enabled" type="bool" setter="set_feature" getter="get_feature" default="false">
If [code]true[/code], subsurface scattering is enabled. Emulates light that penetrates an object's surface, is scattered, and then emerges.
</member>
<member name="subsurf_scatter_skin_mode" type="bool" setter="set_flag" getter="get_flag" default="false">
- If [code]true[/code], subsurface scattering will use a special mode optimized for the color and density of human skin.
+ If [code]true[/code], subsurface scattering will use a special mode optimized for the color and density of human skin, such as boosting the intensity of the red channel in subsurface scattering.
</member>
<member name="subsurf_scatter_strength" type="float" setter="set_subsurface_scattering_strength" getter="get_subsurface_scattering_strength" default="0.0">
The strength of the subsurface scattering effect.
@@ -365,14 +366,19 @@
Texture used to control the subsurface scattering strength. Stored in the red texture channel. Multiplied by [member subsurf_scatter_strength].
</member>
<member name="subsurf_scatter_transmittance_boost" type="float" setter="set_transmittance_boost" getter="get_transmittance_boost" default="0.0">
+ The intensity of the subsurface scattering transmittance effect.
</member>
<member name="subsurf_scatter_transmittance_color" type="Color" setter="set_transmittance_color" getter="get_transmittance_color" default="Color(1, 1, 1, 1)">
+ The color to multiply the subsurface scattering transmittance effect with. Ignored if [member subsurf_scatter_skin_mode] is [code]true[/code].
</member>
<member name="subsurf_scatter_transmittance_depth" type="float" setter="set_transmittance_depth" getter="get_transmittance_depth" default="0.1">
+ The depth of the subsurface scattering transmittance effect.
</member>
<member name="subsurf_scatter_transmittance_enabled" type="bool" setter="set_feature" getter="get_feature" default="false">
+ If [code]true[/code], enables subsurface scattering transmittance. Only effective if [member subsurf_scatter_enabled] is [code]true[/code]. See also [member backlight_enabled].
</member>
<member name="subsurf_scatter_transmittance_texture" type="Texture2D" setter="set_texture" getter="get_texture">
+ The texture to use for multiplying the intensity of the subsurface scattering transmitteance intensity. See also [member subsurf_scatter_texture]. Ignored if [member subsurf_scatter_skin_mode] is [code]true[/code].
</member>
<member name="texture_filter" type="int" setter="set_texture_filter" getter="get_texture_filter" enum="BaseMaterial3D.TextureFilter" default="3">
Filter flags for the texture. See [enum TextureFilter] for options.
@@ -385,6 +391,7 @@
If [code]true[/code], transparency is enabled on the body. See also [member blend_mode].
</member>
<member name="use_particle_trails" type="bool" setter="set_flag" getter="get_flag" default="false">
+ If [code]true[/code], enables parts of the shader required for [GPUParticles3D] trails to function. This also requires using a mesh with appropriate skinning, such as [RibbonTrailMesh] or [TubeTrailMesh]. Enabling this feature outside of materials used in [GPUParticles3D] meshes will break material rendering.
</member>
<member name="use_point_size" type="bool" setter="set_flag" getter="get_flag" default="false">
If [code]true[/code], render point size can be changed.
@@ -682,6 +689,7 @@
Enables the skin mode for subsurface scattering which is used to improve the look of subsurface scattering when used for human skin.
</constant>
<constant name="FLAG_PARTICLE_TRAILS_MODE" value="19" enum="Flags">
+ Enables parts of the shader required for [GPUParticles3D] trails to function. This also requires using a mesh with appropriate skinning, such as [RibbonTrailMesh] or [TubeTrailMesh]. Enabling this feature outside of materials used in [GPUParticles3D] meshes will break material rendering.
</constant>
<constant name="FLAG_ALBEDO_TEXTURE_MSDF" value="20" enum="Flags">
Enables multichannel signed distance field rendering shader.
diff --git a/doc/classes/Basis.xml b/doc/classes/Basis.xml
index 6d9b679fbc..652d6d2407 100644
--- a/doc/classes/Basis.xml
+++ b/doc/classes/Basis.xml
@@ -70,6 +70,7 @@
<param index="0" name="euler" type="Vector3" />
<param index="1" name="order" type="int" default="2" />
<description>
+ Constructs a pure rotation Basis matrix from Euler angles in the specified Euler rotation order. By default, use YXZ order (most common).
</description>
</method>
<method name="from_scale" qualifiers="static">
@@ -112,6 +113,12 @@
Returns [code]true[/code] if this basis and [param b] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this basis is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="looking_at" qualifiers="static">
<return type="Basis" />
<param index="0" name="target" type="Vector3" />
@@ -191,16 +198,22 @@
</members>
<constants>
<constant name="EULER_ORDER_XYZ" value="0">
+ Euler angle composing/decomposing order where X component is first, then Y, then Z.
</constant>
<constant name="EULER_ORDER_XZY" value="1">
+ Euler angle composing/decomposing order where X component is first, then Z, then Y.
</constant>
<constant name="EULER_ORDER_YXZ" value="2">
+ Euler angle composing/decomposing order where Y component is first, then X, then Z.
</constant>
<constant name="EULER_ORDER_YZX" value="3">
+ Euler angle composing/decomposing order where Y component is first, then Z, then X.
</constant>
<constant name="EULER_ORDER_ZXY" value="4">
+ Euler angle composing/decomposing order where Z component is first, then X, then Y.
</constant>
<constant name="EULER_ORDER_ZYX" value="5">
+ Euler angle composing/decomposing order where Z component is first, then Y, then X.
</constant>
<constant name="IDENTITY" value="Basis(1, 0, 0, 0, 1, 0, 0, 0, 1)">
The identity basis, with no rotation or scaling applied.
diff --git a/doc/classes/BoneMap.xml b/doc/classes/BoneMap.xml
index f7a4845b7d..7135406d3c 100644
--- a/doc/classes/BoneMap.xml
+++ b/doc/classes/BoneMap.xml
@@ -8,6 +8,7 @@
By assigning the actual [Skeleton3D] bone name as the key value, it maps the [Skeleton3D] to the [SkeletonProfile].
</description>
<tutorials>
+ <link title="Retargeting 3D Skeletons">$DOCS_URL/tutorials/assets_pipeline/retargeting_3d_skeletons.html</link>
</tutorials>
<methods>
<method name="find_profile_bone_name" qualifiers="const">
diff --git a/doc/classes/CPUParticles2D.xml b/doc/classes/CPUParticles2D.xml
index 906789d09f..314e46d9d0 100644
--- a/doc/classes/CPUParticles2D.xml
+++ b/doc/classes/CPUParticles2D.xml
@@ -29,12 +29,14 @@
<return type="float" />
<param index="0" name="param" type="int" enum="CPUParticles2D.Parameter" />
<description>
+ Returns the maximum value range for the given parameter.
</description>
</method>
<method name="get_param_min" qualifiers="const">
<return type="float" />
<param index="0" name="param" type="int" enum="CPUParticles2D.Parameter" />
<description>
+ Returns the minimum value range for the given parameter.
</description>
</method>
<method name="get_particle_flag" qualifiers="const">
@@ -63,6 +65,7 @@
<param index="0" name="param" type="int" enum="CPUParticles2D.Parameter" />
<param index="1" name="value" type="float" />
<description>
+ Sets the maximum value for the given parameter.
</description>
</method>
<method name="set_param_min">
@@ -70,6 +73,7 @@
<param index="0" name="param" type="int" enum="CPUParticles2D.Parameter" />
<param index="1" name="value" type="float" />
<description>
+ Sets the minimum value for the given parameter.
</description>
</method>
<method name="set_particle_flag">
@@ -89,29 +93,38 @@
Each particle's rotation will be animated along this [Curve].
</member>
<member name="angle_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum initial rotation applied to each particle, in degrees.
</member>
<member name="angle_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member angle_max].
</member>
<member name="angular_velocity_curve" type="Curve" setter="set_param_curve" getter="get_param_curve">
Each particle's angular velocity will vary along this [Curve].
</member>
<member name="angular_velocity_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum initial angular velocity (rotation speed) applied to each particle in [i]degrees[/i] per second.
</member>
<member name="angular_velocity_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member angular_velocity_max].
</member>
<member name="anim_offset_curve" type="Curve" setter="set_param_curve" getter="get_param_curve">
Each particle's animation offset will vary along this [Curve].
</member>
<member name="anim_offset_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum animation offset that corresponds to frame index in the texture. [code]0[/code] is the first frame, [code]1[/code] is the last one. See [member CanvasItemMaterial.particles_animation].
</member>
<member name="anim_offset_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member anim_offset_max].
</member>
<member name="anim_speed_curve" type="Curve" setter="set_param_curve" getter="get_param_curve">
Each particle's animation speed will vary along this [Curve].
</member>
<member name="anim_speed_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum particle animation speed. Animation speed of [code]1[/code] means that the particles will make full [code]0[/code] to [code]1[/code] offset cycle during lifetime, [code]2[/code] means [code]2[/code] cycles etc.
+ With animation speed greater than [code]1[/code], remember to enable [member CanvasItemMaterial.particles_anim_loop] property if you want the animation to repeat.
</member>
<member name="anim_speed_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member anim_speed_max].
</member>
<member name="color" type="Color" setter="set_color" getter="get_color" default="Color(1, 1, 1, 1)">
Each particle's initial color. If [member texture] is defined, it will be multiplied by this color.
@@ -126,8 +139,10 @@
Damping will vary along this [Curve].
</member>
<member name="damping_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ The maximum rate at which particles lose velocity. For example value of [code]100[/code] means that the particle will go from [code]100[/code] velocity to [code]0[/code] in [code]1[/code] second.
</member>
<member name="damping_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member damping_max].
</member>
<member name="direction" type="Vector2" setter="set_direction" getter="get_direction" default="Vector2(1, 0)">
Unit vector specifying the particles' emission direction.
@@ -160,7 +175,7 @@
How rapidly particles in an emission cycle are emitted. If greater than [code]0[/code], there will be a gap in emissions before the next cycle begins.
</member>
<member name="fixed_fps" type="int" setter="set_fixed_fps" getter="get_fixed_fps" default="0">
- The particle system's frame rate is fixed to a value. For instance, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
+ The particle system's frame rate is fixed to a value. For example, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
</member>
<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.
@@ -172,12 +187,16 @@
Each particle's hue will vary along this [Curve].
</member>
<member name="hue_variation_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum initial hue variation applied to each particle. It will shift the particle color's hue.
</member>
<member name="hue_variation_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member hue_variation_max].
</member>
<member name="initial_velocity_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum initial velocity magnitude for each particle. Direction comes from [member direction] and [member spread].
</member>
<member name="initial_velocity_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member initial_velocity_max].
</member>
<member name="lifetime" type="float" setter="set_lifetime" getter="get_lifetime" default="1.0">
Amount of time each particle will exist.
@@ -189,8 +208,10 @@
Each particle's linear acceleration will vary along this [Curve].
</member>
<member name="linear_accel_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum linear acceleration applied to each particle in the direction of motion.
</member>
<member name="linear_accel_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member linear_accel_max].
</member>
<member name="local_coords" type="bool" setter="set_use_local_coordinates" getter="get_use_local_coordinates" default="false">
If [code]true[/code], particles use the parent node's coordinate space (known as local coordinates). This will cause particles to move and rotate along the [CPUParticles2D] node (and its parents) when it is moved or rotated. If [code]false[/code], particles use global coordinates; they will not move or rotate along the [CPUParticles2D] node (and its parents) when it is moved or rotated.
@@ -202,8 +223,10 @@
Each particle's orbital velocity will vary along this [Curve].
</member>
<member name="orbit_velocity_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum orbital velocity applied to each particle. Makes the particles circle around origin. Specified in number of full rotations around origin per second.
</member>
<member name="orbit_velocity_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member orbit_velocity_max].
</member>
<member name="particle_flag_align_y" type="bool" setter="set_particle_flag" getter="get_particle_flag" default="false">
Align Y axis of particle with the direction of its velocity.
@@ -215,8 +238,10 @@
Each particle's radial acceleration will vary along this [Curve].
</member>
<member name="radial_accel_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum radial acceleration applied to each particle. Makes particle accelerate away from the origin or towards it if negative.
</member>
<member name="radial_accel_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member radial_accel_max].
</member>
<member name="randomness" type="float" setter="set_randomness_ratio" getter="get_randomness_ratio" default="0.0">
Emission lifetime randomness ratio.
@@ -225,17 +250,24 @@
Each particle's scale will vary along this [Curve].
</member>
<member name="scale_amount_max" type="float" setter="set_param_max" getter="get_param_max" default="1.0">
+ Maximum initial scale applied to each particle.
</member>
<member name="scale_amount_min" type="float" setter="set_param_min" getter="get_param_min" default="1.0">
+ Minimum equivalent of [member scale_amount_max].
</member>
<member name="scale_curve_x" type="Curve" setter="set_scale_curve_x" getter="get_scale_curve_x">
+ Each particle's horizontal scale will vary along this [Curve].
+ [member split_scale] must be enabled.
</member>
<member name="scale_curve_y" type="Curve" setter="set_scale_curve_y" getter="get_scale_curve_y">
+ Each particle's vertical scale will vary along this [Curve].
+ [member split_scale] must be enabled.
</member>
<member name="speed_scale" type="float" setter="set_speed_scale" getter="get_speed_scale" default="1.0">
Particle system's running speed scaling ratio. A value of [code]0[/code] can be used to pause the particles.
</member>
<member name="split_scale" type="bool" setter="set_split_scale" getter="get_split_scale" default="false">
+ If [code]true[/code], the scale curve will be split into x and y components. See [member scale_curve_x] and [member scale_curve_y].
</member>
<member name="spread" type="float" setter="set_spread" getter="get_spread" default="45.0">
Each particle's initial direction range from [code]+spread[/code] to [code]-spread[/code] degrees.
@@ -244,8 +276,10 @@
Each particle's tangential acceleration will vary along this [Curve].
</member>
<member name="tangential_accel_max" type="float" setter="set_param_max" getter="get_param_max" default="0.0">
+ Maximum tangential acceleration applied to each particle. Tangential acceleration is perpendicular to the particle's velocity giving the particles a swirling motion.
</member>
<member name="tangential_accel_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
+ Minimum equivalent of [member tangential_accel_max].
</member>
<member name="texture" type="Texture2D" setter="set_texture" getter="get_texture">
Particle texture. If [code]null[/code], particles will be squares.
diff --git a/doc/classes/CPUParticles3D.xml b/doc/classes/CPUParticles3D.xml
index 6b39c08b3f..3a15a117f5 100644
--- a/doc/classes/CPUParticles3D.xml
+++ b/doc/classes/CPUParticles3D.xml
@@ -28,12 +28,14 @@
<return type="float" />
<param index="0" name="param" type="int" enum="CPUParticles3D.Parameter" />
<description>
+ Returns the maximum value range for the given parameter.
</description>
</method>
<method name="get_param_min" qualifiers="const">
<return type="float" />
<param index="0" name="param" type="int" enum="CPUParticles3D.Parameter" />
<description>
+ Returns the minimum value range for the given parameter.
</description>
</method>
<method name="get_particle_flag" qualifiers="const">
@@ -62,7 +64,7 @@
<param index="0" name="param" type="int" enum="CPUParticles3D.Parameter" />
<param index="1" name="value" type="float" />
<description>
- Sets the maximum value for the given parameter
+ Sets the maximum value for the given parameter.
</description>
</method>
<method name="set_param_min">
@@ -70,7 +72,7 @@
<param index="0" name="param" type="int" enum="CPUParticles3D.Parameter" />
<param index="1" name="value" type="float" />
<description>
- Sets the minimum value for the given parameter
+ Sets the minimum value for the given parameter.
</description>
</method>
<method name="set_particle_flag">
@@ -187,7 +189,7 @@
How rapidly particles in an emission cycle are emitted. If greater than [code]0[/code], there will be a gap in emissions before the next cycle begins.
</member>
<member name="fixed_fps" type="int" setter="set_fixed_fps" getter="get_fixed_fps" default="0">
- The particle system's frame rate is fixed to a value. For instance, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the particle system itself.
+ The particle system's frame rate is fixed to a value. For example, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the particle system itself.
</member>
<member name="flatness" type="float" setter="set_flatness" getter="get_flatness" default="0.0">
Amount of [member spread] in Y/Z plane. A value of [code]1[/code] restricts particles to X/Z plane.
diff --git a/doc/classes/Camera2D.xml b/doc/classes/Camera2D.xml
index 671ecb6af1..9315a85e1f 100644
--- a/doc/classes/Camera2D.xml
+++ b/doc/classes/Camera2D.xml
@@ -52,14 +52,14 @@
<return type="Vector2" />
<description>
Returns this camera's target position, in global coordinates.
- [b]Note:[/b] The returned value is not the same as [member Node2D.global_position], as it is affected by the drag properties. It is also not the same as the current position if [member smoothing_enabled] is [code]true[/code] (see [method get_screen_center_position]).
+ [b]Note:[/b] The returned value is not the same as [member Node2D.global_position], as it is affected by the drag properties. It is also not the same as the current position if [member position_smoothing_enabled] is [code]true[/code] (see [method get_screen_center_position]).
</description>
</method>
<method name="reset_smoothing">
<return type="void" />
<description>
Sets the camera's position immediately to its current smoothing destination.
- This method has no effect if [member smoothing_enabled] is [code]false[/code].
+ This method has no effect if [member position_smoothing_enabled] is [code]false[/code].
</description>
</method>
<method name="set_drag_margin">
@@ -138,7 +138,7 @@
</member>
<member name="limit_smoothed" type="bool" setter="set_limit_smoothing_enabled" getter="is_limit_smoothing_enabled" default="false">
If [code]true[/code], the camera smoothly stops when reaches its limits.
- This property has no effect if [member smoothing_enabled] is [code]false[/code].
+ This property has no effect if [member position_smoothing_enabled] is [code]false[/code].
[b]Note:[/b] To immediately update the camera's position to be within limits without smoothing, even with this setting enabled, invoke [method reset_smoothing].
</member>
<member name="limit_top" type="int" setter="set_limit" getter="get_limit" default="-10000000">
@@ -147,6 +147,12 @@
<member name="offset" type="Vector2" setter="set_offset" getter="get_offset" default="Vector2(0, 0)">
The camera's relative offset. Useful for looking around or camera shake animations. The offsetted camera can go past the limits defined in [member limit_top], [member limit_bottom], [member limit_left] and [member limit_right].
</member>
+ <member name="position_smoothing_enabled" type="bool" setter="set_position_smoothing_enabled" getter="is_position_smoothing_enabled" default="false">
+ If [code]true[/code], the camera's view smoothly moves towards its target position at [member position_smoothing_speed].
+ </member>
+ <member name="position_smoothing_speed" type="float" setter="set_position_smoothing_speed" getter="get_position_smoothing_speed" default="5.0">
+ Speed in pixels per second of the camera's smoothing effect when [member position_smoothing_enabled] is [code]true[/code].
+ </member>
<member name="process_callback" type="int" setter="set_process_callback" getter="get_process_callback" enum="Camera2D.Camera2DProcessCallback" default="1">
The camera's process callback. See [enum Camera2DProcessCallback].
</member>
@@ -157,12 +163,6 @@
<member name="rotation_smoothing_speed" type="float" setter="set_rotation_smoothing_speed" getter="get_rotation_smoothing_speed" default="5.0">
The angular, asymptotic speed of the camera's rotation smoothing effect when [member rotation_smoothing_enabled] is [code]true[/code].
</member>
- <member name="smoothing_enabled" type="bool" setter="set_enable_follow_smoothing" getter="is_follow_smoothing_enabled" default="false">
- If [code]true[/code], the camera smoothly moves towards the target at [member smoothing_speed].
- </member>
- <member name="smoothing_speed" type="float" setter="set_follow_smoothing" getter="get_follow_smoothing" default="5.0">
- Speed in pixels per second of the camera's smoothing effect when [member smoothing_enabled] is [code]true[/code].
- </member>
<member name="zoom" type="Vector2" setter="set_zoom" getter="get_zoom" default="Vector2(1, 1)">
The camera's zoom. A zoom of [code]Vector(2, 2)[/code] doubles the size seen in the viewport. A zoom of [code]Vector(0.5, 0.5)[/code] halves the size seen in the viewport.
</member>
diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml
index 947e6a3d4c..b2d3e5cfdb 100644
--- a/doc/classes/CanvasItem.xml
+++ b/doc/classes/CanvasItem.xml
@@ -535,7 +535,7 @@
</method>
</methods>
<members>
- <member name="clip_children" type="bool" setter="set_clip_children" getter="is_clipping_children" default="false">
+ <member name="clip_children" type="int" setter="set_clip_children_mode" getter="get_clip_children_mode" enum="CanvasItem.ClipChildrenMode" default="0">
Allows the current node to clip children nodes, essentially acting as a mask.
</member>
<member name="light_mask" type="int" setter="set_light_mask" getter="get_light_mask" default="1">
@@ -653,5 +653,13 @@
<constant name="TEXTURE_REPEAT_MAX" value="4" enum="TextureRepeat">
Represents the size of the [enum TextureRepeat] enum.
</constant>
+ <constant name="CLIP_CHILDREN_DISABLED" value="0" enum="ClipChildrenMode">
+ </constant>
+ <constant name="CLIP_CHILDREN_ONLY" value="1" enum="ClipChildrenMode">
+ </constant>
+ <constant name="CLIP_CHILDREN_AND_DRAW" value="2" enum="ClipChildrenMode">
+ </constant>
+ <constant name="CLIP_CHILDREN_MAX" value="3" enum="ClipChildrenMode">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/CanvasLayer.xml b/doc/classes/CanvasLayer.xml
index 50c0860d1f..7c1b19b961 100644
--- a/doc/classes/CanvasLayer.xml
+++ b/doc/classes/CanvasLayer.xml
@@ -5,6 +5,7 @@
</brief_description>
<description>
Canvas drawing layer. [CanvasItem] nodes that are direct or indirect children of a [CanvasLayer] will be drawn in that layer. The layer is a numeric index that defines the draw order. The default 2D scene renders with index 0, so a [CanvasLayer] with index -1 will be drawn below, and one with index 1 will be drawn above. This is very useful for HUDs (in layer 1+ or above), or backgrounds (in layer -1 or below).
+ Embedded [Window]s are placed in layer 1024. CanvasItems in layer 1025 or above appear in front of embedded windows, CanvasItems in layer 1023 or below appear behind embedded windows.
</description>
<tutorials>
<link title="Viewport and canvas transforms">$DOCS_URL/tutorials/2d/2d_transforms.html</link>
diff --git a/doc/classes/CanvasTexture.xml b/doc/classes/CanvasTexture.xml
index ac18c2d474..2dc83790c7 100644
--- a/doc/classes/CanvasTexture.xml
+++ b/doc/classes/CanvasTexture.xml
@@ -1,25 +1,36 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="CanvasTexture" inherits="Texture2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
+ Texture with optional normal and specular maps for use in 2D rendering.
</brief_description>
<description>
+ [CanvasTexture] is an alternative to [ImageTexture] for 2D rendering. It allows using normal maps and specular maps in any node that inherits from [CanvasItem]. [CanvasTexture] also allows overriding the texture's filter and repeat mode independently of the node's properties (or the project settings).
+ [b]Note:[/b] [CanvasTexture] cannot be used in 3D rendering. For physically-based materials in 3D, use [BaseMaterial3D] instead.
</description>
<tutorials>
</tutorials>
<members>
<member name="diffuse_texture" type="Texture2D" setter="set_diffuse_texture" getter="get_diffuse_texture">
+ The diffuse (color) texture to use. This is the main texture you want to set in most cases.
</member>
<member name="normal_texture" type="Texture2D" setter="set_normal_texture" getter="get_normal_texture">
+ The normal map texture to use. Only has a visible effect if [Light2D]s are affecting this [CanvasTexture].
+ [b]Note:[/b] Godot expects the normal map to use X+, Y+, and Z+ coordinates. See [url=http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates]this page[/url] for a comparison of normal map coordinates expected by popular engines.
</member>
<member name="specular_color" type="Color" setter="set_specular_color" getter="get_specular_color" default="Color(1, 1, 1, 1)">
+ The multiplier for specular reflection colors. The [Light2D]'s color is also taken into account when determining the reflection color. Only has a visible effect if [Light2D]s are affecting this [CanvasTexture].
</member>
<member name="specular_shininess" type="float" setter="set_specular_shininess" getter="get_specular_shininess" default="1.0">
+ The specular exponent for [Light2D] specular reflections. Higher values result in a more glossy/"wet" look, with reflections becoming more localized and less visible overall. The default value of [code]1.0[/code] disables specular reflections entirely. Only has a visible effect if [Light2D]s are affecting this [CanvasTexture].
</member>
<member name="specular_texture" type="Texture2D" setter="set_specular_texture" getter="get_specular_texture">
+ The specular map to use for [Light2D] specular reflections. This should be a grayscale or colored texture, with brighter areas resulting in a higher [member specular_shininess] value. Using a colored [member specular_texture] allows controlling specular shininess on a per-channel basis. Only has a visible effect if [Light2D]s are affecting this [CanvasTexture].
</member>
<member name="texture_filter" type="int" setter="set_texture_filter" getter="get_texture_filter" enum="CanvasItem.TextureFilter" default="0">
+ The texture filtering mode to use when drawing this [CanvasTexture].
</member>
<member name="texture_repeat" type="int" setter="set_texture_repeat" getter="get_texture_repeat" enum="CanvasItem.TextureRepeat" default="0">
+ The texture repeat mode to use when drawing this [CanvasTexture].
</member>
</members>
</class>
diff --git a/doc/classes/CheckBox.xml b/doc/classes/CheckBox.xml
index 2ffe880971..699e872e99 100644
--- a/doc/classes/CheckBox.xml
+++ b/doc/classes/CheckBox.xml
@@ -4,7 +4,7 @@
Binary choice user interface widget. See also [CheckButton].
</brief_description>
<description>
- A checkbox allows the user to make a binary choice (choosing only one of two possible options). It's similar to [CheckButton] in functionality, but it has a different appearance. To follow established UX patterns, it's recommended to use CheckBox when toggling it has [b]no[/b] immediate effect on something. For instance, it should be used when toggling it will only do something once a confirmation button is pressed.
+ A checkbox allows the user to make a binary choice (choosing only one of two possible options). It's similar to [CheckButton] in functionality, but it has a different appearance. To follow established UX patterns, it's recommended to use CheckBox when toggling it has [b]no[/b] immediate effect on something. For example, it could be used when toggling it will only do something once a confirmation button is pressed.
See also [BaseButton] which contains common properties and methods associated with this node.
</description>
<tutorials>
diff --git a/doc/classes/CheckButton.xml b/doc/classes/CheckButton.xml
index 2f584103be..dfbaa7cbee 100644
--- a/doc/classes/CheckButton.xml
+++ b/doc/classes/CheckButton.xml
@@ -4,7 +4,7 @@
Checkable button. See also [CheckBox].
</brief_description>
<description>
- CheckButton is a toggle button displayed as a check field. It's similar to [CheckBox] in functionality, but it has a different appearance. To follow established UX patterns, it's recommended to use CheckButton when toggling it has an [b]immediate[/b] effect on something. For instance, it should be used if toggling it enables/disables a setting without requiring the user to press a confirmation button.
+ CheckButton is a toggle button displayed as a check field. It's similar to [CheckBox] in functionality, but it has a different appearance. To follow established UX patterns, it's recommended to use CheckButton when toggling it has an [b]immediate[/b] effect on something. For example, it could be used if toggling it enables/disables a setting without requiring the user to press a confirmation button.
See also [BaseButton] which contains common properties and methods associated with this node.
</description>
<tutorials>
diff --git a/doc/classes/ClassDB.xml b/doc/classes/ClassDB.xml
index 58a536406f..5d3c6210f6 100644
--- a/doc/classes/ClassDB.xml
+++ b/doc/classes/ClassDB.xml
@@ -13,7 +13,7 @@
<return type="bool" />
<param index="0" name="class" type="StringName" />
<description>
- Returns [code]true[/code] if you can instance objects from the specified [param class], [code]false[/code] in other case.
+ Returns [code]true[/code] if objects can be instantiated from the specified [param class], otherwise returns [code]false[/code].
</description>
</method>
<method name="class_exists" qualifiers="const">
diff --git a/doc/classes/Color.xml b/doc/classes/Color.xml
index 3a3803c1da..a11d7157f1 100644
--- a/doc/classes/Color.xml
+++ b/doc/classes/Color.xml
@@ -145,6 +145,11 @@
<return type="int" />
<param index="0" name="name" type="String" />
<description>
+ Returns the index of a named color. Use [method get_named_color] to get the actual color.
+ [codeblock]
+ var idx = Color.find_named_color("khaki")
+ modulate = Color.get_named_color(idx)
+ [/codeblock]
</description>
</method>
<method name="from_hsv" qualifiers="static">
@@ -187,6 +192,7 @@
<return type="Color" />
<param index="0" name="rgbe" type="int" />
<description>
+ Encodes a [Color] from a RGBE9995 format integer. See [constant Image.FORMAT_RGBE9995].
</description>
</method>
<method name="from_string" qualifiers="static">
@@ -194,6 +200,7 @@
<param index="0" name="str" type="String" />
<param index="1" name="default" type="Color" />
<description>
+ Creates a [Color] from string, which can be either a HTML color code or a named color. Fallbacks to [param default] if the string does not denote any valid color.
</description>
</method>
<method name="get_luminance" qualifiers="const">
@@ -208,29 +215,37 @@
<return type="Color" />
<param index="0" name="idx" type="int" />
<description>
+ Returns a named color with the given index. You can get the index from [method find_named_color] or iteratively from [method get_named_color_count].
</description>
</method>
<method name="get_named_color_count" qualifiers="static">
<return type="int" />
<description>
+ Returns the number of available named colors.
</description>
</method>
<method name="get_named_color_name" qualifiers="static">
<return type="String" />
<param index="0" name="idx" type="int" />
<description>
+ Returns the name of a color with the given index. You can get the index from [method find_named_color] or iteratively from [method get_named_color_count].
</description>
</method>
<method name="hex" qualifiers="static">
<return type="Color" />
<param index="0" name="hex" type="int" />
<description>
+ Returns the [Color] associated with the provided integer number, with 8 bits per channel in ARGB order. The integer should be 32-bit. Best used with hexadecimal notation.
+ [codeblock]
+ modulate = Color.hex(0xffff0000) # red
+ [/codeblock]
</description>
</method>
<method name="hex64" qualifiers="static">
<return type="Color" />
<param index="0" name="hex" type="int" />
<description>
+ Same as [method hex], but takes 64-bit integer and the color uses 16 bits per channel.
</description>
</method>
<method name="html" qualifiers="static">
diff --git a/doc/classes/ColorPicker.xml b/doc/classes/ColorPicker.xml
index d09b7f003e..cd1d0b016d 100644
--- a/doc/classes/ColorPicker.xml
+++ b/doc/classes/ColorPicker.xml
@@ -131,6 +131,7 @@
The width of the hue selection slider.
</theme_item>
<theme_item name="label_width" data_type="constant" type="int" default="10">
+ The minimum width of the color labels next to sliders.
</theme_item>
<theme_item name="margin" data_type="constant" type="int" default="4">
The margin around the [ColorPicker].
@@ -160,8 +161,10 @@
The indicator used to signalize that the color value is outside the 0-1 range.
</theme_item>
<theme_item name="picker_cursor" data_type="icon" type="Texture2D">
+ The image displayed over the color box/circle (depending on the [member picker_shape]), marking the currently selected color.
</theme_item>
<theme_item name="sample_bg" data_type="icon" type="Texture2D">
+ Background panel for the color preview box (visible when the color is translucent).
</theme_item>
<theme_item name="screen_picker" data_type="icon" type="Texture2D">
The icon for the screen color picker button.
diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml
index 9c7cb7b089..91e9b65a8a 100644
--- a/doc/classes/Control.xml
+++ b/doc/classes/Control.xml
@@ -383,7 +383,7 @@
<method name="get_global_rect" qualifiers="const">
<return type="Rect2" />
<description>
- Returns the position and size of the control relative to the top-left corner of the screen. See [member position] and [member size].
+ Returns the position and size of the control relative to the [CanvasLayer]. See [member global_position] and [member size].
</description>
</method>
<method name="get_minimum_size" qualifiers="const">
@@ -972,7 +972,7 @@
<member name="clip_contents" type="bool" setter="set_clip_contents" getter="is_clipping_contents" default="false">
Enables whether rendering of [CanvasItem] based children should be clipped to this control's rectangle. If [code]true[/code], parts of a child which would be visibly outside of this control's rectangle will not be rendered and won't receive input.
</member>
- <member name="custom_minimum_size" type="Vector2i" setter="set_custom_minimum_size" getter="get_custom_minimum_size" default="Vector2i(0, 0)">
+ <member name="custom_minimum_size" type="Vector2" setter="set_custom_minimum_size" getter="get_custom_minimum_size" default="Vector2(0, 0)">
The minimum size of the node's bounding rectangle. If you set it to a value greater than (0, 0), the node's bounding rectangle will always have at least this size, even if its content is smaller. If it's set to (0, 0), the node sizes automatically to fit its content, be it a texture or child nodes.
</member>
<member name="focus_mode" type="int" setter="set_focus_mode" getter="get_focus_mode" enum="Control.FocusMode" default="0">
@@ -999,7 +999,7 @@
If this property is not set, Godot will select a "best guess" based on surrounding nodes in the scene tree.
</member>
<member name="global_position" type="Vector2" setter="_set_global_position" getter="get_global_position">
- The node's global position, relative to the world (usually to the top-left corner of the window).
+ The node's global position, relative to the world (usually to the [CanvasLayer]).
</member>
<member name="grow_horizontal" type="int" setter="set_h_grow_direction" getter="get_h_grow_direction" enum="Control.GrowDirection" default="1">
Controls the direction on the horizontal axis in which the control should grow if its horizontal minimum size is changed to be greater than its current size, as the control always has to be at least the minimum size.
@@ -1051,6 +1051,9 @@
[b]Note:[/b] This property is mainly intended to be used for animation purposes. Text inside the Control will look pixelated or blurry when the Control is scaled. To support multiple resolutions in your project, use an appropriate viewport stretch mode as described in the [url=$DOCS_URL/tutorials/viewports/multiple_resolutions.html]documentation[/url] instead of scaling Controls individually.
[b]Note:[/b] If the Control node is a child of a [Container] node, the scale will be reset to [code]Vector2(1, 1)[/code] when the scene is instantiated. To set the Control's scale when it's instantiated, wait for one frame using [code]await get_tree().process_frame[/code] then set its [member scale] property.
</member>
+ <member name="shortcut_context" type="Node" setter="set_shortcut_context" getter="get_shortcut_context">
+ The [Node] which must be a parent of the focused [Control] for the shortcut to be activated. If [code]null[/code], the shortcut can be activated when any control is focused (a global shortcut). This allows shortcuts to be accepted only when the user has a certain area of the GUI focused.
+ </member>
<member name="size" type="Vector2" setter="_set_size" getter="get_size" default="Vector2(0, 0)">
The size of the node's bounding rectangle, in pixels. [Container] nodes update this property automatically.
</member>
diff --git a/doc/classes/CylinderShape3D.xml b/doc/classes/CylinderShape3D.xml
index 6ff142da59..dcb14ec945 100644
--- a/doc/classes/CylinderShape3D.xml
+++ b/doc/classes/CylinderShape3D.xml
@@ -5,6 +5,7 @@
</brief_description>
<description>
Cylinder shape for collisions. Like [CapsuleShape3D], but without hemispheres at the cylinder's ends.
+ [b]Note:[/b] There are several known bugs with cylinder collision shapes. Using [CapsuleShape3D] or [BoxShape3D] instead is recommended.
[b]Performance:[/b] Being a primitive collision shape, [CylinderShape3D] is fast to check collisions against (though not as fast as [SphereShape3D]). [CylinderShape3D] is also more demanding compared to [CapsuleShape3D].
</description>
<tutorials>
diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml
index a86aff060d..ac1f63af56 100644
--- a/doc/classes/Dictionary.xml
+++ b/doc/classes/Dictionary.xml
@@ -325,18 +325,21 @@
<return type="bool" />
<param index="0" name="right" type="Dictionary" />
<description>
+ Returns [code]true[/code] if the dictionaries differ, i.e. their key or value lists are different (including the order).
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="Dictionary" />
<description>
+ Returns [code]true[/code] if both dictionaries have the same contents, i.e. their keys list and value list are equal.
</description>
</operator>
<operator name="operator []">
<return type="Variant" />
<param index="0" name="key" type="Variant" />
<description>
+ Retunrs a value at the given [param key] or [code]null[/code] and error if the key does not exist. For safe access, use [method get] or [method has].
</description>
</operator>
</operators>
diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml
index 0dbaa9c86f..85d9fd34ca 100644
--- a/doc/classes/DisplayServer.xml
+++ b/doc/classes/DisplayServer.xml
@@ -1116,10 +1116,10 @@
</description>
</method>
<method name="window_get_safe_title_margins" qualifiers="const">
- <return type="Vector2i" />
+ <return type="Vector3i" />
<param index="0" name="window_id" type="int" default="0" />
<description>
- Returns left and right margins of the title that are safe to use (contains no buttons or other elements) when [constant WINDOW_FLAG_EXTEND_TO_TITLE] flag is set.
+ Returns left margins ([code]x[/code]), right margins ([code]y[/code]) adn height ([code]z[/code]) of the title that are safe to use (contains no buttons or other elements) when [constant WINDOW_FLAG_EXTEND_TO_TITLE] flag is set.
</description>
</method>
<method name="window_get_size" qualifiers="const">
diff --git a/doc/classes/EditorFileDialog.xml b/doc/classes/EditorFileDialog.xml
index 891c8d7d92..51e3706981 100644
--- a/doc/classes/EditorFileDialog.xml
+++ b/doc/classes/EditorFileDialog.xml
@@ -4,6 +4,7 @@
A modified version of [FileDialog] used by the editor.
</brief_description>
<description>
+ [EditorFileDialog] is an enhanced version of [FileDialog] avaiable only to editor plugins. Additional features include list of favorited/recent files and ability to see files as thumbnails grid instead of list.
</description>
<tutorials>
</tutorials>
@@ -62,7 +63,7 @@
The dialog's open or save mode, which affects the selection behavior. See [enum FileMode]
</member>
<member name="show_hidden_files" type="bool" setter="set_show_hidden_files" getter="is_showing_hidden_files" default="false">
- If [code]true[/code], hidden files and directories will be visible in the [EditorFileDialog].
+ If [code]true[/code], hidden files and directories will be visible in the [EditorFileDialog]. This property is synchronized with [member EditorSettings.filesystem/file_dialog/show_hidden_files].
</member>
<member name="title" type="String" setter="set_title" getter="get_title" overrides="Window" default="&quot;Save a File&quot;" />
</members>
diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml
index 1e3b1f07ee..0beb2459a3 100644
--- a/doc/classes/EditorInterface.xml
+++ b/doc/classes/EditorInterface.xml
@@ -70,6 +70,7 @@
<method name="get_editor_paths">
<return type="EditorPaths" />
<description>
+ Returns the [EditorPaths] singleton.
</description>
</method>
<method name="get_editor_scale" qualifiers="const">
diff --git a/doc/classes/EditorPlugin.xml b/doc/classes/EditorPlugin.xml
index 563987e2a3..e413c526f4 100644
--- a/doc/classes/EditorPlugin.xml
+++ b/doc/classes/EditorPlugin.xml
@@ -691,11 +691,13 @@
</signal>
<signal name="project_settings_changed">
<description>
+ Emitted when any project setting has changed.
</description>
</signal>
<signal name="resource_saved">
<param index="0" name="resource" type="Resource" />
<description>
+ Emitted when the given [param resource] was saved on disc.
</description>
</signal>
<signal name="scene_changed">
diff --git a/doc/classes/EditorProperty.xml b/doc/classes/EditorProperty.xml
index 9170c449bf..2aca19510b 100644
--- a/doc/classes/EditorProperty.xml
+++ b/doc/classes/EditorProperty.xml
@@ -61,6 +61,7 @@
<method name="update_property">
<return type="void" />
<description>
+ Forces refresh of the property display.
</description>
</method>
</methods>
diff --git a/doc/classes/EditorScript.xml b/doc/classes/EditorScript.xml
index dfc04c9cde..a02fd215d8 100644
--- a/doc/classes/EditorScript.xml
+++ b/doc/classes/EditorScript.xml
@@ -30,6 +30,7 @@
[/csharp]
[/codeblocks]
[b]Note:[/b] The script is run in the Editor context, which means the output is visible in the console window started with the Editor (stdout) instead of the usual Godot [b]Output[/b] dock.
+ [b]Note:[/b] EditorScript is [RefCounted], meaning it is destroyed when nothing references it. This can cause errors during asynchronous operations if there are no references to the script.
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/EditorSettings.xml b/doc/classes/EditorSettings.xml
index 7f3ffce9b7..818dda59bc 100644
--- a/doc/classes/EditorSettings.xml
+++ b/doc/classes/EditorSettings.xml
@@ -363,7 +363,7 @@
The color to use for the selection box that surrounds selected nodes in the 3D editor viewport. The color's alpha channel influences the selection box's opacity.
</member>
<member name="editors/3d_gizmos/gizmo_colors/instantiated" type="Color" setter="" getter="">
- The color override to use for 3D editor gizmos if the [Node3D] in question is part of an instanced scene file (from the perspective of the current scene).
+ The color override to use for 3D editor gizmos if the [Node3D] in question is part of an instantiated scene file (from the perspective of the current scene).
</member>
<member name="editors/3d_gizmos/gizmo_colors/joint" type="Color" setter="" getter="">
The 3D editor gizmo color for [Joint3D]s and [PhysicalBone3D]s.
@@ -457,6 +457,12 @@
If [code]true[/code], when saving a file, the editor will rename the old file to a different name, save a new file, then only remove the old file once the new file has been saved. This makes loss of data less likely to happen if the editor or operating system exits unexpectedly while saving (e.g. due to a crash or power outage).
[b]Note:[/b] On Windows, this feature can interact negatively with certain antivirus programs. In this case, you may have to set this to [code]false[/code] to prevent file locking issues.
</member>
+ <member name="interface/editor/accept_dialog_cancel_ok_buttons" type="int" setter="" getter="">
+ How to position the Cancel and OK buttons in the editor's [AcceptDialog]s. Different platforms have different standard behaviors for this, which can be overridden using this setting. This is useful if you use Godot both on Windows and macOS/Linux and your Godot muscle memory is stronger than your OS specific one.
+ - [b]Auto[/b] follows the platform convention: Cancel first on macOS and Linux, OK first on Windows.
+ - [b]Cancel First[/b] forces the ordering Cancel/OK.
+ - [b]OK First[/b] forces the ordering OK/Cancel.
+ </member>
<member name="interface/editor/automatically_open_screenshots" type="bool" setter="" getter="">
If [code]true[/code], automatically opens screenshots with the default program associated to [code].png[/code] files after a screenshot is taken using the [b]Editor &gt; Take Screenshot[/b] action.
</member>
@@ -671,19 +677,19 @@
If [code]true[/code], displays line length guidelines to help you keep line lengths in check. See also [member text_editor/appearance/guidelines/line_length_guideline_soft_column] and [member text_editor/appearance/guidelines/line_length_guideline_hard_column].
</member>
<member name="text_editor/appearance/gutters/highlight_type_safe_lines" type="bool" setter="" getter="">
- If [code]true[/code], highlights type-safe lines by displaying their line number color with [member text_editor/theme/highlighting/safe_line_number_color] instead of [member text_editor/theme/highlighting/line_number_color]. Type-safe lines are lines of code where the type of all variables is known at compile-time. These type-safe lines will run faster in Godot 4.0 and later thanks to typed instructions.
+ If [code]true[/code], highlights type-safe lines by displaying their line number color with [member text_editor/theme/highlighting/safe_line_number_color] instead of [member text_editor/theme/highlighting/line_number_color]. Type-safe lines are lines of code where the type of all variables is known at compile-time. These type-safe lines may run faster thanks to typed instructions.
</member>
<member name="text_editor/appearance/gutters/line_numbers_zero_padded" type="bool" setter="" getter="">
If [code]true[/code], displays line numbers with zero padding (e.g. [code]007[/code] instead of [code]7[/code]).
</member>
<member name="text_editor/appearance/gutters/show_bookmark_gutter" type="bool" setter="" getter="">
- If [code]true[/code], displays a gutter at the left containing icons for bookmarks.
+ If [code]true[/code], displays icons for bookmarks in a gutter at the left. Bookmarks remain functional when this setting is disabled.
</member>
<member name="text_editor/appearance/gutters/show_info_gutter" type="bool" setter="" getter="">
If [code]true[/code], displays a gutter at the left containing icons for methods with signal connections.
</member>
<member name="text_editor/appearance/gutters/show_line_numbers" type="bool" setter="" getter="">
- If [code]true[/code], displays line numbers in the gutter at the left.
+ If [code]true[/code], displays line numbers in a gutter at the left.
</member>
<member name="text_editor/appearance/lines/code_folding" type="bool" setter="" getter="">
If [code]true[/code], displays the folding arrows next to indented code sections and allows code folding. If [code]false[/code], hides the folding arrows next to indented code sections and disallows code folding.
@@ -752,7 +758,7 @@
[b]Note:[/b] You can hold down [kbd]Alt[/kbd] while using the mouse wheel to temporarily scroll 5 times faster.
</member>
<member name="text_editor/completion/add_type_hints" type="bool" setter="" getter="">
- If [code]true[/code], adds static typing hints such as [code]-&gt; void[/code] and [code]: int[/code] when performing method definition autocompletion.
+ If [code]true[/code], adds static typing hints such as [code]-&gt; void[/code] and [code]: int[/code] when using code autocompletion or when creating onready variables by drag and dropping nodes into the script editor while pressing the [kbd]Ctrl[/kbd] key.
</member>
<member name="text_editor/completion/auto_brace_complete" type="bool" setter="" getter="">
If [code]true[/code], automatically completes braces when making use of code completion.
@@ -803,7 +809,7 @@
The script editor's background color. If set to a translucent color, the editor theme's base color will be visible behind.
</member>
<member name="text_editor/theme/highlighting/base_type_color" type="Color" setter="" getter="">
- The script editor's base type color (used for types like [Vector2], [Vector3], ...).
+ The script editor's base type color (used for types like [Vector2], [Vector3], [Color], ...).
</member>
<member name="text_editor/theme/highlighting/bookmark_color" type="Color" setter="" getter="">
The script editor's bookmark icon color (displayed in the gutter).
@@ -863,10 +869,10 @@
[b]Note:[/b] When using the GDScript syntax highlighter, this is replaced by the function definition color configured in the syntax theme for function definitions (e.g. [code]func _ready():[/code]).
</member>
<member name="text_editor/theme/highlighting/keyword_color" type="Color" setter="" getter="">
- The script editor's non-control flow keyword color (used for keywords like [code]var[/code], [code]func[/code], some built-in methods, ...).
+ The script editor's non-control flow keyword color (used for keywords like [code]var[/code], [code]func[/code], [code]extends[/code], ...).
</member>
<member name="text_editor/theme/highlighting/line_length_guideline_color" type="Color" setter="" getter="">
- The script editor's color for the line length guideline. The "hard" line length guideline will be drawn with this color, whereas the "soft" line length guideline will be drawn with an opacity twice as low.
+ The script editor's color for the line length guideline. The "hard" line length guideline will be drawn with this color, whereas the "soft" line length guideline will be drawn with half of its opacity.
</member>
<member name="text_editor/theme/highlighting/line_number_color" type="Color" setter="" getter="">
The script editor's color for line numbers. See also [member text_editor/theme/highlighting/safe_line_number_color].
@@ -907,7 +913,7 @@
The script editor's background color for text. This should be set to a translucent color so that it can display on top of other line color modifiers such as [member text_editor/theme/highlighting/current_line_color].
</member>
<member name="text_editor/theme/highlighting/user_type_color" type="Color" setter="" getter="">
- The script editor's color for user-defined types (using [code]@class_name[/code]).
+ The script editor's color for user-defined types (using [code]class_name[/code]).
</member>
<member name="text_editor/theme/highlighting/word_highlighted_color" type="Color" setter="" getter="">
The script editor's color for words highlighted by selecting them. Only visible if [member text_editor/appearance/caret/highlight_all_occurrences] is [code]true[/code].
diff --git a/doc/classes/EditorSpinSlider.xml b/doc/classes/EditorSpinSlider.xml
index 2ada211dab..9961e11f7d 100644
--- a/doc/classes/EditorSpinSlider.xml
+++ b/doc/classes/EditorSpinSlider.xml
@@ -10,13 +10,16 @@
</tutorials>
<members>
<member name="flat" type="bool" setter="set_flat" getter="is_flat" default="false">
+ If [code]true[/code], the slider will not draw background.
</member>
<member name="hide_slider" type="bool" setter="set_hide_slider" getter="is_hiding_slider" default="false">
If [code]true[/code], the slider is hidden.
</member>
<member name="label" type="String" setter="set_label" getter="get_label" default="&quot;&quot;">
+ The text that displays to the left of the value.
</member>
<member name="read_only" type="bool" setter="set_read_only" getter="is_read_only" default="false">
+ If [code]true[/code], the slider can't be interacted with.
</member>
<member name="suffix" type="String" setter="set_suffix" getter="get_suffix" default="&quot;&quot;">
The suffix to display after the value (in a faded color). This should generally be a plural word. You may have to use an abbreviation if the suffix is too long to be displayed.
diff --git a/doc/classes/Engine.xml b/doc/classes/Engine.xml
index 2b8663e039..821fae37a6 100644
--- a/doc/classes/Engine.xml
+++ b/doc/classes/Engine.xml
@@ -146,11 +146,13 @@
<return type="ScriptLanguage" />
<param index="0" name="index" type="int" />
<description>
+ Returns an instance of a [ScriptLanguage] with the given index.
</description>
</method>
<method name="get_script_language_count">
<return type="int" />
<description>
+ Returns the number of available script languages. Use with [method get_script_language].
</description>
</method>
<method name="get_singleton" qualifiers="const">
@@ -163,6 +165,7 @@
<method name="get_singleton_list" qualifiers="const">
<return type="PackedStringArray" />
<description>
+ Returns a list of available global singletons.
</description>
</method>
<method name="get_version_info" qualifiers="const">
@@ -244,6 +247,7 @@
<return type="void" />
<param index="0" name="language" type="ScriptLanguage" />
<description>
+ Registers a [ScriptLanguage] instance to be available with [code]ScriptServer[/code].
</description>
</method>
<method name="register_singleton">
@@ -251,12 +255,14 @@
<param index="0" name="name" type="StringName" />
<param index="1" name="instance" type="Object" />
<description>
+ Registers the given object as a singleton, globally available under [param name].
</description>
</method>
<method name="unregister_singleton">
<return type="void" />
<param index="0" name="name" type="StringName" />
<description>
+ Unregisters the singleton registered under [param name]. The singleton object is not freed. Only works with user-defined singletons created with [method register_singleton].
</description>
</method>
</methods>
diff --git a/doc/classes/Environment.xml b/doc/classes/Environment.xml
index 243a28e73d..33b6a786ae 100644
--- a/doc/classes/Environment.xml
+++ b/doc/classes/Environment.xml
@@ -301,6 +301,7 @@
<member name="volumetric_fog_density" type="float" setter="set_volumetric_fog_density" getter="get_volumetric_fog_density" default="0.05">
The base [i]exponential[/i] density of the volumetric fog. Set this to the lowest density you want to have globally. [FogVolume]s can be used to add to or subtract from this density in specific areas. Fog rendering is exponential as in real life.
A value of [code]0.0[/code] disables global volumetric fog while allowing [FogVolume]s to display volumetric fog in specific areas.
+ To make volumetric fog work as a volumetric [i]lighting[/i] solution, set [member volumetric_fog_density] to the lowest non-zero value ([code]0.0001[/code]) then increase lights' [member Light3D.light_volumetric_fog_energy] to values between [code]10000[/code] and [code]100000[/code] to compensate for the very low density.
</member>
<member name="volumetric_fog_detail_spread" type="float" setter="set_volumetric_fog_detail_spread" getter="get_volumetric_fog_detail_spread" default="2.0">
The distribution of size down the length of the froxel buffer. A higher value compresses the froxels closer to the camera and places more detail closer to the camera.
diff --git a/doc/classes/FogMaterial.xml b/doc/classes/FogMaterial.xml
index 7428d6169a..aab6be4212 100644
--- a/doc/classes/FogMaterial.xml
+++ b/doc/classes/FogMaterial.xml
@@ -15,6 +15,7 @@
</member>
<member name="density" type="float" setter="set_density" getter="get_density" default="1.0">
The density of the [FogVolume]. Denser objects are more opaque, but may suffer from under-sampling artifacts that look like stripes. Negative values can be used to subtract fog from other [FogVolume]s or global volumetric fog.
+ [b]Note:[/b] Due to limited precision, [member density] values between [code]-0.001[/code] and [code]0.001[/code] (exclusive) act like [code]0.0[/code]. This does not apply to [member Environment.volumetric_fog_density].
</member>
<member name="density_texture" type="Texture3D" setter="set_density_texture" getter="get_density_texture">
The 3D texture that is used to scale the [member density] of the [FogVolume]. This can be used to vary fog density within the [FogVolume] with any kind of static pattern. For animated effects, consider using a custom [url=$DOCS_URL/tutorials/shaders/shader_reference/fog_shader.html]fog shader[/url].
diff --git a/doc/classes/GPUParticles2D.xml b/doc/classes/GPUParticles2D.xml
index f41e34c43a..043c08eed5 100644
--- a/doc/classes/GPUParticles2D.xml
+++ b/doc/classes/GPUParticles2D.xml
@@ -52,7 +52,7 @@
How rapidly particles in an emission cycle are emitted. If greater than [code]0[/code], there will be a gap in emissions before the next cycle begins.
</member>
<member name="fixed_fps" type="int" setter="set_fixed_fps" getter="get_fixed_fps" default="30">
- The particle system's frame rate is fixed to a value. For instance, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
+ The particle system's frame rate is fixed to a value. For example, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
</member>
<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.
diff --git a/doc/classes/GPUParticles3D.xml b/doc/classes/GPUParticles3D.xml
index e7b436010e..d0be4d784a 100644
--- a/doc/classes/GPUParticles3D.xml
+++ b/doc/classes/GPUParticles3D.xml
@@ -84,7 +84,7 @@
Time ratio between each emission. If [code]0[/code], particles are emitted continuously. If [code]1[/code], all particles are emitted simultaneously.
</member>
<member name="fixed_fps" type="int" setter="set_fixed_fps" getter="get_fixed_fps" default="30">
- The particle system's frame rate is fixed to a value. For instance, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
+ The particle system's frame rate is fixed to a value. For example, changing the value to 2 will make the particles render at 2 frames per second. Note this does not slow down the simulation of the particle system itself.
</member>
<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.
diff --git a/doc/classes/Image.xml b/doc/classes/Image.xml
index 510f14ec54..88cea6820e 100644
--- a/doc/classes/Image.xml
+++ b/doc/classes/Image.xml
@@ -26,7 +26,7 @@
<param index="1" name="src_rect" type="Rect2i" />
<param index="2" name="dst" type="Vector2i" />
<description>
- Alpha-blends [param src_rect] from [param src] image to this image at coordinates [param dst], clipped accordingly to both image bounds. This image and [param src] image [b]must[/b] have the same format. [param src_rect] with not positive size is treated as empty.
+ Alpha-blends [param src_rect] from [param src] image to this image at coordinates [param dst], clipped accordingly to both image bounds. This image and [param src] image [b]must[/b] have the same format. [param src_rect] with non-positive size is treated as empty.
</description>
</method>
<method name="blend_rect_mask">
@@ -36,7 +36,7 @@
<param index="2" name="src_rect" type="Rect2i" />
<param index="3" name="dst" type="Vector2i" />
<description>
- Alpha-blends [param src_rect] from [param src] image to this image using [param mask] image at coordinates [param dst], clipped accordingly to both image bounds. Alpha channels are required for both [param src] and [param mask]. [param dst] pixels and [param src] pixels will blend if the corresponding mask pixel's alpha value is not 0. This image and [param src] image [b]must[/b] have the same format. [param src] image and [param mask] image [b]must[/b] have the same size (width and height) but they can have different formats. [param src_rect] with not positive size is treated as empty.
+ Alpha-blends [param src_rect] from [param src] image to this image using [param mask] image at coordinates [param dst], clipped accordingly to both image bounds. Alpha channels are required for both [param src] and [param mask]. [param dst] pixels and [param src] pixels will blend if the corresponding mask pixel's alpha value is not 0. This image and [param src] image [b]must[/b] have the same format. [param src] image and [param mask] image [b]must[/b] have the same size (width and height) but they can have different formats. [param src_rect] with non-positive size is treated as empty.
</description>
</method>
<method name="blit_rect">
@@ -45,7 +45,7 @@
<param index="1" name="src_rect" type="Rect2i" />
<param index="2" name="dst" type="Vector2i" />
<description>
- Copies [param src_rect] from [param src] image to this image at coordinates [param dst], clipped accordingly to both image bounds. This image and [param src] image [b]must[/b] have the same format. [param src_rect] with not positive size is treated as empty.
+ Copies [param src_rect] from [param src] image to this image at coordinates [param dst], clipped accordingly to both image bounds. This image and [param src] image [b]must[/b] have the same format. [param src_rect] with non-positive size is treated as empty.
</description>
</method>
<method name="blit_rect_mask">
@@ -55,7 +55,7 @@
<param index="2" name="src_rect" type="Rect2i" />
<param index="3" name="dst" type="Vector2i" />
<description>
- Blits [param src_rect] area from [param src] image to this image at the coordinates given by [param dst], clipped accordingly to both image bounds. [param src] pixel is copied onto [param dst] if the corresponding [param mask] pixel's alpha value is not 0. This image and [param src] image [b]must[/b] have the same format. [param src] image and [param mask] image [b]must[/b] have the same size (width and height) but they can have different formats. [param src_rect] with not positive size is treated as empty.
+ Blits [param src_rect] area from [param src] image to this image at the coordinates given by [param dst], clipped accordingly to both image bounds. [param src] pixel is copied onto [param dst] if the corresponding [param mask] pixel's alpha value is not 0. This image and [param src] image [b]must[/b] have the same format. [param src] image and [param mask] image [b]must[/b] have the same size (width and height) but they can have different formats. [param src_rect] with non-positive size is treated as empty.
</description>
</method>
<method name="bump_map_to_normal_map">
@@ -111,8 +111,8 @@
Copies [param src] image to this image.
</description>
</method>
- <method name="create">
- <return type="void" />
+ <method name="create" qualifiers="static">
+ <return type="Image" />
<param index="0" name="width" type="int" />
<param index="1" name="height" type="int" />
<param index="2" name="use_mipmaps" type="bool" />
@@ -121,8 +121,8 @@
Creates an empty image of given size and format. See [enum Format] constants. If [param use_mipmaps] is [code]true[/code] then generate mipmaps for this image. See the [method generate_mipmaps].
</description>
</method>
- <method name="create_from_data">
- <return type="void" />
+ <method name="create_from_data" qualifiers="static">
+ <return type="Image" />
<param index="0" name="width" type="int" />
<param index="1" name="height" type="int" />
<param index="2" name="use_mipmaps" type="bool" />
@@ -454,6 +454,17 @@
Saves the image as a WebP (Web Picture) file to a byte array. By default it will save lossless. If [param lossy] is true, the image will be saved lossy, using the [param quality] setting between 0.0 and 1.0 (inclusive).
</description>
</method>
+ <method name="set_data">
+ <return type="void" />
+ <param index="0" name="width" type="int" />
+ <param index="1" name="height" type="int" />
+ <param index="2" name="use_mipmaps" type="bool" />
+ <param index="3" name="format" type="int" enum="Image.Format" />
+ <param index="4" name="data" type="PackedByteArray" />
+ <description>
+ Overwrites data of an existing [Image]. Non-static equivalent of [method create_from_data].
+ </description>
+ </method>
<method name="set_pixel">
<return type="void" />
<param index="0" name="x" type="int" />
diff --git a/doc/classes/InputEventMIDI.xml b/doc/classes/InputEventMIDI.xml
index 2af88149b6..04d8cab065 100644
--- a/doc/classes/InputEventMIDI.xml
+++ b/doc/classes/InputEventMIDI.xml
@@ -90,7 +90,7 @@
The pressure of the MIDI signal. This value ranges from 0 to 127. For many devices, this value is always zero.
</member>
<member name="velocity" type="int" setter="set_velocity" getter="get_velocity" default="0">
- The velocity of the MIDI signal. This value ranges from 0 to 127. For a piano, this corresponds to how quickly the key was pressed, and is rarely above about 110 in practice.
+ The velocity of the MIDI signal. This value ranges from 0 to 127. For a piano, this corresponds to how quickly the key was pressed, and is rarely above about 110 in practice. Note that some MIDI devices may send a [constant MIDI_MESSAGE_NOTE_ON] message with zero velocity and expect this to be treated the same as a [constant MIDI_MESSAGE_NOTE_OFF] message, but device implementations vary so Godot reports event data exactly as received.
</member>
</members>
</class>
diff --git a/doc/classes/InputEventScreenTouch.xml b/doc/classes/InputEventScreenTouch.xml
index fb50454917..346b6bf732 100644
--- a/doc/classes/InputEventScreenTouch.xml
+++ b/doc/classes/InputEventScreenTouch.xml
@@ -11,6 +11,9 @@
<link title="InputEvent">$DOCS_URL/tutorials/inputs/inputevent.html</link>
</tutorials>
<members>
+ <member name="double_tap" type="bool" setter="set_double_tap" getter="is_double_tap" default="false">
+ If [code]true[/code], the touch's state is a double tap.
+ </member>
<member name="index" type="int" setter="set_index" getter="get_index" default="0">
The touch index in the case of a multi-touch event. One index = one finger.
</member>
diff --git a/doc/classes/Light3D.xml b/doc/classes/Light3D.xml
index e9ebbc0a41..60e20cd97d 100644
--- a/doc/classes/Light3D.xml
+++ b/doc/classes/Light3D.xml
@@ -55,6 +55,7 @@
</member>
<member name="light_angular_distance" type="float" setter="set_param" getter="get_param" default="0.0">
The light's angular size in degrees. Increasing this will make shadows softer at greater distances. Only available for [DirectionalLight3D]s. For reference, the Sun from the Earth is approximately [code]0.5[/code].
+ [b]Note:[/b] [member light_angular_distance] is not affected by [member Node3D.scale] (the light's scale or its parent's scale).
</member>
<member name="light_bake_mode" type="int" setter="set_bake_mode" getter="get_bake_mode" enum="Light3D.BakeMode" default="2">
The light's bake mode. This will affect the global illumination techniques that have an effect on the light's rendering. See [enum BakeMode].
@@ -91,6 +92,7 @@
</member>
<member name="light_size" type="float" setter="set_param" getter="get_param" default="0.0">
The size of the light in Godot units. Only available for [OmniLight3D]s and [SpotLight3D]s. Increasing this value will make the light fade out slower and shadows appear blurrier. This can be used to simulate area lights to an extent.
+ [b]Note:[/b] [member light_size] is not affected by [member Node3D.scale] (the light's scale or its parent's scale).
</member>
<member name="light_specular" type="float" setter="set_param" getter="get_param" default="0.5">
The intensity of the specular blob in objects affected by the light. At [code]0[/code], the light becomes a pure diffuse light. When not baking emission, this can be used to avoid unrealistic reflections when placing lights above an emissive surface.
diff --git a/doc/classes/MenuBar.xml b/doc/classes/MenuBar.xml
index 3ef0572e9f..e8505937ff 100644
--- a/doc/classes/MenuBar.xml
+++ b/doc/classes/MenuBar.xml
@@ -106,9 +106,6 @@
<member name="prefer_global_menu" type="bool" setter="set_prefer_global_menu" getter="is_prefer_global_menu" default="true">
If [code]true[/code], [MenuBar] will use system global menu when supported.
</member>
- <member name="shortcut_context" type="Node" setter="set_shortcut_context" getter="get_shortcut_context">
- The [Node] which must be a parent of the focused GUI [Control] for the shortcut to be activated. If [code]null[/code], the shortcut can be activated when any control is focused (a global shortcut). This allows shortcuts to be accepted only when the user has a certain area of the GUI focused.
- </member>
<member name="start_index" type="int" setter="set_start_index" getter="get_start_index" default="-1">
Position in the global menu to insert first [MenuBar] item at.
</member>
diff --git a/doc/classes/Mesh.xml b/doc/classes/Mesh.xml
index d3d5a7bfaa..facbe5fd0f 100644
--- a/doc/classes/Mesh.xml
+++ b/doc/classes/Mesh.xml
@@ -129,7 +129,7 @@
<method name="get_aabb" qualifiers="const">
<return type="AABB" />
<description>
- Returns the smallest [AABB] enclosing this mesh in local space. Not affected by [code]custom_aabb[/code]. See also [method VisualInstance3D.get_transformed_aabb].
+ Returns the smallest [AABB] enclosing this mesh in local space. Not affected by [code]custom_aabb[/code].
[b]Note:[/b] This is only implemented for [ArrayMesh] and [PrimitiveMesh].
</description>
</method>
diff --git a/doc/classes/MultiMesh.xml b/doc/classes/MultiMesh.xml
index ce2b5f2584..d8a232b3cf 100644
--- a/doc/classes/MultiMesh.xml
+++ b/doc/classes/MultiMesh.xml
@@ -19,7 +19,7 @@
<method name="get_aabb" qualifiers="const">
<return type="AABB" />
<description>
- Returns the visibility axis-aligned bounding box in local space. See also [method VisualInstance3D.get_transformed_aabb].
+ Returns the visibility axis-aligned bounding box in local space.
</description>
</method>
<method name="get_instance_color" qualifiers="const">
diff --git a/doc/classes/MultiplayerPeer.xml b/doc/classes/MultiplayerPeer.xml
index 0f57ff9e55..ba6c60a088 100644
--- a/doc/classes/MultiplayerPeer.xml
+++ b/doc/classes/MultiplayerPeer.xml
@@ -25,10 +25,22 @@
Returns the current state of the connection. See [enum ConnectionStatus].
</description>
</method>
+ <method name="get_packet_channel" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns the channel over which the next available packet was received. See [method PacketPeer.get_available_packet_count].
+ </description>
+ </method>
+ <method name="get_packet_mode" qualifiers="const">
+ <return type="int" enum="MultiplayerPeer.TransferMode" />
+ <description>
+ Returns the [enum MultiplayerPeer.TransferMode] the remote peer used to send the next available packet. See [method PacketPeer.get_available_packet_count].
+ </description>
+ </method>
<method name="get_packet_peer" qualifiers="const">
<return type="int" />
<description>
- Returns the ID of the [MultiplayerPeer] who sent the most recent packet.
+ Returns the ID of the [MultiplayerPeer] who sent the next available packet. See [method PacketPeer.get_available_packet_count].
</description>
</method>
<method name="get_unique_id" qualifiers="const">
@@ -37,6 +49,12 @@
Returns the ID of this [MultiplayerPeer].
</description>
</method>
+ <method name="is_server_relay_supported" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns true if the server can act as a relay in the current configuration (i.e. if the higher level [MultiplayerAPI] should notify connected clients of other peers, and implement a relay protocol to allow communication between them).
+ </description>
+ </method>
<method name="poll">
<return type="void" />
<description>
diff --git a/doc/classes/NavigationAgent2D.xml b/doc/classes/NavigationAgent2D.xml
index 3437e0eca4..a69491ec66 100644
--- a/doc/classes/NavigationAgent2D.xml
+++ b/doc/classes/NavigationAgent2D.xml
@@ -163,7 +163,7 @@
</description>
</signal>
<signal name="velocity_computed">
- <param index="0" name="safe_velocity" type="Vector3" />
+ <param index="0" name="safe_velocity" type="Vector2" />
<description>
Notifies when the collision avoidance velocity is calculated. Emitted by [method set_velocity]. Only emitted when [member avoidance_enabled] is true.
</description>
diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml
index bceb285584..620895d8d8 100644
--- a/doc/classes/Node.xml
+++ b/doc/classes/Node.xml
@@ -529,9 +529,9 @@
<method name="move_child">
<return type="void" />
<param index="0" name="child_node" type="Node" />
- <param index="1" name="to_position" type="int" />
+ <param index="1" name="to_index" type="int" />
<description>
- Moves a child node to a different position (order) among the other children. Since calls, signals, etc are performed by tree order, changing the order of children nodes may be useful. If [param to_position] is negative, the index will be counted from the end.
+ Moves a child node to a different index (order) among the other children. Since calls, signals, etc. are performed by tree order, changing the order of children nodes may be useful. If [param to_index] is negative, the index will be counted from the end.
[b]Note:[/b] Internal children can only be moved within their expected "internal range" (see [code]internal[/code] parameter in [method add_child]).
</description>
</method>
diff --git a/doc/classes/Node3D.xml b/doc/classes/Node3D.xml
index 3df7ec931f..bc2570b183 100644
--- a/doc/classes/Node3D.xml
+++ b/doc/classes/Node3D.xml
@@ -296,6 +296,7 @@
<member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3(1, 1, 1)">
Scale part of the local transformation.
[b]Note:[/b] Mixed negative scales in 3D are not decomposable from the transformation matrix. Due to the way scale is represented with transformation matrices in Godot, the scale values will either be all positive or all negative.
+ [b]Note:[/b] Not all nodes are visually scaled by the [member scale] property. For example, [Light3D]s are not visually affected by [member scale].
</member>
<member name="top_level" type="bool" setter="set_as_top_level" getter="is_set_as_top_level" default="false">
If [code]true[/code], the node will not inherit its transformations from its parent. Node transformations are only in global space.
diff --git a/doc/classes/NodePath.xml b/doc/classes/NodePath.xml
index 9db100c9f8..022b4826ea 100644
--- a/doc/classes/NodePath.xml
+++ b/doc/classes/NodePath.xml
@@ -4,7 +4,7 @@
Pre-parsed scene tree path.
</brief_description>
<description>
- A pre-parsed relative or absolute path in a scene tree, for use with [method Node.get_node] and similar functions. It can reference a node, a resource within a node, or a property of a node or resource. For instance, [code]"Path2D/PathFollow2D/Sprite2D:texture:size"[/code] would refer to the [code]size[/code] property of the [code]texture[/code] resource on the node named [code]"Sprite2D"[/code] which is a child of the other named nodes in the path.
+ A pre-parsed relative or absolute path in a scene tree, for use with [method Node.get_node] and similar functions. It can reference a node, a resource within a node, or a property of a node or resource. For example, [code]"Path2D/PathFollow2D/Sprite2D:texture:size"[/code] would refer to the [code]size[/code] property of the [code]texture[/code] resource on the node named [code]"Sprite2D"[/code] which is a child of the other named nodes in the path.
You will usually just pass a string to [method Node.get_node] and it will be automatically converted, but you may occasionally want to parse a path ahead of time with [NodePath] or the literal syntax [code]^"path"[/code]. Exporting a [NodePath] variable will give you a node selection widget in the properties panel of the editor, which can often be useful.
A [NodePath] is composed of a list of slash-separated node names (like a filesystem path) and an optional colon-separated list of "subnames" which can be resources or properties.
Some examples of NodePaths include the following:
diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index 15b3d4958c..c8491b3a03 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -445,6 +445,15 @@
[b]Note:[/b] This method is not supported on the web platform. It returns an empty string.
</description>
</method>
+ <method name="get_video_adapter_driver_info" qualifiers="const">
+ <return type="PackedStringArray" />
+ <description>
+ Returns the video adapter driver name and version for the user's currently active graphics card.
+ The first element holds the driver name, such as [code]nvidia[/code], [code]amdgpu[/code], etc.
+ The second element holds the driver version. For e.g. the [code]nvidia[/code] driver on a Linux/BSD platform, the version is in the format [code]510.85.02[/code]. For Windows, the driver's format is [code]31.0.15.1659[/code].
+ [b]Note:[/b] This method is only supported on the platforms Linux/BSD and Windows when not running in headless mode. It returns an empty array on other platforms.
+ </description>
+ </method>
<method name="has_environment" qualifiers="const">
<return type="bool" />
<param index="0" name="variable" type="String" />
@@ -616,11 +625,11 @@
</member>
</members>
<constants>
- <constant name="VIDEO_DRIVER_VULKAN" value="0" enum="VideoDriver">
- The Vulkan rendering backend. It requires Vulkan 1.0 support and automatically uses features from Vulkan 1.1 and 1.2 if available.
+ <constant name="RENDERING_DRIVER_VULKAN" value="0" enum="RenderingDriver">
+ The Vulkan rendering driver. It requires Vulkan 1.0 support and automatically uses features from Vulkan 1.1 and 1.2 if available.
</constant>
- <constant name="VIDEO_DRIVER_OPENGL_3" value="1" enum="VideoDriver">
- The OpenGL 3 rendering backend. It uses OpenGL 3.3 Core Profile on desktop platforms, OpenGL ES 3.0 on mobile devices, and WebGL 2.0 on Web.
+ <constant name="RENDERING_DRIVER_OPENGL3" value="1" enum="RenderingDriver">
+ The OpenGL 3 rendering driver. It uses OpenGL 3.3 Core Profile on desktop platforms, OpenGL ES 3.0 on mobile devices, and WebGL 2.0 on Web.
</constant>
<constant name="DAY_SUNDAY" value="0" enum="Weekday">
Sunday.
diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml
index 7ad1908bb5..e663f47ddf 100644
--- a/doc/classes/Object.xml
+++ b/doc/classes/Object.xml
@@ -364,9 +364,9 @@
</method>
<method name="get_indexed" qualifiers="const">
<return type="Variant" />
- <param index="0" name="property" type="NodePath" />
+ <param index="0" name="property_path" type="NodePath" />
<description>
- Gets the object's property indexed by the given [NodePath]. The node path should be relative to the current object and can use the colon character ([code]:[/code]) to access nested properties. Examples: [code]"position:x"[/code] or [code]"material:next_pass:blend_mode"[/code].
+ Gets the object's property indexed by the given [param property_path]. The path should be a [NodePath] relative to the current object and can use the colon character ([code]:[/code]) to access nested properties. Examples: [code]"position:x"[/code] or [code]"material:next_pass:blend_mode"[/code].
[b]Note:[/b] Even though the method takes [NodePath] argument, it doesn't support actual paths to [Node]s in the scene tree, only colon-separated sub-property paths. For the purpose of nodes, use [method Node.get_node_and_resource] instead.
</description>
</method>
@@ -532,10 +532,10 @@
</method>
<method name="set_indexed">
<return type="void" />
- <param index="0" name="property" type="NodePath" />
+ <param index="0" name="property_path" type="NodePath" />
<param index="1" name="value" type="Variant" />
<description>
- Assigns a new value to the property identified by the [NodePath]. The node path should be relative to the current object and can use the colon character ([code]:[/code]) to access nested properties. Example:
+ Assigns a new value to the property identified by the [param property_path]. The path should be a [NodePath] relative to the current object and can use the colon character ([code]:[/code]) to access nested properties. Example:
[codeblocks]
[gdscript]
var node = Node2D.new()
diff --git a/doc/classes/OmniLight3D.xml b/doc/classes/OmniLight3D.xml
index ce63dbdbc1..193ae8deeb 100644
--- a/doc/classes/OmniLight3D.xml
+++ b/doc/classes/OmniLight3D.xml
@@ -15,6 +15,7 @@
</member>
<member name="omni_range" type="float" setter="set_param" getter="get_param" default="5.0">
The light's radius. Note that the effectively lit area may appear to be smaller depending on the [member omni_attenuation] in use. No matter the [member omni_attenuation] in use, the light will never reach anything outside this radius.
+ [b]Note:[/b] [member omni_range] is not affected by [member Node3D.scale] (the light's scale or its parent's scale).
</member>
<member name="omni_shadow_mode" type="int" setter="set_shadow_mode" getter="get_shadow_mode" enum="OmniLight3D.ShadowMode" default="1">
See [enum ShadowMode].
diff --git a/doc/classes/ParticleProcessMaterial.xml b/doc/classes/ParticleProcessMaterial.xml
index a41207e9b3..d4050e3bd1 100644
--- a/doc/classes/ParticleProcessMaterial.xml
+++ b/doc/classes/ParticleProcessMaterial.xml
@@ -217,7 +217,7 @@
Maximum linear acceleration applied to each particle in the direction of motion.
</member>
<member name="linear_accel_min" type="float" setter="set_param_min" getter="get_param_min" default="0.0">
- Minimum equivalent of [member linear_accel_min].
+ Minimum equivalent of [member linear_accel_max].
</member>
<member name="orbit_velocity_curve" type="Texture2D" setter="set_param_texture" getter="get_param_texture">
Each particle's orbital velocity will vary along this [CurveTexture].
@@ -259,6 +259,10 @@
<member name="spread" type="float" setter="set_spread" getter="get_spread" default="45.0">
Each particle's initial direction range from [code]+spread[/code] to [code]-spread[/code] degrees.
</member>
+ <member name="sub_emitter_amount_at_collision" type="int" setter="set_sub_emitter_amount_at_collision" getter="get_sub_emitter_amount_at_collision">
+ Sub particle amount on collision.
+ Maximum amount set in the sub particles emitter.
+ </member>
<member name="sub_emitter_amount_at_end" type="int" setter="set_sub_emitter_amount_at_end" getter="get_sub_emitter_amount_at_end">
</member>
<member name="sub_emitter_frequency" type="float" setter="set_sub_emitter_frequency" getter="get_sub_emitter_frequency">
diff --git a/doc/classes/Plane.xml b/doc/classes/Plane.xml
index e51e3753fc..fbe8afa8d1 100644
--- a/doc/classes/Plane.xml
+++ b/doc/classes/Plane.xml
@@ -119,6 +119,12 @@
Returns [code]true[/code] if this plane and [param to_plane] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this plane is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="is_point_over" qualifiers="const">
<return type="bool" />
<param index="0" name="point" type="Vector3" />
diff --git a/doc/classes/PopupMenu.xml b/doc/classes/PopupMenu.xml
index 23287f4de1..c99760996f 100644
--- a/doc/classes/PopupMenu.xml
+++ b/doc/classes/PopupMenu.xml
@@ -533,6 +533,8 @@
<param index="0" name="id" type="int" />
<description>
Emitted when an item of some [param id] is pressed or its accelerator is activated.
+
+ [b]Note:[/b] If [param id] is negative (either explicitly or due to overflow), this will return the correponding index instead.
</description>
</signal>
<signal name="index_pressed">
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 214f087d78..7843104a59 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -413,6 +413,9 @@
<member name="debug/gdscript/warnings/standalone_ternary" type="int" setter="" getter="" default="1">
When set to [code]warn[/code] or [code]error[/code], produces a warning or an error respectively when calling a ternary expression that has no effect on the surrounding code, such as writing [code]42 if active else 0[/code] as a statement.
</member>
+ <member name="debug/gdscript/warnings/static_called_on_instance" type="int" setter="" getter="" default="1">
+ When set to [code]warn[/code] or [code]error[/code], produces a warning or an error respectively when calling a static method from an instance of a class instead of from the class directly.
+ </member>
<member name="debug/gdscript/warnings/treat_warnings_as_errors" type="bool" setter="" getter="" default="false">
If [code]true[/code], all warnings will be reported as if they are errors.
</member>
@@ -565,8 +568,15 @@
<member name="display/window/ios/hide_home_indicator" type="bool" setter="" getter="" default="true">
If [code]true[/code], the home indicator is hidden automatically. This only affects iOS devices without a physical home button.
</member>
+ <member name="display/window/ios/hide_status_bar" type="bool" setter="" getter="" default="true">
+ If [code]true[/code], the status bar is hidden while the app is running.
+ </member>
+ <member name="display/window/ios/suppress_ui_gesture" type="bool" setter="" getter="" default="true">
+ If [code]true[/code], it will require two swipes to access iOS UI that uses gestures.
+ [b]Note:[/b] This setting has no effect on the home indicator if [code]hide_home_indicator[/code] is [code]true[/code].
+ </member>
<member name="display/window/per_pixel_transparency/allowed" type="bool" setter="" getter="" default="false">
- If [code]true[/code], allows per-pixel transparency for the window background. This affects performance, so leave it on [code]false[/code] unless you need it.
+ If [code]true[/code], allows per-pixel transparency for the window background. This affects performance, so leave it on [code]false[/code] unless you need it. See also [member display/window/size/transparent] and [member rendering/transparent_background].
</member>
<member name="display/window/size/always_on_top" type="bool" setter="" getter="" default="false">
Forces the main window to be always on top.
@@ -591,8 +601,8 @@
[b]Note:[/b] This setting is ignored on iOS.
</member>
<member name="display/window/size/transparent" type="bool" setter="" getter="" default="false">
- Main window background can be transparent.
- [b]Note:[/b] To use transparent splash screen, set [member application/boot_splash/bg_color] to [code]Color(0, 0, 0, 0)[/code].
+ If [code]true[/code], enables a window manager hint that the main window background [i]can[/i] be transparent. This does not make the background actually transparent. For the background to be transparent, the root viewport must also be made transparent by enabling [member rendering/transparent_background].
+ [b]Note:[/b] To use a transparent splash screen, set [member application/boot_splash/bg_color] to [code]Color(0, 0, 0, 0)[/code].
[b]Note:[/b] This setting has no effect if [member display/window/per_pixel_transparency/allowed] is set to [code]false[/code].
</member>
<member name="display/window/size/viewport_height" type="int" setter="" getter="" default="648">
@@ -820,6 +830,13 @@
</member>
<member name="input/ui_swap_input_direction" type="Dictionary" setter="" getter="">
</member>
+ <member name="input/ui_text_add_selection_for_next_occurrence" type="Dictionary" setter="" getter="">
+ If a selection is currently active with the last caret in text fields, searches for the next occurrence of the selection, adds a caret and selects the next occurrence.
+ If no selection is currently active with the last caret in text fields, selects the word currently under the caret.
+ The action can be performed sequentially for all occurrences of the selection of the last caret and for all existing carets.
+ The viewport is adjusted to the latest newly added caret.
+ [b]Note:[/b] Default [code]ui_*[/code] actions cannot be removed as they are necessary for the internal logic of several [Control]s. The events assigned to the action can however be modified.
+ </member>
<member name="input/ui_text_backspace" type="Dictionary" setter="" getter="">
Default [InputEventAction] to delete the character before the text cursor.
[b]Note:[/b] Default [code]ui_*[/code] actions cannot be removed as they are necessary for the internal logic of several [Control]s. The events assigned to the action can however be modified.
@@ -974,7 +991,7 @@
</member>
<member name="input/ui_text_select_word_under_caret" type="Dictionary" setter="" getter="">
If no selection is currently active, selects the word currently under the caret in text fields. If a selection is currently active, deselects the current selection.
- [b]Note:[/b] Currently, this is only implemented in [TextEdit], not [LineEdit].
+ [b]Note:[/b] Default [code]ui_*[/code] actions cannot be removed as they are necessary for the internal logic of several [Control]s. The events assigned to the action can however be modified.
</member>
<member name="input/ui_text_submit" type="Dictionary" setter="" getter="">
Default [InputEventAction] to submit a text field.
@@ -1801,7 +1818,9 @@
Another way to combat specular aliasing is to enable [member rendering/anti_aliasing/screen_space_roughness_limiter/enabled].
</member>
<member name="rendering/anti_aliasing/quality/use_debanding" type="bool" setter="" getter="" default="false">
- If [code]true[/code], uses a fast post-processing dithering filter on the default screen [Viewport] to make banding significantly less visible. In some cases, the dithering pattern may be slightly noticable. Note that this will make losslessly compressed (PNG etc.) screenshots larger.
+ If [code]true[/code], uses a fast post-processing filter to make banding significantly less visible in 3D. 2D rendering is [i]not[/i] affected by debanding unless the [member Environment.background_mode] is [constant Environment.BG_CANVAS].
+ In some cases, debanding may introduce a slightly noticeable dithering pattern. It's recommended to enable debanding only when actually needed since the dithering pattern will make lossless-compressed screenshots larger.
+ [b]Note:[/b] This property is only read when the project starts. To set debanding at run-time, set [member Viewport.use_debanding] on the root [Viewport] instead.
</member>
<member name="rendering/anti_aliasing/quality/use_taa" type="bool" setter="" getter="" default="false">
Enables Temporal Anti-Aliasing for the default screen [Viewport]. TAA works by jittering the camera and accumulating the images of the last rendered frames, motion vector rendering is used to account for camera and object motion. Enabling TAA can make the image blurrier, which is partially counteracted by automatically using a negative mipmap LOD bias (see [member rendering/textures/default_filters/texture_mipmap_bias]).
@@ -2100,8 +2119,6 @@
<member name="rendering/renderer/rendering_method.web" type="String" setter="" getter="" default="&quot;gl_compatibility&quot;">
Override for [member rendering/renderer/rendering_method] on web.
</member>
- <member name="rendering/rendering_device/descriptor_pools/max_descriptors_per_pool" type="int" setter="" getter="" default="64">
- </member>
<member name="rendering/rendering_device/driver" type="String" setter="" getter="" default="&quot;vulkan&quot;">
Sets the driver to be used by the renderer when using a RenderingDevice-based renderer like the clustered renderer or the mobile renderer. This property can not be edited directly, instead, set the driver using the platform-specific overrides.
</member>
@@ -2126,6 +2143,8 @@
</member>
<member name="rendering/rendering_device/staging_buffer/texture_upload_region_size_px" type="int" setter="" getter="" default="64">
</member>
+ <member name="rendering/rendering_device/vulkan/max_descriptors_per_pool" type="int" setter="" getter="" default="64">
+ </member>
<member name="rendering/scaling_3d/fsr_sharpness" type="float" setter="" getter="" default="0.2">
Determines how sharp the upscaled image will be when using the FSR upscaling mode. Sharpness halves with every whole number. Values go from 0.0 (sharpest) to 2.0. Values above 2.0 won't make a visible difference.
</member>
@@ -2202,6 +2221,9 @@
If [code]true[/code], the texture importer will import VRAM-compressed textures using the S3 Texture Compression algorithm. This algorithm is only supported on desktop platforms and consoles.
[b]Note:[/b] Changing this setting does [i]not[/i] impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the [code].godot/imported/[/code] folder located inside the project folder then restart the editor (see [member application/config/use_hidden_project_data_directory]).
</member>
+ <member name="rendering/transparent_background" type="bool" setter="" getter="" default="false">
+ If [code]true[/code], enables [member Viewport.transparent_bg] on the root viewport. This allows per-pixel transparency to be effective after also enabling [member display/window/size/transparent] and [member display/window/per_pixel_transparency/allowed].
+ </member>
<member name="rendering/vrs/mode" type="int" setter="" getter="" default="0">
Set the default Variable Rate Shading (VRS) mode for the main viewport. See [member Viewport.vrs_mode] to change this at runtime, and [enum Viewport.VRSMode] for possible values.
</member>
diff --git a/doc/classes/Projection.xml b/doc/classes/Projection.xml
index 5690ea5e95..602833bca5 100644
--- a/doc/classes/Projection.xml
+++ b/doc/classes/Projection.xml
@@ -1,8 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Projection" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
+ 3D projection (4x4 matrix).
</brief_description>
<description>
+ A 4x4 matrix used for 3D projective transformations. It can represent transformations such as translation, rotation, scaling, shearing, and perspective division. It consists of four [Vector4] columns.
+ For purely linear transformations (translation, rotation, and scale), it is recommended to use [Transform3D], as it is more performant and has a lower memory footprint.
+ Used internally as [Camera3D]'s projection matrix.
</description>
<tutorials>
</tutorials>
@@ -10,18 +14,21 @@
<constructor name="Projection">
<return type="Projection" />
<description>
+ Constructs a default-initialized [Projection] set to [constant IDENTITY].
</description>
</constructor>
<constructor name="Projection">
<return type="Projection" />
<param index="0" name="from" type="Projection" />
<description>
+ Constructs a [Projection] as a copy of the given [Projection].
</description>
</constructor>
<constructor name="Projection">
<return type="Projection" />
<param index="0" name="from" type="Transform3D" />
<description>
+ Constructs a Projection as a copy of the given [Transform3D].
</description>
</constructor>
<constructor name="Projection">
@@ -40,12 +47,14 @@
<return type="Projection" />
<param index="0" name="flip_y" type="bool" />
<description>
+ Creates a new [Projection] that projects positions from a depth range of [code]-1[/code] to [code]1[/code] to one that ranges from [code]0[/code] to [code]1[/code], and flips the projected positions vertically, according to [param flip_y].
</description>
</method>
<method name="create_fit_aabb" qualifiers="static">
<return type="Projection" />
<param index="0" name="aabb" type="AABB" />
<description>
+ Creates a new [Projection] that scales a given projection to fit around a given [AABB] in projection space.
</description>
</method>
<method name="create_for_hmd" qualifiers="static">
@@ -59,6 +68,8 @@
<param index="6" name="z_near" type="float" />
<param index="7" name="z_far" type="float" />
<description>
+ Creates a new [Projection] for projecting positions onto a head-mounted display with the given X:Y aspect ratio, distance between eyes, display width, distance to lens, oversampling factor, and depth clipping planes.
+ [param eye] creates the projection for the left eye when set to 1, or the right eye when set to 2.
</description>
</method>
<method name="create_frustum" qualifiers="static">
@@ -70,6 +81,7 @@
<param index="4" name="z_near" type="float" />
<param index="5" name="z_far" type="float" />
<description>
+ Creates a new [Projection] that projects positions in a frustum with the given clipping planes.
</description>
</method>
<method name="create_frustum_aspect" qualifiers="static">
@@ -81,12 +93,15 @@
<param index="4" name="z_far" type="float" />
<param index="5" name="flip_fov" type="bool" default="false" />
<description>
+ Creates a new [Projection] that projects positions in a frustum with the given size, X:Y aspect ratio, offset, and clipping planes.
+ [param flip_fov] determines whether the projection's field of view is flipped over its diagonal.
</description>
</method>
<method name="create_light_atlas_rect" qualifiers="static">
<return type="Projection" />
<param index="0" name="rect" type="Rect2" />
<description>
+ Creates a new [Projection] that projects positions into the given [Rect2].
</description>
</method>
<method name="create_orthogonal" qualifiers="static">
@@ -98,6 +113,7 @@
<param index="4" name="z_near" type="float" />
<param index="5" name="z_far" type="float" />
<description>
+ Creates a new [Projection] that projects positions using an orthogonal projection with the given clipping planes.
</description>
</method>
<method name="create_orthogonal_aspect" qualifiers="static">
@@ -108,6 +124,8 @@
<param index="3" name="z_far" type="float" />
<param index="4" name="flip_fov" type="bool" default="false" />
<description>
+ Creates a new [Projection] that projects positions using an orthogonal projection with the given size, X:Y aspect ratio, and clipping planes.
+ [param flip_fov] determines whether the projection's field of view is flipped over its diagonal.
</description>
</method>
<method name="create_perspective" qualifiers="static">
@@ -118,6 +136,8 @@
<param index="3" name="z_far" type="float" />
<param index="4" name="flip_fov" type="bool" default="false" />
<description>
+ Creates a new [Projection] that projects positions using a perspective projection with the given Y-axis field of view (in degrees), X:Y aspect ratio, and clipping planes.
+ [param flip_fov] determines whether the projection's field of view is flipped over its diagonal.
</description>
</method>
<method name="create_perspective_hmd" qualifiers="static">
@@ -131,31 +151,40 @@
<param index="6" name="intraocular_dist" type="float" />
<param index="7" name=" convergence_dist" type="float" />
<description>
+ Creates a new [Projection] that projects positions using a perspective projection with the given Y-axis field of view (in degrees), X:Y aspect ratio, and clipping distances. The projection is adjusted for a head-mounted display with the given distance between eyes and distance to a point that can be focused on.
+ [param eye] creates the projection for the left eye when set to 1, or the right eye when set to 2.
+ [param flip_fov] determines whether the projection's field of view is flipped over its diagonal.
</description>
</method>
<method name="determinant" qualifiers="const">
<return type="float" />
<description>
+ Returns a scalar value that is the signed factor by which areas are scaled by this matrix. If the sign is negative, the matrix flips the orientation of the area.
+ The determinant can be used to calculate the invertibility of a matrix or solve linear systems of equations involving the matrix, among other applications.
</description>
</method>
<method name="flipped_y" qualifiers="const">
<return type="Projection" />
<description>
+ Returns a copy of this [Projection] with the signs of the values of the Y column flipped.
</description>
</method>
<method name="get_aspect" qualifiers="const">
<return type="float" />
<description>
+ Returns the X:Y aspect ratio of this [Projection]'s viewport.
</description>
</method>
<method name="get_far_plane_half_extents" qualifiers="const">
<return type="Vector2" />
<description>
+ Returns the dimensions of the far clipping plane of the projection, divided by two.
</description>
</method>
<method name="get_fov" qualifiers="const">
<return type="float" />
<description>
+ Returns the horizontal field of view of the projection (in degrees).
</description>
</method>
<method name="get_fovy" qualifiers="static">
@@ -163,89 +192,114 @@
<param index="0" name="fovx" type="float" />
<param index="1" name="aspect" type="float" />
<description>
+ Returns the vertical field of view of the projection (in degrees) associated with the given horizontal field of view (in degrees) and aspect ratio.
</description>
</method>
<method name="get_lod_multiplier" qualifiers="const">
<return type="float" />
<description>
+ Returns the factor by which the visible level of detail is scaled by this [Projection].
</description>
</method>
<method name="get_pixels_per_meter" qualifiers="const">
<return type="int" />
<param index="0" name="for_pixel_width" type="int" />
<description>
+ Returns the number of pixels with the given pixel width displayed per meter, after this [Projection] is applied.
</description>
</method>
<method name="get_projection_plane" qualifiers="const">
<return type="Plane" />
<param index="0" name="plane" type="int" />
<description>
+ Returns the clipping plane of this [Projection] whose index is given by [param plane].
+ [param plane] should be equal to one of [constant PLANE_NEAR], [constant PLANE_FAR], [constant PLANE_LEFT], [constant PLANE_TOP], [constant PLANE_RIGHT], or [constant PLANE_BOTTOM].
</description>
</method>
<method name="get_viewport_half_extents" qualifiers="const">
<return type="Vector2" />
<description>
+ Returns the dimensions of the viewport plane that this [Projection] projects positions onto, divided by two.
</description>
</method>
<method name="get_z_far" qualifiers="const">
<return type="float" />
<description>
+ Returns the distance for this [Projection] beyond which positions are clipped.
</description>
</method>
<method name="get_z_near" qualifiers="const">
<return type="float" />
<description>
+ Returns the distance for this [Projection] before which positions are clipped.
</description>
</method>
<method name="inverse" qualifiers="const">
<return type="Projection" />
<description>
+ Returns a [Projection] that performs the inverse of this [Projection]'s projective transformation.
</description>
</method>
<method name="is_orthogonal" qualifiers="const">
<return type="bool" />
<description>
+ Returns [code]true[/code] if this [Projection] performs an orthogonal projection.
</description>
</method>
<method name="jitter_offseted" qualifiers="const">
<return type="Projection" />
<param index="0" name="offset" type="Vector2" />
<description>
+ Returns a [Projection] with the X and Y values from the given [Vector2] added to the first and second values of the final column respectively.
</description>
</method>
<method name="perspective_znear_adjusted" qualifiers="const">
<return type="Projection" />
<param index="0" name="new_znear" type="float" />
<description>
+ Returns a [Projection] with the near clipping distance adjusted to be [param new_znear].
+ [b]Note:[/b] The original [Projection] must be a perspective projection.
</description>
</method>
</methods>
<members>
<member name="w" type="Vector4" setter="" getter="" default="Vector4(0, 0, 0, 1)">
+ The projection matrix's W vector (column 3). Equivalent to array index [code]3[/code].
</member>
<member name="x" type="Vector4" setter="" getter="" default="Vector4(1, 0, 0, 0)">
+ The projection matrix's X vector (column 0). Equivalent to array index [code]0[/code].
</member>
<member name="y" type="Vector4" setter="" getter="" default="Vector4(0, 1, 0, 0)">
+ The projection matrix's Y vector (column 1). Equivalent to array index [code]1[/code].
</member>
<member name="z" type="Vector4" setter="" getter="" default="Vector4(0, 0, 1, 0)">
+ The projection matrix's Z vector (column 2). Equivalent to array index [code]2[/code].
</member>
</members>
<constants>
<constant name="PLANE_NEAR" value="0">
+ The index value of the projection's near clipping plane.
</constant>
<constant name="PLANE_FAR" value="1">
+ The index value of the projection's far clipping plane.
</constant>
<constant name="PLANE_LEFT" value="2">
+ The index value of the projection's left clipping plane.
</constant>
<constant name="PLANE_TOP" value="3">
+ The index value of the projection's top clipping plane.
</constant>
<constant name="PLANE_RIGHT" value="4">
+ The index value of the projection's right clipping plane.
</constant>
<constant name="PLANE_BOTTOM" value="5">
+ The index value of the projection bottom clipping plane.
</constant>
<constant name="IDENTITY" value="Projection(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)">
+ A [Projection] with no transformation defined. When applied to other data structures, no transformation is performed.
</constant>
<constant name="ZERO" value="Projection(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)">
+ A [Projection] with all values initialized to 0. When applied to other data structures, they will be zeroed.
</constant>
</constants>
<operators>
@@ -253,30 +307,38 @@
<return type="bool" />
<param index="0" name="right" type="Projection" />
<description>
+ Returns [code]true[/code] if the projections are not equal.
+ [b]Note:[/b] Due to floating-point precision errors, this may return [code]true[/code], even if the projections are virtually equal. An [code]is_equal_approx[/code] method may be added in a future version of Godot.
</description>
</operator>
<operator name="operator *">
<return type="Projection" />
<param index="0" name="right" type="Projection" />
<description>
+ Returns a [Projection] that applies the combined transformations of this [Projection] and [param right].
</description>
</operator>
<operator name="operator *">
<return type="Vector4" />
<param index="0" name="right" type="Vector4" />
<description>
+ Projects (multiplies) the given [Vector4] by this [Projection] matrix.
</description>
</operator>
<operator name="operator ==">
<return type="bool" />
<param index="0" name="right" type="Projection" />
<description>
+ Returns [code]true[/code] if the projections are equal.
+ [b]Note:[/b] Due to floating-point precision errors, this may return [code]false[/code], even if the projections are virtually equal. An [code]is_equal_approx[/code] method may be added in a future version of Godot.
</description>
</operator>
<operator name="operator []">
<return type="Vector4" />
<param index="0" name="index" type="int" />
<description>
+ Returns the column of the [Projection] with the given index.
+ Indices are in the following order: x, y, z, w.
</description>
</operator>
</operators>
diff --git a/doc/classes/PropertyTweener.xml b/doc/classes/PropertyTweener.xml
index 75d9c919aa..78ead65cdd 100644
--- a/doc/classes/PropertyTweener.xml
+++ b/doc/classes/PropertyTweener.xml
@@ -27,7 +27,7 @@
Sets a custom initial value to the [PropertyTweener]. Example:
[codeblock]
var tween = get_tree().create_tween()
- tween.tween_property(self, "position", Vector2(200, 100), 1).from(Vector2(100, 100) #this will move the node from position (100, 100) to (200, 100)
+ tween.tween_property(self, "position", Vector2(200, 100), 1).from(Vector2(100, 100)) #this will move the node from position (100, 100) to (200, 100)
[/codeblock]
</description>
</method>
diff --git a/doc/classes/Quaternion.xml b/doc/classes/Quaternion.xml
index f21ebf57e2..99dffeff9d 100644
--- a/doc/classes/Quaternion.xml
+++ b/doc/classes/Quaternion.xml
@@ -115,6 +115,12 @@
Returns [code]true[/code] if this quaternion and [param to] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this quaternion is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="is_normalized" qualifiers="const">
<return type="bool" />
<description>
diff --git a/doc/classes/RDPipelineRasterizationState.xml b/doc/classes/RDPipelineRasterizationState.xml
index 39a64c730a..48599b6262 100644
--- a/doc/classes/RDPipelineRasterizationState.xml
+++ b/doc/classes/RDPipelineRasterizationState.xml
@@ -13,7 +13,7 @@
</member>
<member name="depth_bias_constant_factor" type="float" setter="set_depth_bias_constant_factor" getter="get_depth_bias_constant_factor" default="0.0">
</member>
- <member name="depth_bias_enable" type="bool" setter="set_depth_bias_enable" getter="get_depth_bias_enable" default="false">
+ <member name="depth_bias_enabled" type="bool" setter="set_depth_bias_enabled" getter="get_depth_bias_enabled" default="false">
</member>
<member name="depth_bias_slope_factor" type="float" setter="set_depth_bias_slope_factor" getter="get_depth_bias_slope_factor" default="0.0">
</member>
diff --git a/doc/classes/RandomNumberGenerator.xml b/doc/classes/RandomNumberGenerator.xml
index b8a290381f..a6254788ce 100644
--- a/doc/classes/RandomNumberGenerator.xml
+++ b/doc/classes/RandomNumberGenerator.xml
@@ -10,10 +10,9 @@
[codeblock]
var rng = RandomNumberGenerator.new()
func _ready():
- rng.randomize()
var my_random_number = rng.randf_range(-10.0, 10.0)
[/codeblock]
- [b]Note:[/b] The default values of [member seed] and [member state] properties are pseudo-random, and changes when calling [method randomize]. The [code]0[/code] value documented here is a placeholder, and not the actual default seed.
+ [b]Note:[/b] The default values of [member seed] and [member state] properties are pseudo-random, and change when calling [method randomize]. The [code]0[/code] value documented here is a placeholder, and not the actual default seed.
</description>
<tutorials>
<link title="Random number generation">$DOCS_URL/tutorials/math/random_number_generation.html</link>
diff --git a/doc/classes/Rect2.xml b/doc/classes/Rect2.xml
index ac012e9604..28fe42afae 100644
--- a/doc/classes/Rect2.xml
+++ b/doc/classes/Rect2.xml
@@ -165,6 +165,12 @@
Returns [code]true[/code] if this [Rect2] and [param rect] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this [Rect2] is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="merge" qualifiers="const">
<return type="Rect2" />
<param index="0" name="b" type="Rect2" />
diff --git a/doc/classes/RenderingDevice.xml b/doc/classes/RenderingDevice.xml
index eb85a4adb4..51c2498ea7 100644
--- a/doc/classes/RenderingDevice.xml
+++ b/doc/classes/RenderingDevice.xml
@@ -1581,6 +1581,10 @@
</constant>
<constant name="LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z" value="34" enum="Limit">
</constant>
+ <constant name="LIMIT_MAX_VIEWPORT_DIMENSIONS_X" value="35" enum="Limit">
+ </constant>
+ <constant name="LIMIT_MAX_VIEWPORT_DIMENSIONS_Y" value="36" enum="Limit">
+ </constant>
<constant name="MEMORY_TEXTURES" value="0" enum="MemoryType">
</constant>
<constant name="MEMORY_BUFFERS" value="1" enum="MemoryType">
diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml
index 6aa9237385..376ba34056 100644
--- a/doc/classes/RenderingServer.xml
+++ b/doc/classes/RenderingServer.xml
@@ -4576,9 +4576,11 @@
</constant>
<constant name="CANVAS_GROUP_MODE_DISABLED" value="0" enum="CanvasGroupMode">
</constant>
- <constant name="CANVAS_GROUP_MODE_OPAQUE" value="1" enum="CanvasGroupMode">
+ <constant name="CANVAS_GROUP_MODE_CLIP_ONLY" value="1" enum="CanvasGroupMode">
</constant>
- <constant name="CANVAS_GROUP_MODE_TRANSPARENT" value="2" enum="CanvasGroupMode">
+ <constant name="CANVAS_GROUP_MODE_CLIP_AND_DRAW" value="2" enum="CanvasGroupMode">
+ </constant>
+ <constant name="CANVAS_GROUP_MODE_TRANSPARENT" value="3" enum="CanvasGroupMode">
</constant>
<constant name="CANVAS_LIGHT_MODE_POINT" value="0" enum="CanvasLightMode">
</constant>
diff --git a/doc/classes/Resource.xml b/doc/classes/Resource.xml
index 3adf10da2d..b2b8a37e39 100644
--- a/doc/classes/Resource.xml
+++ b/doc/classes/Resource.xml
@@ -4,7 +4,8 @@
Base class for all resources.
</brief_description>
<description>
- Resource is the base class for all Godot-specific resource types, serving primarily as data containers. Since they inherit from [RefCounted], resources are reference-counted and freed when no longer in use. They are also cached once loaded from disk, so that any further attempts to load a resource from a given path will return the same reference (all this in contrast to a [Node], which is not reference-counted and can be instantiated from disk as many times as desired). Resources can be saved externally on disk or bundled into another object, such as a [Node] or another resource.
+ Resource is the base class for all Godot-specific resource types, serving primarily as data containers. Since they inherit from [RefCounted], resources are reference-counted and freed when no longer in use. They can also be nested within other resources, and saved on disk. Once loaded from disk, further attempts to load a resource by [member resource_path] returns the same reference. [PackedScene], one of the most common [Object]s in a Godot project, is also a resource, uniquely capable of storing and instantiating the [Node]s it contains as many times as desired.
+ In GDScript, resources can loaded from disk by their [member resource_path] using [method @GDScript.load] or [method @GDScript.preload].
[b]Note:[/b] In C#, resources will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free resources that are no longer in use. This means that unused resources will linger on for a while before being removed.
</description>
<tutorials>
@@ -15,77 +16,94 @@
<method name="_get_rid" qualifiers="virtual">
<return type="RID" />
<description>
+ Override this method to return a custom [RID] when [method get_rid] is called.
</description>
</method>
<method name="duplicate" qualifiers="const">
<return type="Resource" />
<param index="0" name="subresources" type="bool" default="false" />
<description>
- Duplicates the resource, returning a new resource with the exported members copied. [b]Note:[/b] To duplicate the resource the constructor is called without arguments. This method will error when the constructor doesn't have default values.
- By default, sub-resources are shared between resource copies for efficiency. This can be changed by passing [code]true[/code] to the [param subresources] argument which will copy the subresources.
- [b]Note:[/b] If [param subresources] is [code]true[/code], this method will only perform a shallow copy. Nested resources within subresources will not be duplicated and will still be shared.
- [b]Note:[/b] When duplicating a resource, only [code]export[/code]ed properties are copied. Other properties will be set to their default value in the new resource.
+ Duplicates this resource, returning a new resource with its [code]export[/code]ed or [constant PROPERTY_USAGE_STORAGE] properties copied from the original.
+ If [param subresources] is [code]false[/code], a shallow copy is returned. Nested resources within subresources are not duplicated and are shared from the original resource. This behavior can be overriden by the [constant PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE] flag.
+ [b]Note:[/b] For custom resources, this method will fail if [method Object._init] has been defined with required parameters.
</description>
</method>
<method name="emit_changed">
<return type="void" />
<description>
- Emits the [signal changed] signal.
- If external objects which depend on this resource should be updated, this method must be called manually whenever the state of this resource has changed (such as modification of properties).
- The method is equivalent to:
+ Emits the [signal changed] signal. This method is called automatically for built-in resources.
+ [b]Note:[/b] For custom resources, it's recommended to call this method whenever a meaningful change occurs, such as a modified property. This ensures that custom [Object]s depending on the resource are properly updated.
[codeblock]
- emit_signal("changed")
+ var damage:
+ set(new_value):
+ if damage != new_value:
+ damage = new_value
+ emit_changed()
[/codeblock]
- [b]Note:[/b] This method is called automatically for built-in resources.
</description>
</method>
<method name="get_local_scene" qualifiers="const">
<return type="Node" />
<description>
- If [member resource_local_to_scene] is enabled and the resource was loaded from a [PackedScene] instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns [code]null[/code].
+ If [member resource_local_to_scene] is set to [code]true[/code] and the resource has been loaded from a [PackedScene] instantiation, returns the root [Node] of the scene where this resource is used. Otherwise, returns [code]null[/code].
</description>
</method>
<method name="get_rid" qualifiers="const">
<return type="RID" />
<description>
- Returns the RID of the resource (or an empty RID). Many resources (such as [Texture2D], [Mesh], etc) are high-level abstractions of resources stored in a server, so this function will return the original RID.
+ Returns the [RID] of this resource (or an empty RID). Many resources (such as [Texture2D], [Mesh], and so on) are high-level abstractions of resources stored in a specialised server ([DisplayServer], [RenderingServer], etc.), so this function will return the original [RID].
</description>
</method>
<method name="setup_local_to_scene">
<return type="void" />
<description>
- This method is called when a resource with [member resource_local_to_scene] enabled is loaded from a [PackedScene] instantiation. Its behavior can be customized by connecting [signal setup_local_to_scene_requested] from script.
- For most resources, this method performs no base logic. [ViewportTexture] performs custom logic to properly set the proxy texture and flags in the local viewport.
+ Emits the [signal setup_local_to_scene_requested] signal. If [member resource_local_to_scene] is set to [code]true[/code], this method is called from [method PackedScene.instantiate] by the newly duplicated resource within the scene instance.
+ For most resources, this method performs no logic of its own. Custom behavior can be defined by connecting [signal setup_local_to_scene_requested] from a script, [b]not[/b] by overriding this method.
+ [b]Example:[/b] Assign a random value to [code]health[/code] for every duplicated Resource from an instantiated scene, excluding the original.
+ [codeblock]
+ extends Resource
+
+ var health = 0
+
+ func _init():
+ setup_local_to_scene_requested.connect(randomize_health)
+
+ func randomize_health():
+ health = randi_range(10, 40)
+ [/codeblock]
</description>
</method>
<method name="take_over_path">
<return type="void" />
<param index="0" name="path" type="String" />
<description>
- Sets the path of the resource, potentially overriding an existing cache entry for this path. This differs from setting [member resource_path], as the latter would error out if another resource was already cached for the given path.
+ Sets the [member resource_path] to [param path], potentially overriding an existing cache entry for this path. Further attempts to load an overridden resource by path will instead return this resource.
</description>
</method>
</methods>
<members>
<member name="resource_local_to_scene" type="bool" setter="set_local_to_scene" getter="is_local_to_scene" default="false">
- If [code]true[/code], the resource will be made unique in each instance of its local scene. It can thus be modified in a scene instance without impacting other instances of that same scene.
+ If [code]true[/code], the resource is duplicated for each instance of all scenes using it. At run-time, the resource can be modified in one scene without affecting other instances (see [method PackedScene.instantiate]).
+ [b]Note:[/b] Changing this property at run-time has no effect on already created duplicate resources.
</member>
<member name="resource_name" type="String" setter="set_name" getter="get_name" default="&quot;&quot;">
- The name of the resource. This is an optional identifier. If [member resource_name] is not empty, its value will be displayed to represent the current resource in the editor inspector. For built-in scripts, the [member resource_name] will be displayed as the tab name in the script editor.
+ An optional name for this resource. When defined, its value is displayed to represent the resource in the Inspector dock. For built-in scripts, the name is displayed as part of the tab name in the script editor.
</member>
<member name="resource_path" type="String" setter="set_path" getter="get_path" default="&quot;&quot;">
- The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
+ The unique path to this resource. If it has been saved to disk, the value will be its filepath. If the resource is exclusively contained within a scene, the value will be the [PackedScene]'s filepath, followed by an unique identifier.
+ [b]Note:[/b] Setting this property manually may fail if a resource with the same path has already been previously loaded. If necessary, use [method take_over_path].
</member>
</members>
<signals>
<signal name="changed">
<description>
- Emitted whenever the resource changes.
- [b]Note:[/b] This signal is not emitted automatically for custom resources, which means that you need to create a setter and emit the signal yourself.
+ Emitted when the resource changes, usually when one of its properties is modified. See also [method emit_changed].
+ [b]Note:[/b] This signal is not emitted automatically for properties of custom resources. If necessary, a setter needs to be created to emit the signal.
</description>
</signal>
<signal name="setup_local_to_scene_requested">
<description>
+ Emitted when [method setup_local_to_scene] is called, usually by a newly duplicated resource with [member resource_local_to_scene] set to [code]true[/code]. Custom behavior can be defined by connecting this signal.
</description>
</signal>
</signals>
diff --git a/doc/classes/ResourceFormatLoader.xml b/doc/classes/ResourceFormatLoader.xml
index 9b8c8d4d9d..2b6376f2cd 100644
--- a/doc/classes/ResourceFormatLoader.xml
+++ b/doc/classes/ResourceFormatLoader.xml
@@ -71,6 +71,15 @@
The [param cache_mode] property defines whether and how the cache should be used or updated when loading the resource. See [enum CacheMode] for details.
</description>
</method>
+ <method name="_recognize_path" qualifiers="virtual const">
+ <return type="bool" />
+ <param index="0" name="path" type="String" />
+ <param index="1" name="type" type="StringName" />
+ <description>
+ Tells whether or not this loader should load a resource from its resource path for a given type.
+ If it is not implemented, the default behavior returns whether the path's extension is within the ones provided by [method _get_recognized_extensions], and if the type is within the ones provided by [method _get_resource_type].
+ </description>
+ </method>
<method name="_rename_dependencies" qualifiers="virtual const">
<return type="int" />
<param index="0" name="path" type="String" />
diff --git a/doc/classes/ResourceFormatSaver.xml b/doc/classes/ResourceFormatSaver.xml
index 05bfcf3446..1f2af6d157 100644
--- a/doc/classes/ResourceFormatSaver.xml
+++ b/doc/classes/ResourceFormatSaver.xml
@@ -24,6 +24,15 @@
Returns whether the given resource object can be saved by this saver.
</description>
</method>
+ <method name="_recognize_path" qualifiers="virtual const">
+ <return type="bool" />
+ <param index="0" name="resource" type="Resource" />
+ <param index="1" name="path" type="String" />
+ <description>
+ Returns [code]true[/code] if this saver handles a given save path and [code]false[/code] otherwise.
+ If this method is not implemented, the default behavior returns whether the path's extension is within the ones provided by [method _get_recognized_extensions].
+ </description>
+ </method>
<method name="_save" qualifiers="virtual">
<return type="int" />
<param index="0" name="resource" type="Resource" />
diff --git a/doc/classes/RichTextLabel.xml b/doc/classes/RichTextLabel.xml
index f4cbf4c442..b5a917b2bb 100644
--- a/doc/classes/RichTextLabel.xml
+++ b/doc/classes/RichTextLabel.xml
@@ -23,9 +23,11 @@
<param index="2" name="height" type="int" default="0" />
<param index="3" name="color" type="Color" default="Color(1, 1, 1, 1)" />
<param index="4" name="inline_align" type="int" enum="InlineAlignment" default="5" />
+ <param index="5" name="region" type="Rect2" default="Rect2(0, 0, 0, 0)" />
<description>
- Adds an image's opening and closing tags to the tag stack, optionally providing a [param width] and [param height] to resize the image and a [param color] to tint the image.
+ Adds an image's opening and closing tags to the tag stack, optionally providing a [param width] and [param height] to resize the image, a [param color] to tint the image and a [param region] to only use parts of the image.
If [param width] or [param height] is set to 0, the image size will be adjusted in order to keep the original aspect ratio.
+ If [param width] and [param height] are not set, but [param region] is, the region's rect will be used.
</description>
</method>
<method name="add_text">
diff --git a/doc/classes/Script.xml b/doc/classes/Script.xml
index 40ec8ed429..b4b14c01c6 100644
--- a/doc/classes/Script.xml
+++ b/doc/classes/Script.xml
@@ -4,7 +4,7 @@
A class stored as a resource.
</brief_description>
<description>
- A class stored as a resource. A script extends the functionality of all objects that instance it.
+ A class stored as a resource. A script extends the functionality of all objects that instantiate it.
This is the base class for all scripts and should not be used directly. Trying to create a new script with this class will result in an error.
The [code]new[/code] method of a script subclass creates a new instance. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes.
</description>
diff --git a/doc/classes/Shape2D.xml b/doc/classes/Shape2D.xml
index 34ca228795..7be0ba64d6 100644
--- a/doc/classes/Shape2D.xml
+++ b/doc/classes/Shape2D.xml
@@ -66,6 +66,12 @@
Draws a solid shape onto a [CanvasItem] with the [RenderingServer] API filled with the specified [param color]. The exact drawing method is specific for each shape and cannot be configured.
</description>
</method>
+ <method name="get_rect" qualifiers="const">
+ <return type="Rect2" />
+ <description>
+ Returns a [Rect2] representing the shapes boundary.
+ </description>
+ </method>
</methods>
<members>
<member name="custom_solver_bias" type="float" setter="set_custom_solver_bias" getter="get_custom_solver_bias" default="0.0">
diff --git a/doc/classes/SkeletonProfile.xml b/doc/classes/SkeletonProfile.xml
index 55d21f3224..57bdd52d9e 100644
--- a/doc/classes/SkeletonProfile.xml
+++ b/doc/classes/SkeletonProfile.xml
@@ -7,6 +7,7 @@
This resource is used in [EditorScenePostImport]. Some parameters are referring to bones in [Skeleton3D], [Skin], [Animation], and some other nodes are rewritten based on the parameters of [SkeletonProfile].
</description>
<tutorials>
+ <link title="Retargeting 3D Skeletons">$DOCS_URL/tutorials/assets_pipeline/retargeting_3d_skeletons.html</link>
</tutorials>
<methods>
<method name="find_bone" qualifiers="const">
diff --git a/doc/classes/SkeletonProfileHumanoid.xml b/doc/classes/SkeletonProfileHumanoid.xml
index 11f0521718..0dbd66d8d6 100644
--- a/doc/classes/SkeletonProfileHumanoid.xml
+++ b/doc/classes/SkeletonProfileHumanoid.xml
@@ -6,6 +6,7 @@
A [SkeletonProfile] as a preset that is optimized for the human form. This exists for standardization, so all parameters are read-only.
</description>
<tutorials>
+ <link title="Retargeting 3D Skeletons">$DOCS_URL/tutorials/assets_pipeline/retargeting_3d_skeletons.html</link>
</tutorials>
<members>
<member name="bone_size" type="int" setter="set_bone_size" getter="get_bone_size" overrides="SkeletonProfile" default="56" />
diff --git a/doc/classes/SpotLight3D.xml b/doc/classes/SpotLight3D.xml
index 62cb55daec..28e2ef0d95 100644
--- a/doc/classes/SpotLight3D.xml
+++ b/doc/classes/SpotLight3D.xml
@@ -14,6 +14,7 @@
<member name="shadow_bias" type="float" setter="set_param" getter="get_param" overrides="Light3D" default="0.03" />
<member name="spot_angle" type="float" setter="set_param" getter="get_param" default="45.0">
The spotlight's angle in degrees.
+ [b]Note:[/b] [member spot_angle] is not affected by [member Node3D.scale] (the light's scale or its parent's scale).
</member>
<member name="spot_angle_attenuation" type="float" setter="set_param" getter="get_param" default="1.0">
The spotlight's angular attenuation curve.
@@ -23,6 +24,7 @@
</member>
<member name="spot_range" type="float" setter="set_param" getter="get_param" default="5.0">
The maximal range that can be reached by the spotlight. Note that the effectively lit area may appear to be smaller depending on the [member spot_attenuation] in use. No matter the [member spot_attenuation] in use, the light will never reach anything outside this range.
+ [b]Note:[/b] [member spot_range] is not affected by [member Node3D.scale] (the light's scale or its parent's scale).
</member>
</members>
</class>
diff --git a/doc/classes/StandardMaterial3D.xml b/doc/classes/StandardMaterial3D.xml
index bd6e5cdfa2..0f6a3168eb 100644
--- a/doc/classes/StandardMaterial3D.xml
+++ b/doc/classes/StandardMaterial3D.xml
@@ -4,7 +4,7 @@
Physically based rendering (PBR) material that can be applied to 3D objects.
</brief_description>
<description>
- StandardMaterial3D's properties are inherited from [BaseMaterial3D].
+ [StandardMaterial3D]'s properties are inherited from [BaseMaterial3D]. [StandardMaterial3D] uses separate textures for ambient occlusion, roughness and metallic maps. To use a single ORM map for all 3 textures, use an [ORMMaterial3D] instead.
</description>
<tutorials>
<link title="Standard Material 3D and ORM Material 3D">$DOCS_URL/tutorials/3d/standard_material_3d.html</link>
diff --git a/doc/classes/String.xml b/doc/classes/String.xml
index 316bb923b7..320b9fd737 100644
--- a/doc/classes/String.xml
+++ b/doc/classes/String.xml
@@ -364,7 +364,7 @@
<return type="bool" />
<param index="0" name="with_prefix" type="bool" default="false" />
<description>
- Returns [code]true[/code] if this string contains a valid hexadecimal number. If [param with_prefix] is [code]true[/code], then a validity of the hexadecimal number is determined by [code]0x[/code] prefix, for instance: [code]0xDEADC0DE[/code].
+ Returns [code]true[/code] if this string contains a valid hexadecimal number. If [param with_prefix] is [code]true[/code], then a validity of the hexadecimal number is determined by the [code]0x[/code] prefix, for example: [code]0xDEADC0DE[/code].
</description>
</method>
<method name="is_valid_html_color" qualifiers="const">
diff --git a/doc/classes/SurfaceTool.xml b/doc/classes/SurfaceTool.xml
index ccec691107..d56cc9a31b 100644
--- a/doc/classes/SurfaceTool.xml
+++ b/doc/classes/SurfaceTool.xml
@@ -133,6 +133,7 @@
<description>
Generates normals from vertices so you do not have to do it manually. If [param flip] is [code]true[/code], the resulting normals will be inverted. [method generate_normals] should be called [i]after[/i] generating geometry and [i]before[/i] committing the mesh using [method commit] or [method commit_to_arrays]. For correct display of normal-mapped surfaces, you will also have to generate tangents using [method generate_tangents].
[b]Note:[/b] [method generate_normals] only works if the primitive type to be set to [constant Mesh.PRIMITIVE_TRIANGLES].
+ [b]Note:[/b] [method generate_normals] takes smooth groups into account. If you don't specify any smooth group for each vertex, [method generate_normals] will smooth normals for you.
</description>
</method>
<method name="generate_tangents">
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index 2f9b971fc8..879a355f25 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -70,6 +70,12 @@
Register a new gutter to this [TextEdit]. Use [param at] to have a specific gutter order. A value of [code]-1[/code] appends the gutter to the right.
</description>
</method>
+ <method name="add_selection_for_next_occurrence">
+ <return type="void" />
+ <description>
+ Adds a selection and a caret for the next occurrence of the current selection. If there is no active selection, selects word under caret.
+ </description>
+ </method>
<method name="adjust_carets_after_edit">
<return type="void" />
<param index="0" name="caret" type="int" />
@@ -240,6 +246,12 @@
Returns the width of the gutter at the given index.
</description>
</method>
+ <method name="get_h_scroll_bar" qualifiers="const">
+ <return type="HScrollBar" />
+ <description>
+ Returns the [HScrollBar] used by [TextEdit].
+ </description>
+ </method>
<method name="get_indent_level" qualifiers="const">
<return type="int" />
<param index="0" name="line" type="int" />
@@ -509,6 +521,12 @@
Returns the number of lines that may be drawn.
</description>
</method>
+ <method name="get_v_scroll_bar" qualifiers="const">
+ <return type="VScrollBar" />
+ <description>
+ Returns the [VScrollBar] of the [TextEdit].
+ </description>
+ </method>
<method name="get_version" qualifiers="const">
<return type="int" />
<description>
diff --git a/doc/classes/TextLine.xml b/doc/classes/TextLine.xml
index 471c1a9040..d1dfdecbd2 100644
--- a/doc/classes/TextLine.xml
+++ b/doc/classes/TextLine.xml
@@ -144,6 +144,7 @@
</methods>
<members>
<member name="alignment" type="int" setter="set_horizontal_alignment" getter="get_horizontal_alignment" enum="HorizontalAlignment" default="0">
+ Sets text alignment within the line as if the line was horizontal.
</member>
<member name="direction" type="int" setter="set_direction" getter="get_direction" enum="TextServer.Direction" default="0">
Text writing direction.
diff --git a/doc/classes/Texture2D.xml b/doc/classes/Texture2D.xml
index 14e89a1b74..3dd8c339b2 100644
--- a/doc/classes/Texture2D.xml
+++ b/doc/classes/Texture2D.xml
@@ -33,7 +33,7 @@
</method>
<method name="_draw_rect_region" qualifiers="virtual const">
<return type="void" />
- <param index="0" name="tp_canvas_item" type="RID" />
+ <param index="0" name="to_canvas_item" type="RID" />
<param index="1" name="rect" type="Rect2" />
<param index="2" name="src_rect" type="Rect2" />
<param index="3" name="modulate" type="Color" />
diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml
index 348184a16a..01246f0c2e 100644
--- a/doc/classes/TileMap.xml
+++ b/doc/classes/TileMap.xml
@@ -365,7 +365,7 @@
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 [constant VISIBILITY_MODE_DEFAULT], this depends on the show navigation debug settings.
+ Show or hide the TileMap's navigation meshes. 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/Transform2D.xml b/doc/classes/Transform2D.xml
index 905b3d77af..23d20a5a75 100644
--- a/doc/classes/Transform2D.xml
+++ b/doc/classes/Transform2D.xml
@@ -123,6 +123,12 @@
Returns [code]true[/code] if this transform and [code]transform[/code] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this transform is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="looking_at" qualifiers="const">
<return type="Transform2D" />
<param index="0" name="target" type="Vector2" default="Vector2(0, 0)" />
diff --git a/doc/classes/Transform3D.xml b/doc/classes/Transform3D.xml
index 18b4f9e6f9..b3145ea022 100644
--- a/doc/classes/Transform3D.xml
+++ b/doc/classes/Transform3D.xml
@@ -82,6 +82,12 @@
Returns [code]true[/code] if this transform and [code]transform[/code] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this transform is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="looking_at" qualifiers="const">
<return type="Transform3D" />
<param index="0" name="target" type="Vector3" />
diff --git a/doc/classes/TreeItem.xml b/doc/classes/TreeItem.xml
index c109dc57f7..a8ffef427f 100644
--- a/doc/classes/TreeItem.xml
+++ b/doc/classes/TreeItem.xml
@@ -425,6 +425,15 @@
Sets the given column's button [Texture2D] at index [param button_idx] to [param button].
</description>
</method>
+ <method name="set_button_color">
+ <return type="void" />
+ <param index="0" name="column" type="int" />
+ <param index="1" name="button_idx" type="int" />
+ <param index="2" name="color" type="Color" />
+ <description>
+ Sets the given column's button color at index [param button_idx] to [param color].
+ </description>
+ </method>
<method name="set_button_disabled">
<return type="void" />
<param index="0" name="column" type="int" />
diff --git a/doc/classes/VSlider.xml b/doc/classes/VSlider.xml
index b30349e538..488154106f 100644
--- a/doc/classes/VSlider.xml
+++ b/doc/classes/VSlider.xml
@@ -33,6 +33,7 @@
The background of the area below the grabber.
</theme_item>
<theme_item name="grabber_area_highlight" data_type="style" type="StyleBox">
+ The background of the area below the grabber, to the left of the grabber.
</theme_item>
<theme_item name="slider" data_type="style" type="StyleBox">
The background for the whole slider. Determines the width of the [code]grabber_area[/code].
diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml
index e1852340c0..5590f82336 100644
--- a/doc/classes/Vector2.xml
+++ b/doc/classes/Vector2.xml
@@ -206,6 +206,12 @@
Returns [code]true[/code] if this vector and [code]v[/code] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this vector is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="is_normalized" qualifiers="const">
<return type="bool" />
<description>
diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml
index 1ef84050cd..1a2cdfe10e 100644
--- a/doc/classes/Vector3.xml
+++ b/doc/classes/Vector3.xml
@@ -174,10 +174,16 @@
Returns [code]true[/code] if this vector and [param to] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this vector is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="is_normalized" qualifiers="const">
<return type="bool" />
<description>
- Returns [code]true[/code] if the vector is normalized, [code]false[/code] otherwise.
+ Returns [code]true[/code] if the vector is [method normalized], [code]false[/code] otherwise.
</description>
</method>
<method name="is_zero_approx" qualifiers="const">
@@ -238,18 +244,22 @@
<method name="normalized" qualifiers="const">
<return type="Vector3" />
<description>
- Returns the vector scaled to unit length. Equivalent to [code]v / v.length()[/code].
+ Returns the vector scaled to unit length. Equivalent to [code]v / v.length()[/code]. See also [method is_normalized].
</description>
</method>
<method name="octahedron_decode" qualifiers="static">
<return type="Vector3" />
<param index="0" name="uv" type="Vector2" />
<description>
+ Returns the [Vector3] from an octahedral-compressed form created using [method octahedron_encode] (stored as a [Vector2]).
</description>
</method>
<method name="octahedron_encode" qualifiers="const">
<return type="Vector2" />
<description>
+ Returns the octahedral-encoded (oct32) form of this [Vector3] as a [Vector2]. Since a [Vector2] occupies 1/3 less memory compared to [Vector3], this form of compression can be used to pass greater amounts of [method normalized] [Vector3]s without increasing storage or memory requirements. See also [method octahedron_decode].
+ [b]Note:[/b] [method octahedron_encode] can only be used for [method normalized] vectors. [method octahedron_encode] does [i]not[/i] check whether this [Vector3] is normalized, and will return a value that does not decompress to the original value if the [Vector3] is not normalized.
+ [b]Note:[/b] Octahedral compression is [i]lossy[/i], although visual differences are rarely perceptible in real world scenarios.
</description>
</method>
<method name="outer" qualifiers="const">
diff --git a/doc/classes/Vector4.xml b/doc/classes/Vector4.xml
index fdc93f82ec..662d0bce3a 100644
--- a/doc/classes/Vector4.xml
+++ b/doc/classes/Vector4.xml
@@ -135,6 +135,12 @@
Returns [code]true[/code] if this vector and [param with] are approximately equal, by running [method @GlobalScope.is_equal_approx] on each component.
</description>
</method>
+ <method name="is_finite" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this vector is finite, by calling [method @GlobalScope.is_finite] on each component.
+ </description>
+ </method>
<method name="is_normalized" qualifiers="const">
<return type="bool" />
<description>
diff --git a/doc/classes/Vector4i.xml b/doc/classes/Vector4i.xml
index 3eea93ce1f..e9ac5b9475 100644
--- a/doc/classes/Vector4i.xml
+++ b/doc/classes/Vector4i.xml
@@ -133,12 +133,20 @@
<return type="Vector4i" />
<param index="0" name="right" type="Vector4i" />
<description>
+ Gets the remainder of each component of the [Vector4i] with the components of the given [Vector4i]. This operation uses truncated division, which is often not desired as it does not work well with negative numbers. Consider using [method @GlobalScope.posmod] instead if you want to handle negative numbers.
+ [codeblock]
+ print(Vector4i(10, -20, 30, -40) % Vector4i(7, 8, 9, 10)) # Prints "(3, -4, 3, 0)"
+ [/codeblock]
</description>
</operator>
<operator name="operator %">
<return type="Vector4i" />
<param index="0" name="right" type="int" />
<description>
+ Gets the remainder of each component of the [Vector4i] with the the given [int]. This operation uses truncated division, which is often not desired as it does not work well with negative numbers. Consider using [method @GlobalScope.posmod] instead if you want to handle negative numbers.
+ [codeblock]
+ print(Vector4i(10, -20, 30, -40) % 7) # Prints "(3, -6, 2, -5)"
+ [/codeblock]
</description>
</operator>
<operator name="operator *">
diff --git a/doc/classes/Viewport.xml b/doc/classes/Viewport.xml
index 998e782975..5706d098e8 100644
--- a/doc/classes/Viewport.xml
+++ b/doc/classes/Viewport.xml
@@ -71,6 +71,12 @@
<description>
</description>
</method>
+ <method name="get_screen_transform" qualifiers="const">
+ <return type="Transform2D" />
+ <description>
+ Returns the transform from the Viewport's coordinates to the screen coordinates of the containing window manager window.
+ </description>
+ </method>
<method name="get_texture" qualifiers="const">
<return type="ViewportTexture" />
<description>
@@ -300,6 +306,8 @@
If [code]true[/code], the viewport should render its background as transparent.
</member>
<member name="use_debanding" type="bool" setter="set_use_debanding" getter="is_using_debanding" default="false">
+ If [code]true[/code], uses a fast post-processing filter to make banding significantly less visible in 3D. 2D rendering is [i]not[/i] affected by debanding unless the [member Environment.background_mode] is [constant Environment.BG_CANVAS]. See also [member ProjectSettings.rendering/anti_aliasing/quality/use_debanding].
+ In some cases, debanding may introduce a slightly noticeable dithering pattern. It's recommended to enable debanding only when actually needed since the dithering pattern will make lossless-compressed screenshots larger.
</member>
<member name="use_occlusion_culling" type="bool" setter="set_use_occlusion_culling" getter="is_using_occlusion_culling" default="false">
If [code]true[/code], [OccluderInstance3D] nodes will be usable for occlusion culling in 3D for this viewport. For the root viewport, [member ProjectSettings.rendering/occlusion_culling/use_occlusion_culling] must be set to [code]true[/code] instead.
diff --git a/doc/classes/ViewportTexture.xml b/doc/classes/ViewportTexture.xml
index 87de664aad..6bd64a50bb 100644
--- a/doc/classes/ViewportTexture.xml
+++ b/doc/classes/ViewportTexture.xml
@@ -6,6 +6,7 @@
<description>
Displays the content of a [Viewport] node as a dynamic [Texture2D]. This can be used to mix controls, 2D, and 3D elements in the same scene.
To create a ViewportTexture in code, use the [method Viewport.get_texture] method on the target viewport.
+ [b]Note:[/b] When local to scene, this texture uses [method Resource.setup_local_to_scene] to set the proxy texture and flags in the local viewport.
</description>
<tutorials>
<link title="GUI in 3D Demo">https://godotengine.org/asset-library/asset/127</link>
diff --git a/doc/classes/VisibleOnScreenEnabler2D.xml b/doc/classes/VisibleOnScreenEnabler2D.xml
index 50d0c00017..8590e9cc9f 100644
--- a/doc/classes/VisibleOnScreenEnabler2D.xml
+++ b/doc/classes/VisibleOnScreenEnabler2D.xml
@@ -1,23 +1,30 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisibleOnScreenEnabler2D" inherits="VisibleOnScreenNotifier2D" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
+ Automatically disables another node if not visible on screen.
</brief_description>
<description>
+ VisibleOnScreenEnabler2D detects when it is visible on screen (just like [VisibleOnScreenNotifier2D]) and automatically enables or disables the target node. The target node is disabled when [VisibleOnScreenEnabler2D] is not visible on screen (including when [member CanvasItem.visible] is [code]false[/code]), and enabled when the enabler is visible. The disabling is achieved by changing [member Node.process_mode].
</description>
<tutorials>
</tutorials>
<members>
<member name="enable_mode" type="int" setter="set_enable_mode" getter="get_enable_mode" enum="VisibleOnScreenEnabler2D.EnableMode" default="0">
+ Determines how the node is enabled. Corresponds to [enum Node.ProcessMode]. Disabled node uses [constant Node.PROCESS_MODE_DISABLED].
</member>
<member name="enable_node_path" type="NodePath" setter="set_enable_node_path" getter="get_enable_node_path" default="NodePath(&quot;..&quot;)">
+ The path to the target node, relative to the [VisibleOnScreenEnabler2D]. The target node is cached; it's only assigned when setting this property (if the [VisibleOnScreenEnabler2D] is inside scene tree) and every time the [VisibleOnScreenEnabler2D] enters the scene tree. If the path is invalid, nothing will happen.
</member>
</members>
<constants>
<constant name="ENABLE_MODE_INHERIT" value="0" enum="EnableMode">
+ Corresponds to [constant Node.PROCESS_MODE_INHERIT].
</constant>
<constant name="ENABLE_MODE_ALWAYS" value="1" enum="EnableMode">
+ Corresponds to [constant Node.PROCESS_MODE_ALWAYS].
</constant>
<constant name="ENABLE_MODE_WHEN_PAUSED" value="2" enum="EnableMode">
+ Corresponds to [constant Node.PROCESS_MODE_WHEN_PAUSED.
</constant>
</constants>
</class>
diff --git a/doc/classes/VisualInstance3D.xml b/doc/classes/VisualInstance3D.xml
index 9574686506..94e8c25660 100644
--- a/doc/classes/VisualInstance3D.xml
+++ b/doc/classes/VisualInstance3D.xml
@@ -17,7 +17,7 @@
<method name="get_aabb" qualifiers="const">
<return type="AABB" />
<description>
- Returns the [AABB] (also known as the bounding box) for this [VisualInstance3D]. See also [method get_transformed_aabb].
+ Returns the [AABB] (also known as the bounding box) for this [VisualInstance3D].
</description>
</method>
<method name="get_base" qualifiers="const">
@@ -39,13 +39,6 @@
Returns whether or not the specified layer of the [member layers] is enabled, given a [code]layer_number[/code] between 1 and 20.
</description>
</method>
- <method name="get_transformed_aabb" qualifiers="const">
- <return type="AABB" />
- <description>
- Returns the transformed [AABB] (also known as the bounding box) for this [VisualInstance3D].
- Transformed in this case means the [AABB] plus the position, rotation, and scale of the [Node3D]'s [Transform3D]. See also [method get_aabb].
- </description>
- </method>
<method name="set_base">
<return type="void" />
<param index="0" name="base" type="RID" />
diff --git a/doc/classes/XROrigin3D.xml b/doc/classes/XROrigin3D.xml
index 7acee097e7..506d0fce41 100644
--- a/doc/classes/XROrigin3D.xml
+++ b/doc/classes/XROrigin3D.xml
@@ -13,6 +13,9 @@
<link title="XR documentation index">$DOCS_URL/tutorials/xr/index.html</link>
</tutorials>
<members>
+ <member name="current" type="bool" setter="set_current" getter="is_current" default="false">
+ Is this XROrigin3D node the current origin used by the [XRServer]?
+ </member>
<member name="world_scale" type="float" setter="set_world_scale" getter="get_world_scale" default="1.0">
Allows you to adjust the scale to your game's units. Most AR/VR platforms assume a scale of 1 game world unit = 1 real world meter.
[b]Note:[/b] This method is a passthrough to the [XRServer] itself.
diff --git a/doc/classes/XRPose.xml b/doc/classes/XRPose.xml
index 0e58fab9b3..31a484ea40 100644
--- a/doc/classes/XRPose.xml
+++ b/doc/classes/XRPose.xml
@@ -30,7 +30,7 @@
<member name="name" type="StringName" setter="set_name" getter="get_name" default="&amp;&quot;&quot;">
The name of this pose. Pose names are often driven by an action map setup by the user. Godot does suggest a number of pose names that it expects [XRInterface]s to implement:
- [code]root[/code] defines a root location, often used for tracked objects that do not have further nodes.
- - [code]aim[/code] defines the tip of a controller with the orientation pointing outwards, for instance: add your raycasts to this.
+ - [code]aim[/code] defines the tip of a controller with the orientation pointing outwards, for example: add your raycasts to this.
- [code]grip[/code] defines the location where the user grips the controller
- [code]skeleton[/code] defines the root location a hand mesh should be placed when using hand tracking and the animated skeleton supplied by the XR runtime.
</member>
@@ -46,7 +46,7 @@
No tracking information is available for this pose.
</constant>
<constant name="XR_TRACKING_CONFIDENCE_LOW" value="1" enum="TrackingConfidence">
- Tracking information may be inaccurate or estimated. For instance with inside out tracking this would indicate a controller may be (partially) obscured.
+ Tracking information may be inaccurate or estimated. For example, with inside out tracking this would indicate a controller may be (partially) obscured.
</constant>
<constant name="XR_TRACKING_CONFIDENCE_HIGH" value="2" enum="TrackingConfidence">
Tracking information is deemed accurate and up to date.
diff --git a/doc/classes/XRServer.xml b/doc/classes/XRServer.xml
index 48b00323d3..d940ea41ac 100644
--- a/doc/classes/XRServer.xml
+++ b/doc/classes/XRServer.xml
@@ -30,18 +30,18 @@
<param index="1" name="keep_height" type="bool" />
<description>
This is an important function to understand correctly. AR and VR platforms all handle positioning slightly differently.
- For platforms that do not offer spatial tracking, our origin point (0,0,0) is the location of our HMD, but you have little control over the direction the player is facing in the real world.
+ For platforms that do not offer spatial tracking, our origin point (0, 0, 0) is the location of our HMD, but you have little control over the direction the player is facing in the real world.
For platforms that do offer spatial tracking, our origin point depends very much on the system. For OpenVR, our origin point is usually the center of the tracking space, on the ground. For other platforms, it's often the location of the tracking camera.
This method allows you to center your tracker on the location of the HMD. It will take the current location of the HMD and use that to adjust all your tracking data; in essence, realigning the real world to your player's current position in the game world.
For this method to produce usable results, tracking information must be available. This often takes a few frames after starting your game.
- You should call this method after a few seconds have passed. For instance, when the user requests a realignment of the display holding a designated button on a controller for a short period of time, or when implementing a teleport mechanism.
+ You should call this method after a few seconds have passed. For example, when the user requests a realignment of the display holding a designated button on a controller for a short period of time, or when implementing a teleport mechanism.
</description>
</method>
<method name="find_interface" qualifiers="const">
<return type="XRInterface" />
<param index="0" name="name" type="String" />
<description>
- Finds an interface by its [param name]. For instance, if your project uses capabilities of an AR/VR platform, you can find the interface for that platform by name and initialize it.
+ Finds an interface by its [param name]. For example, if your project uses capabilities of an AR/VR platform, you can find the interface for that platform by name and initialize it.
</description>
</method>
<method name="get_hmd_transform">
diff --git a/doc/classes/float.xml b/doc/classes/float.xml
index 9d685b9cd0..d7232bb0e9 100644
--- a/doc/classes/float.xml
+++ b/doc/classes/float.xml
@@ -194,7 +194,7 @@
<return type="bool" />
<param index="0" name="right" type="float" />
<description>
- Returns [code]true[/code] the left float is less than the right one.
+ Returns [code]true[/code] if the left float is less than the right one.
</description>
</operator>
<operator name="operator &lt;">
@@ -208,7 +208,7 @@
<return type="bool" />
<param index="0" name="right" type="float" />
<description>
- Returns [code]true[/code] the left integer is less than or equal to the right one.
+ Returns [code]true[/code] if the left float is less than or equal to the right one.
</description>
</operator>
<operator name="operator &lt;=">
@@ -237,7 +237,7 @@
<return type="bool" />
<param index="0" name="right" type="float" />
<description>
- Returns [code]true[/code] the left float is greater than the right one.
+ Returns [code]true[/code] if the left float is greater than the right one.
</description>
</operator>
<operator name="operator &gt;">
@@ -251,7 +251,7 @@
<return type="bool" />
<param index="0" name="right" type="float" />
<description>
- Returns [code]true[/code] the left float is greater than or equal to the right one.
+ Returns [code]true[/code] if the left float is greater than or equal to the right one.
</description>
</operator>
<operator name="operator &gt;=">
diff --git a/doc/classes/int.xml b/doc/classes/int.xml
index 78e2e7d18f..868a8e9944 100644
--- a/doc/classes/int.xml
+++ b/doc/classes/int.xml
@@ -72,14 +72,14 @@
<return type="bool" />
<param index="0" name="right" type="float" />
<description>
- Returns [code]true[/code] if operands are different from each other.
+ Returns [code]true[/code] if this [int] is not equivalent to the given [float].
</description>
</operator>
<operator name="operator !=">
<return type="bool" />
<param index="0" name="right" type="int" />
<description>
- Returns [code]true[/code] if operands are different from each other.
+ Returns [code]true[/code] if the integers are not equal.
</description>
</operator>
<operator name="operator %">
@@ -262,7 +262,7 @@
<return type="bool" />
<param index="0" name="right" type="int" />
<description>
- Returns [code]true[/code] the left integer is less than the right one.
+ Returns [code]true[/code] if the left integer is less than the right one.
</description>
</operator>
<operator name="operator &lt;&lt;">
@@ -287,7 +287,7 @@
<return type="bool" />
<param index="0" name="right" type="int" />
<description>
- Returns [code]true[/code] the left integer is less than or equal to the right one.
+ Returns [code]true[/code] if the left integer is less than or equal to the right one.
</description>
</operator>
<operator name="operator ==">
@@ -315,7 +315,7 @@
<return type="bool" />
<param index="0" name="right" type="int" />
<description>
- Returns [code]true[/code] the left integer is greater than the right one.
+ Returns [code]true[/code] if the left integer is greater than the right one.
</description>
</operator>
<operator name="operator &gt;=">
@@ -329,7 +329,7 @@
<return type="bool" />
<param index="0" name="right" type="int" />
<description>
- Returns [code]true[/code] the left integer is greater than or equal to the right one.
+ Returns [code]true[/code] if the left integer is greater than or equal to the right one.
</description>
</operator>
<operator name="operator &gt;&gt;">
diff --git a/drivers/SCsub b/drivers/SCsub
index dd81fc645c..6cfcb1d18c 100644
--- a/drivers/SCsub
+++ b/drivers/SCsub
@@ -24,6 +24,7 @@ SConscript("winmidi/SCsub")
# Graphics drivers
if env["vulkan"]:
+ SConscript("spirv-reflect/SCsub")
SConscript("vulkan/SCsub")
if env["opengl3"]:
SConscript("gl_context/SCsub")
@@ -31,7 +32,6 @@ if env["opengl3"]:
# Core dependencies
SConscript("png/SCsub")
-SConscript("spirv-reflect/SCsub")
env.add_source_files(env.drivers_sources, "*.cpp")
diff --git a/drivers/gles3/effects/copy_effects.cpp b/drivers/gles3/effects/copy_effects.cpp
index de0181f887..92c29a4264 100644
--- a/drivers/gles3/effects/copy_effects.cpp
+++ b/drivers/gles3/effects/copy_effects.cpp
@@ -114,7 +114,7 @@ CopyEffects::~CopyEffects() {
copy.shader.version_free(copy.shader_version);
}
-void CopyEffects::copy_to_rect(const Rect2i &p_rect) {
+void CopyEffects::copy_to_rect(const Rect2 &p_rect) {
copy.shader.version_bind_shader(copy.shader_version, CopyShaderGLES3::MODE_COPY_SECTION);
copy.shader.version_set_uniform(CopyShaderGLES3::COPY_SECTION, p_rect.position.x, p_rect.position.y, p_rect.size.x, p_rect.size.y, copy.shader_version, CopyShaderGLES3::MODE_COPY_SECTION);
glBindVertexArray(quad_array);
diff --git a/drivers/gles3/effects/copy_effects.h b/drivers/gles3/effects/copy_effects.h
index b863e76579..7f16b4e0f3 100644
--- a/drivers/gles3/effects/copy_effects.h
+++ b/drivers/gles3/effects/copy_effects.h
@@ -61,7 +61,7 @@ public:
~CopyEffects();
// These functions assume that a framebuffer and texture are bound already. They only manage the shader, uniforms, and vertex array.
- void copy_to_rect(const Rect2i &p_rect);
+ void copy_to_rect(const Rect2 &p_rect);
void copy_screen();
void bilinear_blur(GLuint p_source_texture, int p_mipmap_count, const Rect2i &p_region);
void set_color(const Color &p_color, const Rect2i &p_region);
diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp
index c635e18132..5d0edda6c5 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.cpp
+++ b/drivers/gles3/rasterizer_canvas_gles3.cpp
@@ -115,7 +115,7 @@ void RasterizerCanvasGLES3::_update_transform_to_mat4(const Transform3D &p_trans
p_mat4[15] = 1;
}
-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) {
+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_light_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();
@@ -130,7 +130,10 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
if (syncStatus == GL_UNSIGNALED) {
// If older than 2 frames, wait for sync OpenGL can have up to 3 frames in flight, any more and we need to sync anyway.
if (state.canvas_instance_data_buffers[state.current_buffer].last_frame_used < RSG::rasterizer->get_frame_number() - 2) {
+#ifndef WEB_ENABLED
+ // On web, we do nothing as the glSubBufferData will force a sync anyway and WebGL does not like waiting.
glClientWaitSync(state.canvas_instance_data_buffers[state.current_buffer].fence, 0, 100000000); // wait for up to 100ms
+#endif
} else {
// Used in last frame or frame before that. OpenGL can get up to two frames behind, so these buffers may still be in use
// Allocate a new buffer and use that.
@@ -144,9 +147,173 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
}
}
- // TODO: Setup Directional Lights
+ //setup directional lights if exist
+
+ uint32_t light_count = 0;
+ uint32_t directional_light_count = 0;
+ {
+ Light *l = p_directional_light_list;
+ uint32_t index = 0;
+
+ while (l) {
+ if (index == data.max_lights_per_render) {
+ l->render_index_cache = -1;
+ l = l->next_ptr;
+ continue;
+ }
+
+ CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
+ if (!clight) { //unused or invalid texture
+ l->render_index_cache = -1;
+ l = l->next_ptr;
+ ERR_CONTINUE(!clight);
+ }
+
+ Vector2 canvas_light_dir = l->xform_cache.columns[1].normalized();
+
+ state.light_uniforms[index].position[0] = -canvas_light_dir.x;
+ state.light_uniforms[index].position[1] = -canvas_light_dir.y;
+
+ //_update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);
+
+ state.light_uniforms[index].height = l->height; //0..1 here
+
+ for (int i = 0; i < 4; i++) {
+ state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
+ state.light_uniforms[index].color[i] = l->color[i];
+ }
+
+ state.light_uniforms[index].color[3] = l->energy; //use alpha for energy, so base color can go separate
+
+ /*
+ if (state.shadow_fb.is_valid()) {
+ state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
+ state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
+ state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
+ } else {
+ state.light_uniforms[index].shadow_pixel_size = 1.0;
+ state.light_uniforms[index].shadow_z_far_inv = 1.0;
+ state.light_uniforms[index].shadow_y_ofs = 0;
+ }
+ */
+
+ state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
+ state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
+ /*
+ if (clight->shadow.enabled) {
+ state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
+ }
+ */
+
+ l->render_index_cache = index;
+
+ index++;
+ l = l->next_ptr;
+ }
- // TODO: Setup lights
+ light_count = index;
+ directional_light_count = light_count;
+ state.using_directional_lights = directional_light_count > 0;
+ }
+
+ //setup lights if exist
+
+ {
+ Light *l = p_light_list;
+ uint32_t index = light_count;
+
+ while (l) {
+ if (index == data.max_lights_per_render) {
+ l->render_index_cache = -1;
+ l = l->next_ptr;
+ continue;
+ }
+
+ CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
+ if (!clight) { //unused or invalid texture
+ l->render_index_cache = -1;
+ l = l->next_ptr;
+ ERR_CONTINUE(!clight);
+ }
+ Transform2D to_light_xform = (p_canvas_transform * l->light_shader_xform).affine_inverse();
+
+ Vector2 canvas_light_pos = p_canvas_transform.xform(l->xform.get_origin()); //convert light position to canvas coordinates, as all computation is done in canvas coords to avoid precision loss
+ state.light_uniforms[index].position[0] = canvas_light_pos.x;
+ state.light_uniforms[index].position[1] = canvas_light_pos.y;
+
+ _update_transform_2d_to_mat2x4(to_light_xform, state.light_uniforms[index].matrix);
+ _update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
+
+ state.light_uniforms[index].height = l->height * (p_canvas_transform.columns[0].length() + p_canvas_transform.columns[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
+ for (int i = 0; i < 4; i++) {
+ state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
+ state.light_uniforms[index].color[i] = l->color[i];
+ }
+
+ state.light_uniforms[index].color[3] = l->energy; //use alpha for energy, so base color can go separate
+
+ /*
+ if (state.shadow_fb.is_valid()) {
+ state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
+ state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
+ state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
+ } else {
+ state.light_uniforms[index].shadow_pixel_size = 1.0;
+ state.light_uniforms[index].shadow_z_far_inv = 1.0;
+ state.light_uniforms[index].shadow_y_ofs = 0;
+ }
+ */
+ state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
+ state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
+ /*
+ if (clight->shadow.enabled) {
+ state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
+ }
+ */
+
+ if (clight->texture.is_valid()) {
+ Rect2 atlas_rect = GLES3::TextureStorage::get_singleton()->texture_atlas_get_texture_rect(clight->texture);
+ state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;
+ state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;
+ state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;
+ state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;
+
+ } else {
+ state.light_uniforms[index].atlas_rect[0] = 0;
+ state.light_uniforms[index].atlas_rect[1] = 0;
+ state.light_uniforms[index].atlas_rect[2] = 0;
+ state.light_uniforms[index].atlas_rect[3] = 0;
+ }
+
+ l->render_index_cache = index;
+
+ index++;
+ l = l->next_ptr;
+ }
+
+ light_count = index;
+ }
+
+ if (light_count > 0) {
+ glBindBufferBase(GL_UNIFORM_BUFFER, LIGHT_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_buffer].light_ubo);
+
+#ifdef WEB_ENABLED
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, state.light_uniforms);
+#else
+ // On Desktop and mobile we map the memory without synchronizing for maximum speed.
+ void *ubo = glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(LightUniform) * light_count, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
+ memcpy(ubo, state.light_uniforms, sizeof(LightUniform) * light_count);
+ glUnmapBuffer(GL_UNIFORM_BUFFER);
+#endif
+
+ GLuint texture_atlas = texture_storage->texture_atlas_get_texture();
+ if (texture_atlas == 0) {
+ GLES3::Texture *tex = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_WHITE));
+ texture_atlas = tex->tex_id;
+ }
+ glActiveTexture(GL_TEXTURE0 + GLES3::Config::get_singleton()->max_texture_image_units - 2);
+ glBindTexture(GL_TEXTURE_2D, texture_atlas);
+ }
{
//update canvas state uniform buffer
@@ -175,13 +342,12 @@ 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;
- // TODO: temporary, this should be set at the top of this function
glViewport(0, 0, render_target_size.x, render_target_size.y);
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;
+ state_buffer.directional_light_count = directional_light_count;
Vector2 canvas_scale = p_canvas_transform.get_scale();
@@ -200,7 +366,7 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
state_buffer.sdf_to_tex[3] = -sdf_tex_rect.position.y / sdf_tex_rect.size.height;
state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);
- glBindBufferBase(GL_UNIFORM_BUFFER, BASE_UNIFORM_LOCATION, state.canvas_state_buffer);
+ glBindBufferBase(GL_UNIFORM_BUFFER, BASE_UNIFORM_LOCATION, state.canvas_instance_data_buffers[state.current_buffer].state_ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), &state_buffer, GL_STREAM_DRAW);
GLuint global_buffer = material_storage->global_shader_parameters_get_uniform_buffer();
@@ -270,10 +436,12 @@ void RasterizerCanvasGLES3::canvas_render_items(RID p_to_render_target, Item *p_
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, starting_index, false);
item_count = 0;
- Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
-
- if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_OPAQUE) {
+ if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {
+ Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
+ if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
+ items[item_count++] = ci->canvas_group_owner;
+ }
} else if (!backbuffer_cleared) {
texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));
backbuffer_cleared = true;
@@ -381,9 +549,18 @@ void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_cou
}
RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
-
- if (material.is_null() && ci->canvas_group != nullptr) {
- material = default_canvas_group_material;
+ if (ci->canvas_group != nullptr) {
+ if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
+ if (!p_to_backbuffer) {
+ material = default_clip_children_material;
+ }
+ } else {
+ if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {
+ material = default_clip_children_material;
+ } else {
+ material = default_canvas_group_material;
+ }
+ }
}
GLES3::CanvasShaderData *shader_data_cache = nullptr;
@@ -442,7 +619,9 @@ void RasterizerCanvasGLES3::_render_items(RID p_to_render_target, int p_item_cou
GLES3::CanvasMaterialData *material_data = state.canvas_instance_batches[i].material_data;
CanvasShaderGLES3::ShaderVariant variant = state.canvas_instance_batches[i].shader_variant;
- _bind_material(material_data, variant);
+ uint64_t specialization = 0;
+ specialization |= uint64_t(state.canvas_instance_batches[i].lights_disabled);
+ _bind_material(material_data, variant, specialization);
GLES3::CanvasShaderData::BlendMode blend_mode = state.canvas_instance_batches[i].blend_mode;
@@ -554,6 +733,38 @@ void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, const Tran
bool skipping = false;
+ // TODO: consider making lights a per-batch property and then baking light operations in the shader for better performance.
+ uint32_t lights[4] = { 0, 0, 0, 0 };
+
+ uint16_t light_count = 0;
+
+ {
+ Light *light = p_lights;
+
+ while (light) {
+ if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
+ uint32_t light_index = light->render_index_cache;
+ lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
+
+ light_count++;
+
+ if (light_count == data.max_lights_per_item) {
+ break;
+ }
+ }
+ light = light->next_ptr;
+ }
+
+ base_flags |= light_count << FLAGS_LIGHT_COUNT_SHIFT;
+ }
+
+ bool lights_disabled = light_count == 0 && !state.using_directional_lights;
+
+ if (lights_disabled != state.canvas_instance_batches[state.current_batch_index].lights_disabled) {
+ _new_batch(r_batch_broken, r_index);
+ state.canvas_instance_batches[state.current_batch_index].lights_disabled = lights_disabled;
+ }
+
const Item::Command *c = p_item->commands;
while (c) {
if (skipping && c->type != Item::Command::TYPE_ANIMATION_SLICE) {
@@ -580,6 +791,11 @@ void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, const Tran
state.instance_data_array[r_index].pad[0] = 0.0;
state.instance_data_array[r_index].pad[1] = 0.0;
+ state.instance_data_array[r_index].lights[0] = lights[0];
+ state.instance_data_array[r_index].lights[1] = lights[1];
+ state.instance_data_array[r_index].lights[2] = lights[2];
+ state.instance_data_array[r_index].lights[3] = lights[3];
+
state.instance_data_array[r_index].flags = base_flags | (state.instance_data_array[r_index == 0 ? 0 : r_index - 1].flags & (FLAGS_DEFAULT_NORMAL_MAP_USED | FLAGS_DEFAULT_SPECULAR_MAP_USED)); //reset on each command for sanity, keep canvastexture binding config
Color blend_color;
@@ -808,7 +1024,7 @@ void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, const Tran
_add_to_batch(r_index, r_batch_broken);
if (primitive->point_count == 4) {
- // Reset base data
+ // Reset base data.
_update_transform_2d_to_mat2x3(base_transform * draw_transform, state.instance_data_array[r_index].world);
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;
@@ -816,12 +1032,13 @@ void RasterizerCanvasGLES3::_record_item_commands(const Item *p_item, const Tran
state.instance_data_array[r_index].flags = base_flags | (state.instance_data_array[r_index - 1].flags & (FLAGS_DEFAULT_NORMAL_MAP_USED | FLAGS_DEFAULT_SPECULAR_MAP_USED)); //reset on each command for sanity, keep canvastexture binding config
for (uint32_t j = 0; j < 3; j++) {
- //second half of triangle
- state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j + 1].x;
- state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j + 1].y;
- state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j + 1].x;
- state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j + 1].y;
- Color col = primitive->colors[j + 1] * base_color;
+ int offset = j == 0 ? 0 : 1;
+ // Second triangle in the quad. Uses vertices 0, 2, 3.
+ state.instance_data_array[r_index].points[j * 2 + 0] = primitive->points[j + offset].x;
+ state.instance_data_array[r_index].points[j * 2 + 1] = primitive->points[j + offset].y;
+ state.instance_data_array[r_index].uvs[j * 2 + 0] = primitive->uvs[j + offset].x;
+ state.instance_data_array[r_index].uvs[j * 2 + 1] = primitive->uvs[j + offset].y;
+ Color col = primitive->colors[j + offset] * base_color;
state.instance_data_array[r_index].colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
state.instance_data_array[r_index].colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
}
@@ -1140,25 +1357,41 @@ void RasterizerCanvasGLES3::_new_batch(bool &r_batch_broken, uint32_t &r_index)
_align_instance_data_buffer(r_index);
}
-void RasterizerCanvasGLES3::_bind_material(GLES3::CanvasMaterialData *p_material_data, CanvasShaderGLES3::ShaderVariant p_variant) {
+void RasterizerCanvasGLES3::_bind_material(GLES3::CanvasMaterialData *p_material_data, CanvasShaderGLES3::ShaderVariant p_variant, uint64_t p_specialization) {
if (p_material_data) {
if (p_material_data->shader_data->version.is_valid() && p_material_data->shader_data->valid) {
// Bind uniform buffer and textures
p_material_data->bind_uniforms();
- GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(p_material_data->shader_data->version, p_variant);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(p_material_data->shader_data->version, p_variant, p_specialization);
} else {
- GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(data.canvas_shader_default_version, p_variant);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(data.canvas_shader_default_version, p_variant, p_specialization);
}
} else {
- GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(data.canvas_shader_default_version, p_variant);
+ GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.version_bind_shader(data.canvas_shader_default_version, p_variant, p_specialization);
}
}
RID RasterizerCanvasGLES3::light_create() {
- return RID();
+ CanvasLight canvas_light;
+ return canvas_light_owner.make_rid(canvas_light);
}
void RasterizerCanvasGLES3::light_set_texture(RID p_rid, RID p_texture) {
+ GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
+
+ CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
+ ERR_FAIL_COND(!cl);
+ if (cl->texture == p_texture) {
+ return;
+ }
+ if (cl->texture.is_valid()) {
+ texture_storage->texture_remove_from_texture_atlas(cl->texture);
+ }
+ cl->texture = p_texture;
+
+ if (cl->texture.is_valid()) {
+ texture_storage->texture_add_to_texture_atlas(cl->texture);
+ }
}
void RasterizerCanvasGLES3::light_set_use_shadow(RID p_rid, bool p_enable) {
@@ -1187,6 +1420,14 @@ void RasterizerCanvasGLES3::set_shadow_texture_size(int p_size) {
}
bool RasterizerCanvasGLES3::free(RID p_rid) {
+ if (canvas_light_owner.owns(p_rid)) {
+ CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
+ ERR_FAIL_COND_V(!cl, false);
+ canvas_light_owner.free(p_rid);
+ } else {
+ return false;
+ }
+
return true;
}
@@ -1357,7 +1598,7 @@ void RasterizerCanvasGLES3::_prepare_canvas_texture(RID p_texture, RS::CanvasIte
state.instance_data_array[r_index].flags &= ~FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
- if (!normal_map) {
+ if (normal_map) {
state.instance_data_array[r_index].flags |= FLAGS_DEFAULT_NORMAL_MAP_USED;
} else {
state.instance_data_array[r_index].flags &= ~FLAGS_DEFAULT_NORMAL_MAP_USED;
@@ -1567,13 +1808,23 @@ void RasterizerCanvasGLES3::free_polygon(PolygonID p_polygon) {
// In theory allocations can reach as high as number of windows * 3 frames
// because OpenGL can start rendering subsequent frames before finishing the current one
void RasterizerCanvasGLES3::_allocate_instance_data_buffer() {
- GLuint new_buffer;
- glGenBuffers(1, &new_buffer);
- glBindBuffer(GL_UNIFORM_BUFFER, new_buffer);
- glBufferData(GL_UNIFORM_BUFFER, data.max_instance_buffer_size, nullptr, GL_DYNAMIC_DRAW);
+ GLuint new_buffers[3];
+ glGenBuffers(3, new_buffers);
+ // Batch UBO.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[0]);
+ glBufferData(GL_UNIFORM_BUFFER, data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW);
+ // Light uniform buffer.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW);
+ // State buffer.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), nullptr, GL_STREAM_DRAW);
+
state.current_buffer = (state.current_buffer + 1);
DataBuffer db;
- db.ubo = new_buffer;
+ db.ubo = new_buffers[0];
+ db.light_ubo = new_buffers[1];
+ db.state_ubo = new_buffers[2];
db.last_frame_used = RSG::rasterizer->get_frame_number();
state.canvas_instance_data_buffers.insert(state.current_buffer, db);
state.current_buffer = state.current_buffer % state.canvas_instance_data_buffers.size();
@@ -1755,12 +2006,21 @@ RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
state.canvas_instance_batches.reserve(200);
for (int i = 0; i < 3; i++) {
- GLuint new_buffer;
- glGenBuffers(1, &new_buffer);
- glBindBuffer(GL_UNIFORM_BUFFER, new_buffer);
- glBufferData(GL_UNIFORM_BUFFER, data.max_instance_buffer_size, nullptr, GL_DYNAMIC_DRAW);
+ GLuint new_buffers[3];
+ glGenBuffers(3, new_buffers);
+ // Batch UBO.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[0]);
+ glBufferData(GL_UNIFORM_BUFFER, data.max_instance_buffer_size, nullptr, GL_STREAM_DRAW);
+ // Light uniform buffer.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[1]);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(LightUniform) * data.max_lights_per_render, nullptr, GL_STREAM_DRAW);
+ // State buffer.
+ glBindBuffer(GL_UNIFORM_BUFFER, new_buffers[2]);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), nullptr, GL_STREAM_DRAW);
DataBuffer db;
- db.ubo = new_buffer;
+ db.ubo = new_buffers[0];
+ db.light_ubo = new_buffers[1];
+ db.state_ubo = new_buffers[2];
db.last_frame_used = 0;
db.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
state.canvas_instance_data_buffers[i] = db;
@@ -1768,6 +2028,7 @@ RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
glBindBuffer(GL_UNIFORM_BUFFER, 0);
state.instance_data_array = memnew_arr(InstanceData, data.max_instances_per_ubo);
+ state.light_uniforms = memnew_arr(LightUniform, data.max_lights_per_render);
{
const uint32_t no_of_instances = data.max_instances_per_batch;
@@ -1794,14 +2055,9 @@ RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
delete[] indices;
}
- glGenBuffers(1, &state.canvas_state_buffer);
- glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_state_buffer);
- glBufferData(GL_UNIFORM_BUFFER, sizeof(StateBuffer), nullptr, GL_STREAM_DRAW);
- glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
String global_defines;
global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
- global_defines += "#define MAX_LIGHTS " + itos(data.max_instances_per_batch) + "\n";
+ global_defines += "#define MAX_LIGHTS " + itos(data.max_lights_per_render) + "\n";
global_defines += "#define MAX_DRAW_DATA_INSTANCES " + itos(data.max_instances_per_batch) + "\n";
GLES3::MaterialStorage::get_singleton()->shaders.canvas_shader.initialize(global_defines);
@@ -1833,6 +2089,26 @@ void fragment() {
material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
}
+ {
+ default_clip_children_shader = material_storage->shader_allocate();
+ material_storage->shader_initialize(default_clip_children_shader);
+
+ material_storage->shader_set_code(default_clip_children_shader, R"(
+// Default clip children shader.
+
+shader_type canvas_item;
+
+void fragment() {
+ vec4 c = textureLod(SCREEN_TEXTURE, SCREEN_UV, 0.0);
+ COLOR.rgb = c.rgb;
+}
+)");
+ default_clip_children_material = material_storage->material_allocate();
+ material_storage->material_initialize(default_clip_children_material);
+
+ material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);
+ }
+
default_canvas_texture = texture_storage->canvas_texture_allocate();
texture_storage->canvas_texture_initialize(default_canvas_texture);
@@ -1845,6 +2121,8 @@ RasterizerCanvasGLES3::~RasterizerCanvasGLES3() {
material_storage->shaders.canvas_shader.version_free(data.canvas_shader_default_version);
material_storage->material_free(default_canvas_group_material);
material_storage->shader_free(default_canvas_group_shader);
+ material_storage->material_free(default_clip_children_material);
+ material_storage->shader_free(default_clip_children_shader);
singleton = nullptr;
glDeleteBuffers(1, &data.canvas_quad_vertices);
@@ -1854,7 +2132,8 @@ RasterizerCanvasGLES3::~RasterizerCanvasGLES3() {
glDeleteVertexArrays(1, &data.canvas_quad_array);
GLES3::TextureStorage::get_singleton()->canvas_texture_free(default_canvas_texture);
- memfree(state.instance_data_array);
+ memdelete_arr(state.instance_data_array);
+ memdelete_arr(state.light_uniforms);
}
#endif // GLES3_ENABLED
diff --git a/drivers/gles3/rasterizer_canvas_gles3.h b/drivers/gles3/rasterizer_canvas_gles3.h
index 15c2ca5710..aee2782b62 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.h
+++ b/drivers/gles3/rasterizer_canvas_gles3.h
@@ -96,6 +96,33 @@ class RasterizerCanvasGLES3 : public RendererCanvasRender {
DEFAULT_MAX_LIGHTS_PER_RENDER = 256,
};
+ /******************/
+ /**** LIGHTING ****/
+ /******************/
+
+ struct CanvasLight {
+ RID texture;
+ };
+
+ RID_Owner<CanvasLight> canvas_light_owner;
+
+ struct LightUniform {
+ float matrix[8]; //light to texture coordinate matrix
+ float shadow_matrix[8]; //light to shadow coordinate matrix
+ float color[4];
+
+ uint8_t shadow_color[4];
+ uint32_t flags; //index to light texture
+ float shadow_pixel_size;
+ float height;
+
+ float position[2];
+ float shadow_z_far_inv;
+ float shadow_y_ofs;
+
+ float atlas_rect[4];
+ };
+
public:
enum {
BASE_UNIFORM_LOCATION = 0,
@@ -184,8 +211,8 @@ public:
RID canvas_shader_default_version;
- uint32_t max_lights_per_render;
- uint32_t max_lights_per_item;
+ uint32_t max_lights_per_render = 256;
+ uint32_t max_lights_per_item = 16;
uint32_t max_instances_per_batch = 512;
uint32_t max_instances_per_ubo = 16384;
uint32_t max_instance_buffer_size = 16384 * 128;
@@ -212,16 +239,22 @@ public:
const Item::Command *command = nullptr;
Item::Command::Type command_type = Item::Command::TYPE_ANIMATION_SLICE; // Can default to any type that doesn't form a batch.
uint32_t primitive_points = 0;
+
+ bool lights_disabled = false;
};
+ // DataBuffer contains our per-frame data. I.e. the resources that are updated each frame.
+ // We track them and ensure that they don't get reused until at least 2 frames have passed
+ // to avoid the GPU stalling to wait for a resource to become available.
struct DataBuffer {
GLuint ubo = 0;
+ GLuint light_ubo = 0;
+ GLuint state_ubo = 0;
uint64_t last_frame_used = -3;
GLsync fence = GLsync();
};
struct State {
- GLuint canvas_state_buffer;
LocalVector<DataBuffer> canvas_instance_data_buffers;
LocalVector<Batch> canvas_instance_batches;
uint32_t current_buffer = 0;
@@ -230,6 +263,10 @@ public:
InstanceData *instance_data_array = nullptr;
+ LightUniform *light_uniforms = nullptr;
+
+ bool using_directional_lights = false;
+
RID current_tex = RID();
RS::CanvasItemTextureFilter current_filter_mode = RS::CANVAS_ITEM_TEXTURE_FILTER_MAX;
RS::CanvasItemTextureRepeat current_repeat_mode = RS::CANVAS_ITEM_TEXTURE_REPEAT_MAX;
@@ -247,6 +284,8 @@ public:
RID default_canvas_texture;
RID default_canvas_group_material;
RID default_canvas_group_shader;
+ RID default_clip_children_material;
+ RID default_clip_children_shader;
typedef void Texture;
@@ -282,7 +321,7 @@ public:
void _render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, uint32_t &r_last_index, bool p_to_backbuffer = false);
void _record_item_commands(const Item *p_item, const Transform2D &p_canvas_transform_inverse, Item *&current_clip, GLES3::CanvasShaderData::BlendMode p_blend_mode, Light *p_lights, uint32_t &r_index, bool &r_break_batch);
void _render_batch(Light *p_lights, uint32_t p_index);
- void _bind_material(GLES3::CanvasMaterialData *p_material_data, CanvasShaderGLES3::ShaderVariant p_variant);
+ void _bind_material(GLES3::CanvasMaterialData *p_material_data, CanvasShaderGLES3::ShaderVariant p_variant, uint64_t p_specialization);
void _new_batch(bool &r_batch_broken, uint32_t &r_index);
void _add_to_batch(uint32_t &r_index, bool &r_batch_broken);
void _allocate_instance_data_buffer();
diff --git a/drivers/gles3/rasterizer_gles3.cpp b/drivers/gles3/rasterizer_gles3.cpp
index 0836a21254..ea97dff522 100644
--- a/drivers/gles3/rasterizer_gles3.cpp
+++ b/drivers/gles3/rasterizer_gles3.cpp
@@ -274,15 +274,32 @@ RasterizerGLES3::~RasterizerGLES3() {
void RasterizerGLES3::prepare_for_blitting_render_targets() {
}
-void RasterizerGLES3::_blit_render_target_to_screen(RID p_render_target, DisplayServer::WindowID p_screen, const Rect2 &p_screen_rect) {
+void RasterizerGLES3::_blit_render_target_to_screen(RID p_render_target, DisplayServer::WindowID p_screen, const Rect2 &p_screen_rect, uint32_t p_layer) {
GLES3::RenderTarget *rt = GLES3::TextureStorage::get_singleton()->get_render_target(p_render_target);
+
ERR_FAIL_COND(!rt);
- glBindFramebuffer(GL_READ_FRAMEBUFFER, rt->fbo);
+ GLuint read_fbo = 0;
+ if (rt->view_count > 1) {
+ glGenFramebuffers(1, &read_fbo);
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, read_fbo);
+ glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, rt->color, 0, p_layer);
+ } else {
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, rt->fbo);
+ }
+
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
// Flip content upside down to correct for coordinates.
- 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);
+ Vector2i screen_rect_end = p_screen_rect.get_end();
+ glBlitFramebuffer(0, 0, rt->size.x, rt->size.y,
+ p_screen_rect.position.x, screen_rect_end.y, screen_rect_end.x, p_screen_rect.position.y,
+ GL_COLOR_BUFFER_BIT, GL_NEAREST);
+
+ if (read_fbo != 0) {
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
+ glDeleteFramebuffers(1, &read_fbo);
+ }
}
// is this p_screen useless in a multi window environment?
@@ -293,7 +310,7 @@ void RasterizerGLES3::blit_render_targets_to_screen(DisplayServer::WindowID p_sc
RID rid_rt = blit.render_target;
Rect2 dst_rect = blit.dst_rect;
- _blit_render_target_to_screen(rid_rt, p_screen, dst_rect);
+ _blit_render_target_to_screen(rid_rt, p_screen, dst_rect, blit.multi_view.use_layer ? blit.multi_view.layer : 0);
}
}
diff --git a/drivers/gles3/rasterizer_gles3.h b/drivers/gles3/rasterizer_gles3.h
index 431515fd0d..d7d26685b4 100644
--- a/drivers/gles3/rasterizer_gles3.h
+++ b/drivers/gles3/rasterizer_gles3.h
@@ -68,7 +68,7 @@ protected:
RasterizerCanvasGLES3 *canvas = nullptr;
RasterizerSceneGLES3 *scene = nullptr;
- void _blit_render_target_to_screen(RID p_render_target, DisplayServer::WindowID p_screen, const Rect2 &p_screen_rect);
+ void _blit_render_target_to_screen(RID p_render_target, DisplayServer::WindowID p_screen, const Rect2 &p_screen_rect, uint32_t p_layer);
public:
RendererUtilities *get_utilities() { return utilities; }
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index 4c71edc24c..6e9d4e5963 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -1166,12 +1166,13 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const
// LOD
if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
- //lod
- Vector3 lod_support_min = inst->transformed_aabb.get_support(-p_render_data->lod_camera_plane.normal);
- Vector3 lod_support_max = inst->transformed_aabb.get_support(p_render_data->lod_camera_plane.normal);
+ // Get the LOD support points on the mesh AABB.
+ Vector3 lod_support_min = inst->transformed_aabb.get_support(p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
+ Vector3 lod_support_max = inst->transformed_aabb.get_support(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
- float distance_min = p_render_data->lod_camera_plane.distance_to(lod_support_min);
- float distance_max = p_render_data->lod_camera_plane.distance_to(lod_support_max);
+ // Get the distances to those points on the AABB from the camera origin.
+ float distance_min = (float)p_render_data->cam_transform.origin.distance_to(lod_support_min);
+ float distance_max = (float)p_render_data->cam_transform.origin.distance_to(lod_support_max);
float distance = 0.0;
@@ -1188,8 +1189,8 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const
distance = 1.0;
}
- uint32_t indices;
- surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, &indices);
+ uint32_t indices = 0;
+ surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, indices);
/*
if (p_render_data->render_info) {
indices = _indices_to_primitives(surf->primitive, indices);
@@ -1272,6 +1273,19 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da
GLES3::MaterialStorage::store_transform(p_render_data->cam_transform, scene_state.ubo.inv_view_matrix);
GLES3::MaterialStorage::store_transform(p_render_data->inv_cam_transform, scene_state.ubo.view_matrix);
+ if (p_render_data->view_count > 1) {
+ for (uint32_t v = 0; v < p_render_data->view_count; v++) {
+ projection = correction * p_render_data->view_projection[v];
+ GLES3::MaterialStorage::store_camera(projection, scene_state.multiview_ubo.projection_matrix_view[v]);
+ GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.multiview_ubo.inv_projection_matrix_view[v]);
+
+ scene_state.multiview_ubo.eye_offset[v][0] = p_render_data->view_eye_offset[v].x;
+ scene_state.multiview_ubo.eye_offset[v][1] = p_render_data->view_eye_offset[v].y;
+ scene_state.multiview_ubo.eye_offset[v][2] = p_render_data->view_eye_offset[v].z;
+ scene_state.multiview_ubo.eye_offset[v][3] = 0.0;
+ }
+ }
+
scene_state.ubo.directional_light_count = p_render_data->directional_light_count;
scene_state.ubo.z_far = p_render_data->z_far;
@@ -1373,6 +1387,15 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da
glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
+
+ if (p_render_data->view_count > 1) {
+ if (scene_state.multiview_buffer == 0) {
+ glGenBuffers(1, &scene_state.multiview_buffer);
+ }
+ glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW);
+ glBindBuffer(GL_UNIFORM_BUFFER, 0);
+ }
}
// Puts lights into Uniform Buffers. Needs to be called before _fill_list as this caches the index of each light in the Uniform Buffer
@@ -1650,7 +1673,6 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_
// 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_column(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;
@@ -1916,8 +1938,14 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
GLES3::SceneShaderData *prev_shader = nullptr;
GeometryInstanceGLES3 *prev_inst = nullptr;
SceneShaderGLES3::ShaderVariant prev_variant = SceneShaderGLES3::ShaderVariant::MODE_COLOR;
+ SceneShaderGLES3::ShaderVariant shader_variant = SceneShaderGLES3::MODE_COLOR; // Assigned to silence wrong -Wmaybe-initialized
- SceneShaderGLES3::ShaderVariant shader_variant = SceneShaderGLES3::MODE_COLOR; // Assigned to silence wrong -Wmaybe-initialized.
+ // @todo Get this from p_params->spec_constant_base_flags instead of hardcoding it.
+ uint32_t base_spec_constants = 0;
+
+ if (p_render_data->view_count > 1) {
+ base_spec_constants |= 1 << SPEC_CONSTANT_USE_MULTIVIEW;
+ }
switch (p_pass_mode) {
case PASS_MODE_COLOR:
@@ -1957,8 +1985,6 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
continue;
}
- //uint32_t base_spec_constants = p_params->spec_constant_base_flags;
-
GLES3::SceneShaderData *shader;
GLES3::SceneMaterialData *material_data;
void *mesh_surface;
@@ -2128,7 +2154,7 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
}
if (prev_shader != shader || prev_variant != instance_variant) {
- material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant);
+ material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, base_spec_constants);
float opaque_prepass_threshold = 0.0;
if constexpr (p_pass_mode == PASS_MODE_DEPTH) {
opaque_prepass_threshold = 0.99;
@@ -2136,7 +2162,7 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
opaque_prepass_threshold = 0.1;
}
- material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant);
+ material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, base_spec_constants);
prev_shader = shader;
prev_variant = instance_variant;
@@ -2144,21 +2170,21 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params,
if (prev_inst != inst || prev_shader != shader || prev_variant != instance_variant) {
// Rebind the light indices.
- material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_count, shader->version, instance_variant);
- material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_count, shader->version, instance_variant);
+ material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_count, shader->version, instance_variant, base_spec_constants);
+ material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_count, shader->version, instance_variant, base_spec_constants);
if (inst->omni_light_count) {
- glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES, shader->version, instance_variant), inst->omni_light_count, inst->omni_light_gl_cache.ptr());
+ glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES, shader->version, instance_variant, base_spec_constants), inst->omni_light_count, inst->omni_light_gl_cache.ptr());
}
if (inst->spot_light_count) {
- glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES, shader->version, instance_variant), inst->spot_light_count, inst->spot_light_gl_cache.ptr());
+ glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES, shader->version, instance_variant, base_spec_constants), inst->spot_light_count, inst->spot_light_gl_cache.ptr());
}
prev_inst = inst;
}
- material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant);
+ material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, base_spec_constants);
if (inst->instance_count > 0) {
// Using MultiMesh.
// Bind instance buffers.
diff --git a/drivers/gles3/rasterizer_scene_gles3.h b/drivers/gles3/rasterizer_scene_gles3.h
index d11dc14080..3a759425e2 100644
--- a/drivers/gles3/rasterizer_scene_gles3.h
+++ b/drivers/gles3/rasterizer_scene_gles3.h
@@ -74,6 +74,7 @@ enum SceneUniformLocation {
SCENE_OMNILIGHT_UNIFORM_LOCATION,
SCENE_SPOTLIGHT_UNIFORM_LOCATION,
SCENE_DIRECTIONAL_LIGHT_UNIFORM_LOCATION,
+ SCENE_MULTIVIEW_UNIFORM_LOCATION,
};
enum SkyUniformLocation {
@@ -90,6 +91,8 @@ enum {
SPEC_CONSTANT_DISABLE_OMNI_LIGHTS = 2,
SPEC_CONSTANT_DISABLE_SPOT_LIGHTS = 3,
SPEC_CONSTANT_DISABLE_FOG = 4,
+ SPEC_CONSTANT_USE_RADIANCE_MAP = 5,
+ SPEC_CONSTANT_USE_MULTIVIEW = 6,
};
struct RenderDataGLES3 {
@@ -118,7 +121,6 @@ struct RenderDataGLES3 {
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;
@@ -344,6 +346,13 @@ private:
};
static_assert(sizeof(UBO) % 16 == 0, "Scene UBO size must be a multiple of 16 bytes");
+ struct MultiviewUBO {
+ float projection_matrix_view[RendererSceneRender::MAX_RENDER_VIEWS][16];
+ float inv_projection_matrix_view[RendererSceneRender::MAX_RENDER_VIEWS][16];
+ float eye_offset[RendererSceneRender::MAX_RENDER_VIEWS][4];
+ };
+ static_assert(sizeof(MultiviewUBO) % 16 == 0, "Multiview UBO size must be a multiple of 16 bytes");
+
struct TonemapUBO {
float exposure = 1.0;
float white = 1.0;
@@ -354,6 +363,8 @@ private:
UBO ubo;
GLuint ubo_buffer = 0;
+ MultiviewUBO multiview_ubo;
+ GLuint multiview_buffer = 0;
GLuint tonemap_buffer = 0;
bool used_depth_prepass = false;
diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp
index 033f10dbc5..2ff7f72180 100644
--- a/drivers/gles3/shader_gles3.cpp
+++ b/drivers/gles3/shader_gles3.cpp
@@ -142,7 +142,7 @@ RID ShaderGLES3::version_create() {
return version_owner.make_rid(version);
}
-void ShaderGLES3::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template, uint64_t p_specialization) {
+void ShaderGLES3::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, StageType p_stage_type, uint64_t p_specialization) {
#ifdef GLES_OVER_GL
builder.append("#version 330\n");
builder.append("#define USE_GLES_OVER_GL\n");
@@ -171,6 +171,24 @@ void ShaderGLES3::_build_variant_code(StringBuilder &builder, uint32_t p_variant
}
builder.append("\n"); //make sure defines begin at newline
+ // Insert multiview extension loading, because it needs to appear before
+ // any non-preprocessor code (like the "precision highp..." lines below).
+ builder.append("#ifdef USE_MULTIVIEW\n");
+ builder.append("#if defined(GL_OVR_multiview2)\n");
+ builder.append("#extension GL_OVR_multiview2 : require\n");
+ builder.append("#elif defined(GL_OVR_multiview)\n");
+ builder.append("#extension GL_OVR_multiview : require\n");
+ builder.append("#endif\n");
+ if (p_stage_type == StageType::STAGE_TYPE_VERTEX) {
+ builder.append("layout(num_views=2) in;\n");
+ }
+ builder.append("#define ViewIndex gl_ViewID_OVR\n");
+ builder.append("#define MAX_VIEWS 2\n");
+ builder.append("#else\n");
+ builder.append("#define ViewIndex 0\n");
+ builder.append("#define MAX_VIEWS 1\n");
+ builder.append("#endif\n");
+
// Default to highp precision unless specified otherwise.
builder.append("precision highp float;\n");
builder.append("precision highp int;\n");
@@ -180,8 +198,9 @@ void ShaderGLES3::_build_variant_code(StringBuilder &builder, uint32_t p_variant
builder.append("precision highp sampler2DArray;\n");
#endif
- for (uint32_t i = 0; i < p_template.chunks.size(); i++) {
- const StageTemplate::Chunk &chunk = p_template.chunks[i];
+ const StageTemplate &stage_template = stage_templates[p_stage_type];
+ for (uint32_t i = 0; i < stage_template.chunks.size(); i++) {
+ const StageTemplate::Chunk &chunk = stage_template.chunks[i];
switch (chunk.type) {
case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {
builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)
@@ -224,7 +243,7 @@ void ShaderGLES3::_compile_specialization(Version::Specialization &spec, uint32_
//vertex stage
{
StringBuilder builder;
- _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_VERTEX], p_specialization);
+ _build_variant_code(builder, p_variant, p_version, STAGE_TYPE_VERTEX, p_specialization);
spec.vert_id = glCreateShader(GL_VERTEX_SHADER);
String builder_string = builder.as_string();
@@ -272,7 +291,7 @@ void ShaderGLES3::_compile_specialization(Version::Specialization &spec, uint32_
//fragment stage
{
StringBuilder builder;
- _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_FRAGMENT], p_specialization);
+ _build_variant_code(builder, p_variant, p_version, STAGE_TYPE_FRAGMENT, p_specialization);
spec.frag_id = glCreateShader(GL_FRAGMENT_SHADER);
String builder_string = builder.as_string();
@@ -413,7 +432,7 @@ RS::ShaderNativeSourceCode ShaderGLES3::version_get_native_source_code(RID p_ver
{
StringBuilder builder;
- _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_VERTEX], specialization_default_mask);
+ _build_variant_code(builder, i, version, STAGE_TYPE_VERTEX, specialization_default_mask);
RS::ShaderNativeSourceCode::Version::Stage stage;
stage.name = "vertex";
@@ -425,7 +444,7 @@ RS::ShaderNativeSourceCode ShaderGLES3::version_get_native_source_code(RID p_ver
//fragment stage
{
StringBuilder builder;
- _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_FRAGMENT], specialization_default_mask);
+ _build_variant_code(builder, i, version, STAGE_TYPE_FRAGMENT, specialization_default_mask);
RS::ShaderNativeSourceCode::Version::Stage stage;
stage.name = "fragment";
diff --git a/drivers/gles3/shader_gles3.h b/drivers/gles3/shader_gles3.h
index 2b72549b5b..760b5e5ddb 100644
--- a/drivers/gles3/shader_gles3.h
+++ b/drivers/gles3/shader_gles3.h
@@ -153,7 +153,7 @@ private:
StageTemplate stage_templates[STAGE_TYPE_MAX];
- void _build_variant_code(StringBuilder &p_builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template, uint64_t p_specialization);
+ void _build_variant_code(StringBuilder &p_builder, uint32_t p_variant, const Version *p_version, StageType p_stage_type, uint64_t p_specialization);
void _add_stage(const char *p_code, StageType p_stage_type);
diff --git a/drivers/gles3/shaders/canvas.glsl b/drivers/gles3/shaders/canvas.glsl
index a177112476..23db41802e 100644
--- a/drivers/gles3/shaders/canvas.glsl
+++ b/drivers/gles3/shaders/canvas.glsl
@@ -211,7 +211,9 @@ void main() {
#include "canvas_uniforms_inc.glsl"
#include "stdlib_inc.glsl"
-//uniform sampler2D atlas_texture; //texunit:-2
+#ifndef DISABLE_LIGHTING
+uniform sampler2D atlas_texture; //texunit:-2
+#endif // DISABLE_LIGHTING
//uniform sampler2D shadow_atlas_texture; //texunit:-3
uniform sampler2D screen_texture; //texunit:-4
uniform sampler2D sdf_texture; //texunit:-5
@@ -243,6 +245,77 @@ layout(std140) uniform MaterialUniforms{
#endif
#GLOBALS
+#ifndef DISABLE_LIGHTING
+#ifdef LIGHT_CODE_USED
+
+vec4 light_compute(
+ vec3 light_vertex,
+ vec3 light_position,
+ vec3 normal,
+ vec4 light_color,
+ float light_energy,
+ vec4 specular_shininess,
+ inout vec4 shadow_modulate,
+ vec2 screen_uv,
+ vec2 uv,
+ vec4 color, bool is_directional) {
+ vec4 light = vec4(0.0);
+ vec3 light_direction = vec3(0.0);
+
+ if (is_directional) {
+ light_direction = normalize(mix(vec3(light_position.xy, 0.0), vec3(0, 0, 1), light_position.z));
+ light_position = vec3(0.0);
+ } else {
+ light_direction = normalize(light_position - light_vertex);
+ }
+
+#CODE : LIGHT
+
+ return light;
+}
+
+#endif
+
+vec3 light_normal_compute(vec3 light_vec, vec3 normal, vec3 base_color, vec3 light_color, vec4 specular_shininess, bool specular_shininess_used) {
+ float cNdotL = max(0.0, dot(normal, light_vec));
+
+ if (specular_shininess_used) {
+ //blinn
+ vec3 view = vec3(0.0, 0.0, 1.0); // not great but good enough
+ vec3 half_vec = normalize(view + light_vec);
+
+ float cNdotV = max(dot(normal, view), 0.0);
+ float cNdotH = max(dot(normal, half_vec), 0.0);
+ float cVdotH = max(dot(view, half_vec), 0.0);
+ float cLdotH = max(dot(light_vec, half_vec), 0.0);
+ float shininess = exp2(15.0 * specular_shininess.a + 1.0) * 0.25;
+ float blinn = pow(cNdotH, shininess);
+ blinn *= (shininess + 8.0) * (1.0 / (8.0 * M_PI));
+ float s = (blinn) / max(4.0 * cNdotV * cNdotL, 0.75);
+
+ return specular_shininess.rgb * light_color * s + light_color * base_color * cNdotL;
+ } else {
+ return light_color * base_color * cNdotL;
+ }
+}
+
+void light_blend_compute(uint light_base, vec4 light_color, inout vec3 color) {
+ uint blend_mode = light_array[light_base].flags & LIGHT_FLAGS_BLEND_MASK;
+
+ switch (blend_mode) {
+ case LIGHT_FLAGS_BLEND_MODE_ADD: {
+ color.rgb += light_color.rgb * light_color.a;
+ } break;
+ case LIGHT_FLAGS_BLEND_MODE_SUB: {
+ color.rgb -= light_color.rgb * light_color.a;
+ } break;
+ case LIGHT_FLAGS_BLEND_MODE_MIX: {
+ color.rgb = mix(color.rgb, light_color.rgb, light_color.a);
+ } break;
+ }
+}
+
+#endif
#ifdef USE_NINEPATCH
@@ -353,7 +426,8 @@ void main() {
color *= texture(color_texture, uv);
}
- bool using_light = false;
+ uint light_count = (draw_data[draw_data_instance].flags >> uint(FLAGS_LIGHT_COUNT_SHIFT)) & uint(0xF); //max 16 lights
+ bool using_light = light_count > 0u || directional_light_count > 0u;
vec3 normal;
@@ -414,11 +488,105 @@ void main() {
#endif
}
+ if (normal_used) {
+ //convert by item transform
+ normal.xy = mat2(normalize(draw_data[draw_data_instance].world_x), normalize(draw_data[draw_data_instance].world_y)) * normal.xy;
+ //convert by canvas transform
+ normal = normalize((canvas_normal_transform * vec4(normal, 0.0)).xyz);
+ }
+
+ vec4 base_color = color;
+
#ifdef MODE_LIGHT_ONLY
color = vec4(0.0);
#else
color *= canvas_modulation;
#endif
+#if !defined(DISABLE_LIGHTING) && !defined(MODE_UNSHADED)
+
+ // Directional Lights
+
+ for (uint i = 0u; i < directional_light_count; i++) {
+ uint light_base = i;
+
+ vec2 direction = light_array[light_base].position;
+ vec4 light_color = light_array[light_base].color;
+
+#ifdef LIGHT_CODE_USED
+
+ vec4 shadow_modulate = vec4(1.0);
+ light_color = light_compute(light_vertex, vec3(direction, light_array[light_base].height), normal, light_color, light_color.a, specular_shininess, shadow_modulate, screen_uv, uv, base_color, true);
+#else
+
+ if (normal_used) {
+ vec3 light_vec = normalize(mix(vec3(direction, 0.0), vec3(0, 0, 1), light_array[light_base].height));
+ light_color.rgb = light_normal_compute(light_vec, normal, base_color.rgb, light_color.rgb, specular_shininess, specular_shininess_used);
+ } else {
+ light_color.rgb *= base_color.rgb;
+ }
+#endif
+
+ light_blend_compute(light_base, light_color, color.rgb);
+ }
+
+ // Positional Lights
+
+ for (uint i = 0u; i < MAX_LIGHTS_PER_ITEM; i++) {
+ if (i >= light_count) {
+ break;
+ }
+ uint light_base;
+ if (i < 8u) {
+ if (i < 4u) {
+ light_base = draw_data[draw_data_instance].lights[0];
+ } else {
+ light_base = draw_data[draw_data_instance].lights[1];
+ }
+ } else {
+ if (i < 12u) {
+ light_base = draw_data[draw_data_instance].lights[2];
+ } else {
+ light_base = draw_data[draw_data_instance].lights[3];
+ }
+ }
+ light_base >>= (i & 3u) * 8u;
+ light_base &= uint(0xFF);
+
+ vec2 tex_uv = (vec4(vertex, 0.0, 1.0) * mat4(light_array[light_base].texture_matrix[0], light_array[light_base].texture_matrix[1], vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0))).xy; //multiply inverse given its transposed. Optimizer removes useless operations.
+ vec2 tex_uv_atlas = tex_uv * light_array[light_base].atlas_rect.zw + light_array[light_base].atlas_rect.xy;
+ vec4 light_color = textureLod(atlas_texture, tex_uv_atlas, 0.0);
+ vec4 light_base_color = light_array[light_base].color;
+
+#ifdef LIGHT_CODE_USED
+
+ vec4 shadow_modulate = vec4(1.0);
+ vec3 light_position = vec3(light_array[light_base].position, light_array[light_base].height);
+
+ light_color.rgb *= light_base_color.rgb;
+ light_color = light_compute(light_vertex, light_position, normal, light_color, light_base_color.a, specular_shininess, shadow_modulate, screen_uv, uv, base_color, false);
+#else
+
+ light_color.rgb *= light_base_color.rgb * light_base_color.a;
+
+ if (normal_used) {
+ vec3 light_pos = vec3(light_array[light_base].position, light_array[light_base].height);
+ vec3 pos = light_vertex;
+ vec3 light_vec = normalize(light_pos - pos);
+
+ light_color.rgb = light_normal_compute(light_vec, normal, base_color.rgb, light_color.rgb, specular_shininess, specular_shininess_used);
+ } else {
+ light_color.rgb *= base_color.rgb;
+ }
+#endif
+ if (any(lessThan(tex_uv, vec2(0.0, 0.0))) || any(greaterThanEqual(tex_uv, vec2(1.0, 1.0)))) {
+ //if outside the light texture, light color is zero
+ light_color.a = 0.0;
+ }
+
+ light_blend_compute(light_base, light_color, color.rgb);
+ }
+#endif
+
frag_color = color;
}
diff --git a/drivers/gles3/shaders/canvas_uniforms_inc.glsl b/drivers/gles3/shaders/canvas_uniforms_inc.glsl
index 6b65e09cbf..dd5ebecb1a 100644
--- a/drivers/gles3/shaders/canvas_uniforms_inc.glsl
+++ b/drivers/gles3/shaders/canvas_uniforms_inc.glsl
@@ -82,6 +82,7 @@ layout(std140) uniform CanvasData { //ubo:0
uint pad2;
};
+#ifndef DISABLE_LIGHTING
#define LIGHT_FLAGS_BLEND_MASK uint(3 << 16)
#define LIGHT_FLAGS_BLEND_MODE_ADD uint(0 << 16)
#define LIGHT_FLAGS_BLEND_MODE_SUB uint(1 << 16)
@@ -94,6 +95,27 @@ layout(std140) uniform CanvasData { //ubo:0
#define LIGHT_FLAGS_SHADOW_PCF5 uint(1 << 22)
#define LIGHT_FLAGS_SHADOW_PCF13 uint(2 << 22)
+struct Light {
+ mat2x4 texture_matrix; //light to texture coordinate matrix (transposed)
+ mat2x4 shadow_matrix; //light to shadow coordinate matrix (transposed)
+ vec4 color;
+
+ uint shadow_color; // packed
+ uint flags; //index to light texture
+ float shadow_pixel_size;
+ float height;
+
+ vec2 position;
+ float shadow_zfar_inv;
+ float shadow_y_ofs;
+
+ vec4 atlas_rect;
+};
+
+layout(std140) uniform LightData { //ubo:2
+ Light light_array[MAX_LIGHTS];
+};
+#endif // DISABLE_LIGHTING
layout(std140) uniform DrawDataInstances { //ubo:3
DrawData draw_data[MAX_DRAW_DATA_INSTANCES];
diff --git a/drivers/gles3/shaders/copy.glsl b/drivers/gles3/shaders/copy.glsl
index ca2fc7e36d..796ba79c2e 100644
--- a/drivers/gles3/shaders/copy.glsl
+++ b/drivers/gles3/shaders/copy.glsl
@@ -2,7 +2,7 @@
#[modes]
mode_default = #define MODE_SIMPLE_COPY
-mode_copy_section = #define USE_COPY_SECTION
+mode_copy_section = #define USE_COPY_SECTION \n#define MODE_SIMPLE_COPY
mode_gaussian_blur = #define MODE_GAUSSIAN_BLUR
mode_mipmap = #define MODE_MIPMAP
mode_simple_color = #define MODE_SIMPLE_COLOR \n#define USE_COPY_SECTION
@@ -25,8 +25,7 @@ void main() {
gl_Position = vec4(vertex_attrib, 1.0, 1.0);
#ifdef USE_COPY_SECTION
- gl_Position.xy = (copy_section.xy + (uv_interp.xy * 0.5 + 0.5) * copy_section.zw) * 2.0 - 1.0;
- uv_interp = copy_section.xy + uv_interp * copy_section.zw;
+ gl_Position.xy = (copy_section.xy + uv_interp.xy * copy_section.zw) * 2.0 - 1.0;
#endif
}
diff --git a/drivers/gles3/shaders/scene.glsl b/drivers/gles3/shaders/scene.glsl
index efd6036ba9..ed176c7829 100644
--- a/drivers/gles3/shaders/scene.glsl
+++ b/drivers/gles3/shaders/scene.glsl
@@ -16,6 +16,7 @@ DISABLE_LIGHT_OMNI = false
DISABLE_LIGHT_SPOT = false
DISABLE_FOG = false
USE_RADIANCE_MAP = true
+USE_MULTIVIEW = false
#[vertex]
@@ -153,6 +154,15 @@ layout(std140) uniform SceneData { // ubo:2
}
scene_data;
+#ifdef USE_MULTIVIEW
+layout(std140) uniform MultiviewData { // ubo:8
+ highp mat4 projection_matrix_view[MAX_VIEWS];
+ highp mat4 inv_projection_matrix_view[MAX_VIEWS];
+ highp vec4 eye_offset[MAX_VIEWS];
+}
+multiview_data;
+#endif
+
uniform highp mat4 world_transform;
#ifdef USE_LIGHTMAP
@@ -250,8 +260,14 @@ void main() {
#if defined(OVERRIDE_POSITION)
highp vec4 position;
#endif
- highp mat4 projection_matrix = scene_data.projection_matrix;
- highp mat4 inv_projection_matrix = scene_data.inv_projection_matrix;
+
+#ifdef USE_MULTIVIEW
+ mat4 projection_matrix = multiview_data.projection_matrix_view[ViewIndex];
+ mat4 inv_projection_matrix = multiview_data.inv_projection_matrix_view[ViewIndex];
+#else
+ mat4 projection_matrix = scene_data.projection_matrix;
+ mat4 inv_projection_matrix = scene_data.inv_projection_matrix;
+#endif //USE_MULTIVIEW
#ifdef USE_INSTANCING
vec4 instance_custom = vec4(unpackHalf2x16(instance_color_custom_data.z), unpackHalf2x16(instance_color_custom_data.w));
@@ -339,7 +355,6 @@ void main() {
/* clang-format off */
#[fragment]
-
// Default to SPECULAR_SCHLICK_GGX.
#if !defined(SPECULAR_DISABLED) && !defined(SPECULAR_SCHLICK_GGX) && !defined(SPECULAR_TOON)
#define SPECULAR_SCHLICK_GGX
@@ -463,6 +478,15 @@ layout(std140) uniform SceneData { // ubo:2
}
scene_data;
+#ifdef USE_MULTIVIEW
+layout(std140) uniform MultiviewData { // ubo:8
+ highp mat4 projection_matrix_view[MAX_VIEWS];
+ highp mat4 inv_projection_matrix_view[MAX_VIEWS];
+ highp vec4 eye_offset[MAX_VIEWS];
+}
+multiview_data;
+#endif
+
/* clang-format off */
#GLOBALS
@@ -530,8 +554,13 @@ uniform highp samplerCubeShadow positional_shadow; // texunit:-4
#endif // !defined(DISABLE_LIGHT_OMNI) && !defined(DISABLE_LIGHT_SPOT)
-uniform highp sampler2D screen_texture; // texunit:-5
+#ifdef USE_MULTIVIEW
+uniform highp sampler2DArray depth_buffer; // texunit:-6
+uniform highp sampler2DArray screen_texture; // texunit:-5
+#else
uniform highp sampler2D depth_buffer; // texunit:-6
+uniform highp sampler2D screen_texture; // texunit:-5
+#endif
uniform highp mat4 world_transform;
uniform mediump float opaque_prepass_threshold;
@@ -884,7 +913,11 @@ vec4 fog_process(vec3 vertex) {
void main() {
//lay out everything, whatever is unused is optimized away anyway
vec3 vertex = vertex_interp;
+#ifdef USE_MULTIVIEW
+ vec3 view = -normalize(vertex_interp - multiview_data.eye_offset[ViewIndex].xyz);
+#else
vec3 view = -normalize(vertex_interp);
+#endif
vec3 albedo = vec3(1.0);
vec3 backlight = vec3(0.0);
vec4 transmittance_color = vec4(0.0, 0.0, 0.0, 1.0);
@@ -1096,9 +1129,15 @@ void main() {
#if defined(CUSTOM_IRRADIANCE_USED)
ambient_light = mix(ambient_light, custom_irradiance.rgb, custom_irradiance.a);
#endif // CUSTOM_IRRADIANCE_USED
- ambient_light *= albedo.rgb;
- ambient_light *= ao;
+ {
+#if defined(AMBIENT_LIGHT_DISABLED)
+ ambient_light = vec3(0.0, 0.0, 0.0);
+#else
+ ambient_light *= albedo.rgb;
+ ambient_light *= ao;
+#endif // AMBIENT_LIGHT_DISABLED
+ }
// convert ao to direct light ao
ao = mix(1.0, ao, ao_light_affect);
diff --git a/drivers/gles3/shaders/tonemap.glsl b/drivers/gles3/shaders/tonemap.glsl
index a478cf9170..0b769e77f2 100644
--- a/drivers/gles3/shaders/tonemap.glsl
+++ b/drivers/gles3/shaders/tonemap.glsl
@@ -44,7 +44,11 @@ in vec2 uv_interp;
layout(location = 0) out vec4 frag_color;
+#ifdef USE_MULTIVIEW
+uniform highp sampler2DArray source; //texunit:0
+#else
uniform highp sampler2D source; //texunit:0
+#endif
#if defined(USE_GLOW_LEVEL1) || defined(USE_GLOW_LEVEL2) || defined(USE_GLOW_LEVEL3) || defined(USE_GLOW_LEVEL4) || defined(USE_GLOW_LEVEL5) || defined(USE_GLOW_LEVEL6) || defined(USE_GLOW_LEVEL7)
#define USING_GLOW // only use glow when at least one glow level is selected
@@ -191,10 +195,17 @@ vec3 apply_fxaa(vec3 color, vec2 uv_interp, vec2 pixel_size) {
const float FXAA_REDUCE_MUL = (1.0 / 8.0);
const float FXAA_SPAN_MAX = 8.0;
+#ifdef USE_MULTIVIEW
+ vec3 rgbNW = textureLod(source, vec3(uv_interp + vec2(-1.0, -1.0) * pixel_size, ViewIndex), 0.0).xyz;
+ vec3 rgbNE = textureLod(source, vec3(uv_interp + vec2(1.0, -1.0) * pixel_size, ViewIndex), 0.0).xyz;
+ vec3 rgbSW = textureLod(source, vec3(uv_interp + vec2(-1.0, 1.0) * pixel_size, ViewIndex), 0.0).xyz;
+ vec3 rgbSE = textureLod(source, vec3(uv_interp + vec2(1.0, 1.0) * pixel_size, ViewIndex), 0.0).xyz;
+#else
vec3 rgbNW = textureLod(source, uv_interp + vec2(-1.0, -1.0) * pixel_size, 0.0).xyz;
vec3 rgbNE = textureLod(source, uv_interp + vec2(1.0, -1.0) * pixel_size, 0.0).xyz;
vec3 rgbSW = textureLod(source, uv_interp + vec2(-1.0, 1.0) * pixel_size, 0.0).xyz;
vec3 rgbSE = textureLod(source, uv_interp + vec2(1.0, 1.0) * pixel_size, 0.0).xyz;
+#endif
vec3 rgbM = color;
vec3 luma = vec3(0.299, 0.587, 0.114);
float lumaNW = dot(rgbNW, luma);
@@ -219,8 +230,13 @@ vec3 apply_fxaa(vec3 color, vec2 uv_interp, vec2 pixel_size) {
dir * rcpDirMin)) *
pixel_size;
+#ifdef USE_MULTIVIEW
+ vec3 rgbA = 0.5 * (textureLod(source, vec3(uv_interp + dir * (1.0 / 3.0 - 0.5), ViewIndex), 0.0).xyz + textureLod(source, vec3(uv_interp + dir * (2.0 / 3.0 - 0.5), ViewIndex), 0.0).xyz);
+ vec3 rgbB = rgbA * 0.5 + 0.25 * (textureLod(source, vec3(uv_interp + dir * -0.5, ViewIndex), 0.0).xyz + textureLod(source, vec3(uv_interp + dir * 0.5, ViewIndex), 0.0).xyz);
+#else
vec3 rgbA = 0.5 * (textureLod(source, uv_interp + dir * (1.0 / 3.0 - 0.5), 0.0).xyz + textureLod(source, uv_interp + dir * (2.0 / 3.0 - 0.5), 0.0).xyz);
vec3 rgbB = rgbA * 0.5 + 0.25 * (textureLod(source, uv_interp + dir * -0.5, 0.0).xyz + textureLod(source, uv_interp + dir * 0.5, 0.0).xyz);
+#endif
float lumaB = dot(rgbB, luma);
if ((lumaB < lumaMin) || (lumaB > lumaMax)) {
@@ -231,7 +247,11 @@ vec3 apply_fxaa(vec3 color, vec2 uv_interp, vec2 pixel_size) {
}
void main() {
+#ifdef USE_MULTIVIEW
+ vec4 color = textureLod(source, vec3(uv_interp, ViewIndex), 0.0);
+#else
vec4 color = textureLod(source, uv_interp, 0.0);
+#endif
#ifdef USE_FXAA
color.rgb = apply_fxaa(color.rgb, uv_interp, pixel_size);
diff --git a/drivers/gles3/storage/config.cpp b/drivers/gles3/storage/config.cpp
index 242c1ce0a9..943df3b156 100644
--- a/drivers/gles3/storage/config.cpp
+++ b/drivers/gles3/storage/config.cpp
@@ -34,6 +34,15 @@
#include "core/config/project_settings.h"
#include "core/templates/vector.h"
+#ifdef ANDROID_ENABLED
+#include <GLES3/gl3.h>
+#include <GLES3/gl3ext.h>
+#include <GLES3/gl3platform.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#endif
+
using namespace GLES3;
#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
@@ -85,6 +94,7 @@ Config::Config() {
glGetIntegerv(GL_MAX_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);
+ glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &max_viewport_size);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_offset_alignment);
@@ -98,6 +108,16 @@ Config::Config() {
anisotropic_level = MIN(float(1 << int(ProjectSettings::get_singleton()->get("rendering/textures/default_filters/anisotropic_filtering_level"))), anisotropic_level);
}
+ multiview_supported = extensions.has("GL_OVR_multiview2") || extensions.has("GL_OVR_multiview");
+#ifdef ANDROID_ENABLED
+ if (multiview_supported) {
+ eglFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)eglGetProcAddress("glFramebufferTextureMultiviewOVR");
+ if (eglFramebufferTextureMultiviewOVR == nullptr) {
+ multiview_supported = false;
+ }
+ }
+#endif
+
force_vertex_shading = false; //GLOBAL_GET("rendering/quality/shading/force_vertex_shading");
use_nearest_mip_filter = GLOBAL_GET("rendering/textures/default_filters/use_nearest_mipmap_filter");
diff --git a/drivers/gles3/storage/config.h b/drivers/gles3/storage/config.h
index fe18345775..d4b38acd18 100644
--- a/drivers/gles3/storage/config.h
+++ b/drivers/gles3/storage/config.h
@@ -44,6 +44,10 @@
#include OPENGL_INCLUDE_H
#endif
+#ifdef ANDROID_ENABLED
+typedef void (*PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)(GLenum, GLenum, GLuint, GLint, GLint, GLsizei);
+#endif
+
namespace GLES3 {
class Config {
@@ -60,6 +64,7 @@ public:
int max_texture_image_units = 0;
int max_texture_size = 0;
int max_uniform_buffer_size = 0;
+ int max_viewport_size = 0;
int max_renderable_elements = 0;
int max_renderable_lights = 0;
int max_lights_per_object = 0;
@@ -82,6 +87,11 @@ public:
bool support_anisotropic_filter = false;
float anisotropic_level = 0.0f;
+ bool multiview_supported = false;
+#ifdef ANDROID_ENABLED
+ PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC eglFramebufferTextureMultiviewOVR = nullptr;
+#endif
+
static Config *get_singleton() { return singleton; };
Config();
diff --git a/drivers/gles3/storage/material_storage.cpp b/drivers/gles3/storage/material_storage.cpp
index ae396ca0f3..724ad57d64 100644
--- a/drivers/gles3/storage/material_storage.cpp
+++ b/drivers/gles3/storage/material_storage.cpp
@@ -897,7 +897,9 @@ _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type,
case ShaderLanguage::TYPE_BVEC3:
case ShaderLanguage::TYPE_IVEC3:
case ShaderLanguage::TYPE_UVEC3:
- case ShaderLanguage::TYPE_VEC3:
+ case ShaderLanguage::TYPE_VEC3: {
+ memset(data, 0, 12 * p_array_size);
+ } break;
case ShaderLanguage::TYPE_BVEC4:
case ShaderLanguage::TYPE_IVEC4:
case ShaderLanguage::TYPE_UVEC4:
diff --git a/drivers/gles3/storage/mesh_storage.cpp b/drivers/gles3/storage/mesh_storage.cpp
index 22d84eba93..11ce31856d 100644
--- a/drivers/gles3/storage/mesh_storage.cpp
+++ b/drivers/gles3/storage/mesh_storage.cpp
@@ -309,12 +309,48 @@ RS::BlendShapeMode MeshStorage::mesh_get_blend_shape_mode(RID p_mesh) const {
}
void MeshStorage::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count);
+ ERR_FAIL_COND(p_data.size() == 0);
+
+ uint64_t data_size = p_data.size();
+ ERR_FAIL_COND(p_offset + data_size > mesh->surfaces[p_surface]->vertex_buffer_size);
+ const uint8_t *r = p_data.ptr();
+
+ glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->vertex_buffer);
+ glBufferSubData(GL_ARRAY_BUFFER, p_offset, data_size, r);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void MeshStorage::mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count);
+ ERR_FAIL_COND(p_data.size() == 0);
+
+ uint64_t data_size = p_data.size();
+ ERR_FAIL_COND(p_offset + data_size > mesh->surfaces[p_surface]->attribute_buffer_size);
+ const uint8_t *r = p_data.ptr();
+
+ glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->attribute_buffer);
+ glBufferSubData(GL_ARRAY_BUFFER, p_offset, data_size, r);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void MeshStorage::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
+ Mesh *mesh = mesh_owner.get_or_null(p_mesh);
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count);
+ ERR_FAIL_COND(p_data.size() == 0);
+
+ uint64_t data_size = p_data.size();
+ ERR_FAIL_COND(p_offset + data_size > mesh->surfaces[p_surface]->skin_buffer_size);
+ const uint8_t *r = p_data.ptr();
+
+ glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->skin_buffer);
+ glBufferSubData(GL_ARRAY_BUFFER, p_offset, data_size, r);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void MeshStorage::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) {
diff --git a/drivers/gles3/storage/mesh_storage.h b/drivers/gles3/storage/mesh_storage.h
index 74f5800795..a31db24f2d 100644
--- a/drivers/gles3/storage/mesh_storage.h
+++ b/drivers/gles3/storage/mesh_storage.h
@@ -325,13 +325,12 @@ public:
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 {
+ _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) 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;
- }
+ 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) {
@@ -342,9 +341,7 @@ public:
if (current_lod == -1) {
return 0;
} else {
- if (r_index_count) {
- *r_index_count = s->lods[current_lod].index_count;
- }
+ r_index_count = s->lods[current_lod].index_count;
return current_lod + 1;
}
}
diff --git a/drivers/gles3/storage/render_scene_buffers_gles3.cpp b/drivers/gles3/storage/render_scene_buffers_gles3.cpp
index 9123984dc7..b8e4530f56 100644
--- a/drivers/gles3/storage/render_scene_buffers_gles3.cpp
+++ b/drivers/gles3/storage/render_scene_buffers_gles3.cpp
@@ -33,12 +33,17 @@
#include "render_scene_buffers_gles3.h"
#include "texture_storage.h"
+#ifdef ANDROID_ENABLED
+#define glFramebufferTextureMultiviewOVR GLES3::Config::get_singleton()->eglFramebufferTextureMultiviewOVR
+#endif
+
RenderSceneBuffersGLES3::~RenderSceneBuffersGLES3() {
free_render_buffer_data();
}
void RenderSceneBuffersGLES3::configure(RID p_render_target, const Size2i p_internal_size, const Size2i p_target_size, float p_fsr_sharpness, float p_texture_mipmap_bias, RS::ViewportMSAA p_msaa, RenderingServer::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_taa, bool p_use_debanding, uint32_t p_view_count) {
GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
+ GLES3::Config *config = GLES3::Config::get_singleton();
//internal_size.x = p_internal_size.x; // ignore for now
//internal_size.y = p_internal_size.y;
@@ -50,7 +55,7 @@ void RenderSceneBuffersGLES3::configure(RID p_render_target, const Size2i p_inte
//msaa = p_msaa;
//screen_space_aa = p_screen_space_aa;
//use_debanding = p_use_debanding;
- //view_count = p_view_count;
+ view_count = p_view_count;
free_render_buffer_data();
@@ -62,24 +67,43 @@ void RenderSceneBuffersGLES3::configure(RID p_render_target, const Size2i p_inte
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
- glBindTexture(GL_TEXTURE_2D, rt->color);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
+ if (view_count > 1 && config->multiview_supported) {
+ glBindTexture(GL_TEXTURE_2D_ARRAY, rt->color);
+ glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, rt->color, 0, 0, view_count);
+ } else {
+ glBindTexture(GL_TEXTURE_2D, rt->color);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
+ }
glGenTextures(1, &depth_texture);
- glBindTexture(GL_TEXTURE_2D, depth_texture);
-
- glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 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);
+ if (view_count > 1 && config->multiview_supported) {
+ glBindTexture(GL_TEXTURE_2D_ARRAY, depth_texture);
+ glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_DEPTH_COMPONENT24, rt->size.x, rt->size.y, view_count, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
+
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ } else {
+ glBindTexture(GL_TEXTURE_2D, depth_texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 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, depth_texture, 0);
+ if (view_count > 1 && config->multiview_supported) {
+ glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depth_texture, 0, 0, view_count);
+ } else {
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_texture, 0);
+ }
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
glBindTexture(GL_TEXTURE_2D, 0);
+ glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindFramebuffer(GL_FRAMEBUFFER, texture_storage->system_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE) {
diff --git a/drivers/gles3/storage/render_scene_buffers_gles3.h b/drivers/gles3/storage/render_scene_buffers_gles3.h
index ad0d2032b0..dbedbd22c3 100644
--- a/drivers/gles3/storage/render_scene_buffers_gles3.h
+++ b/drivers/gles3/storage/render_scene_buffers_gles3.h
@@ -56,7 +56,7 @@ public:
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;
+ uint32_t view_count = 1;
bool is_transparent = false;
diff --git a/drivers/gles3/storage/texture_storage.cpp b/drivers/gles3/storage/texture_storage.cpp
index 442bd69b55..524ff14cc9 100644
--- a/drivers/gles3/storage/texture_storage.cpp
+++ b/drivers/gles3/storage/texture_storage.cpp
@@ -34,6 +34,10 @@
#include "config.h"
#include "drivers/gles3/effects/copy_effects.h"
+#ifdef ANDROID_ENABLED
+#define glFramebufferTextureMultiviewOVR GLES3::Config::get_singleton()->eglFramebufferTextureMultiviewOVR
+#endif
+
using namespace GLES3;
TextureStorage *TextureStorage::singleton = nullptr;
@@ -59,9 +63,7 @@ TextureStorage::TextureStorage() {
{ //create default textures
{ // White Textures
- Ref<Image> image;
- image.instantiate();
- image->create(4, 4, true, Image::FORMAT_RGBA8);
+ Ref<Image> image = Image::create_empty(4, 4, true, Image::FORMAT_RGBA8);
image->fill(Color(1, 1, 1, 1));
image->generate_mipmaps();
@@ -90,9 +92,7 @@ TextureStorage::TextureStorage() {
}
{ // black
- Ref<Image> image;
- image.instantiate();
- image->create(4, 4, true, Image::FORMAT_RGBA8);
+ Ref<Image> image = Image::create_empty(4, 4, true, Image::FORMAT_RGBA8);
image->fill(Color(0, 0, 0, 1));
image->generate_mipmaps();
@@ -116,9 +116,7 @@ TextureStorage::TextureStorage() {
}
{ // transparent black
- Ref<Image> image;
- image.instantiate();
- image->create(4, 4, true, Image::FORMAT_RGBA8);
+ Ref<Image> image = Image::create_empty(4, 4, true, Image::FORMAT_RGBA8);
image->fill(Color(0, 0, 0, 0));
image->generate_mipmaps();
@@ -127,9 +125,7 @@ TextureStorage::TextureStorage() {
}
{
- Ref<Image> image;
- image.instantiate();
- image->create(4, 4, true, Image::FORMAT_RGBA8);
+ Ref<Image> image = Image::create_empty(4, 4, true, Image::FORMAT_RGBA8);
image->fill(Color(0.5, 0.5, 1, 1));
image->generate_mipmaps();
@@ -138,9 +134,7 @@ TextureStorage::TextureStorage() {
}
{
- Ref<Image> image;
- image.instantiate();
- image->create(4, 4, true, Image::FORMAT_RGBA8);
+ Ref<Image> image = Image::create_empty(4, 4, true, Image::FORMAT_RGBA8);
image->fill(Color(1.0, 0.5, 1, 1));
image->generate_mipmaps();
@@ -197,6 +191,22 @@ TextureStorage::TextureStorage() {
glBindTexture(GL_TEXTURE_2D, 0);
+ { // Atlas Texture initialize.
+ uint8_t 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] = 255;
+ }
+
+ glGenTextures(1, &texture_atlas.texture);
+ glBindTexture(GL_TEXTURE_2D, texture_atlas.texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixel_data);
+ }
+
+ glBindTexture(GL_TEXTURE_2D, 0);
+
#ifdef GLES_OVER_GL
glEnable(GL_PROGRAM_POINT_SIZE);
#endif
@@ -207,6 +217,11 @@ TextureStorage::~TextureStorage() {
for (int i = 0; i < DEFAULT_GL_TEXTURE_MAX; i++) {
texture_free(default_gl_textures[i]);
}
+
+ glDeleteTextures(1, &texture_atlas.texture);
+ texture_atlas.texture = 0;
+ glDeleteFramebuffers(1, &texture_atlas.framebuffer);
+ texture_atlas.framebuffer = 0;
}
//TODO, move back to storage
@@ -653,7 +668,7 @@ void TextureStorage::texture_free(RID p_texture) {
}
}
- //decal_atlas_remove_texture(p_texture);
+ texture_atlas_remove_texture(p_texture);
for (int i = 0; i < t->proxies.size(); i++) {
Texture *p = texture_owner.get_or_null(t->proxies[i]);
@@ -709,8 +724,7 @@ void TextureStorage::texture_proxy_initialize(RID p_texture, RID p_base) {
}
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);
+ texture_set_data(p_texture, p_image, p_layer);
#ifdef TOOLS_ENABLED
Texture *tex = texture_owner.get_or_null(p_texture);
@@ -724,9 +738,7 @@ 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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
texture_2d_initialize(p_texture, image);
@@ -735,9 +747,7 @@ void TextureStorage::texture_2d_placeholder_initialize(RID p_texture) {
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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
Vector<Ref<Image>> images;
@@ -756,9 +766,7 @@ void TextureStorage::texture_2d_layered_placeholder_initialize(RID p_texture, Re
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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
Vector<Ref<Image>> images;
@@ -812,9 +820,7 @@ Ref<Image> TextureStorage::texture_2d_get(RID p_texture) const {
data.resize(data_size);
ERR_FAIL_COND_V(data.size() == 0, Ref<Image>());
- Ref<Image> image;
- image.instantiate();
- image->create(texture->width, texture->height, texture->mipmaps > 1, texture->real_format, data);
+ Ref<Image> image = Image::create_from_data(texture->width, texture->height, texture->mipmaps > 1, texture->real_format, data);
ERR_FAIL_COND_V(image->is_empty(), Ref<Image>());
if (texture->format != texture->real_format) {
image->convert(texture->format);
@@ -875,7 +881,7 @@ void TextureStorage::texture_replace(RID p_texture, RID p_by_texture) {
//delete last, so proxies can be updated
texture_owner.free(p_by_texture);
- //decal_atlas_mark_dirty_on_texture(p_texture);
+ texture_atlas_mark_dirty_on_texture(p_texture);
}
void TextureStorage::texture_set_size_override(RID p_texture, int p_width, int p_height) {
@@ -1009,7 +1015,7 @@ void TextureStorage::texture_set_data(RID p_texture, const Ref<Image> &p_image,
img->resize_to_po2(false);
}
- GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_layer] : GL_TEXTURE_2D;
+ GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_layer] : texture->target;
Vector<uint8_t> read = img->get_data();
@@ -1066,7 +1072,11 @@ 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);
- glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
+ if (texture->target == GL_TEXTURE_2D_ARRAY) {
+ glTexSubImage3D(GL_TEXTURE_2D_ARRAY, i, 0, 0, p_layer, w, h, 0, format, type, &read[ofs]);
+ } else {
+ glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
+ }
}
tsize += size;
@@ -1143,6 +1153,217 @@ RID TextureStorage::texture_create_radiance_cubemap(RID p_source, int p_resoluti
return RID();
}
+/* TEXTURE ATLAS API */
+
+void TextureStorage::texture_add_to_texture_atlas(RID p_texture) {
+ if (!texture_atlas.textures.has(p_texture)) {
+ TextureAtlas::Texture t;
+ t.users = 1;
+ texture_atlas.textures[p_texture] = t;
+ texture_atlas.dirty = true;
+ } else {
+ TextureAtlas::Texture *t = texture_atlas.textures.getptr(p_texture);
+ t->users++;
+ }
+}
+
+void TextureStorage::texture_remove_from_texture_atlas(RID p_texture) {
+ TextureAtlas::Texture *t = texture_atlas.textures.getptr(p_texture);
+ ERR_FAIL_COND(!t);
+ t->users--;
+ if (t->users == 0) {
+ texture_atlas.textures.erase(p_texture);
+ // Do not mark it dirty, there is no need to since it remains working.
+ }
+}
+
+void TextureStorage::texture_atlas_mark_dirty_on_texture(RID p_texture) {
+ if (texture_atlas.textures.has(p_texture)) {
+ texture_atlas.dirty = true; // Mark it dirty since it was most likely modified.
+ }
+}
+
+void TextureStorage::texture_atlas_remove_texture(RID p_texture) {
+ if (texture_atlas.textures.has(p_texture)) {
+ texture_atlas.textures.erase(p_texture);
+ // There is not much a point of making it dirty, texture can be removed next time the atlas is updated.
+ }
+}
+
+GLuint TextureStorage::texture_atlas_get_texture() const {
+ return texture_atlas.texture;
+}
+
+void TextureStorage::update_texture_atlas() {
+ CopyEffects *copy_effects = CopyEffects::get_singleton();
+ ERR_FAIL_NULL(copy_effects);
+
+ if (!texture_atlas.dirty) {
+ return; //nothing to do
+ }
+
+ texture_atlas.dirty = false;
+
+ if (texture_atlas.texture != 0) {
+ glDeleteTextures(1, &texture_atlas.texture);
+ texture_atlas.texture = 0;
+ glDeleteFramebuffers(1, &texture_atlas.framebuffer);
+ texture_atlas.framebuffer = 0;
+ }
+
+ const int border = 2;
+
+ if (texture_atlas.textures.size()) {
+ //generate atlas
+ Vector<TextureAtlas::SortItem> itemsv;
+ itemsv.resize(texture_atlas.textures.size());
+ int base_size = 8;
+
+ int idx = 0;
+
+ for (const KeyValue<RID, TextureAtlas::Texture> &E : texture_atlas.textures) {
+ TextureAtlas::SortItem &si = itemsv.write[idx];
+
+ Texture *src_tex = get_texture(E.key);
+
+ si.size.width = (src_tex->width / border) + 1;
+ si.size.height = (src_tex->height / border) + 1;
+ si.pixel_size = Size2i(src_tex->width, src_tex->height);
+
+ if (base_size < si.size.width) {
+ base_size = nearest_power_of_2_templated(si.size.width);
+ }
+
+ si.texture = E.key;
+ idx++;
+ }
+
+ //sort items by size
+ itemsv.sort();
+
+ //attempt to create atlas
+ int item_count = itemsv.size();
+ TextureAtlas::SortItem *items = itemsv.ptrw();
+
+ int atlas_height = 0;
+
+ while (true) {
+ Vector<int> v_offsetsv;
+ v_offsetsv.resize(base_size);
+
+ int *v_offsets = v_offsetsv.ptrw();
+ memset(v_offsets, 0, sizeof(int) * base_size);
+
+ int max_height = 0;
+
+ for (int i = 0; i < item_count; i++) {
+ //best fit
+ TextureAtlas::SortItem &si = items[i];
+ int best_idx = -1;
+ int best_height = 0x7FFFFFFF;
+ for (int j = 0; j <= base_size - si.size.width; j++) {
+ int height = 0;
+ for (int k = 0; k < si.size.width; k++) {
+ int h = v_offsets[k + j];
+ if (h > height) {
+ height = h;
+ if (height > best_height) {
+ break; //already bad
+ }
+ }
+ }
+
+ if (height < best_height) {
+ best_height = height;
+ best_idx = j;
+ }
+ }
+
+ //update
+ for (int k = 0; k < si.size.width; k++) {
+ v_offsets[k + best_idx] = best_height + si.size.height;
+ }
+
+ si.pos.x = best_idx;
+ si.pos.y = best_height;
+
+ if (si.pos.y + si.size.height > max_height) {
+ max_height = si.pos.y + si.size.height;
+ }
+ }
+
+ if (max_height <= base_size * 2) {
+ atlas_height = max_height;
+ break; //good ratio, break;
+ }
+
+ base_size *= 2;
+ }
+
+ texture_atlas.size.width = base_size * border;
+ texture_atlas.size.height = nearest_power_of_2_templated(atlas_height * border);
+
+ for (int i = 0; i < item_count; i++) {
+ TextureAtlas::Texture *t = texture_atlas.textures.getptr(items[i].texture);
+ t->uv_rect.position = items[i].pos * border + Vector2i(border / 2, border / 2);
+ t->uv_rect.size = items[i].pixel_size;
+
+ t->uv_rect.position /= Size2(texture_atlas.size);
+ t->uv_rect.size /= Size2(texture_atlas.size);
+ }
+ } else {
+ texture_atlas.size.width = 4;
+ texture_atlas.size.height = 4;
+ }
+
+ { // Atlas Texture initialize.
+ // TODO validate texture atlas size with maximum texture size
+ glGenTextures(1, &texture_atlas.texture);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, texture_atlas.texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texture_atlas.size.width, texture_atlas.size.height, 0, GL_RGBA, 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);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
+
+ glGenFramebuffers(1, &texture_atlas.framebuffer);
+ glBindFramebuffer(GL_FRAMEBUFFER, texture_atlas.framebuffer);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_atlas.texture, 0);
+
+ GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+
+ if (status != GL_FRAMEBUFFER_COMPLETE) {
+ glDeleteFramebuffers(1, &texture_atlas.framebuffer);
+ texture_atlas.framebuffer = 0;
+ glDeleteTextures(1, &texture_atlas.texture);
+ texture_atlas.texture = 0;
+ WARN_PRINT("Could not create texture atlas, status: " + get_framebuffer_error(status));
+ return;
+ }
+ glViewport(0, 0, texture_atlas.size.width, texture_atlas.size.height);
+ glClearColor(0.0, 0.0, 0.0, 0.0);
+ glClear(GL_COLOR_BUFFER_BIT);
+ glBindTexture(GL_TEXTURE_2D, 0);
+ }
+
+ glDisable(GL_BLEND);
+
+ if (texture_atlas.textures.size()) {
+ for (const KeyValue<RID, TextureAtlas::Texture> &E : texture_atlas.textures) {
+ TextureAtlas::Texture *t = texture_atlas.textures.getptr(E.key);
+ Texture *src_tex = get_texture(E.key);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, src_tex->tex_id);
+ copy_effects->copy_to_rect(t->uv_rect);
+ }
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+}
+
/* DECAL API */
RID TextureStorage::decal_allocate() {
@@ -1211,6 +1432,8 @@ void TextureStorage::_update_render_target(RenderTarget *rt) {
return;
}
+ Config *config = Config::get_singleton();
+
rt->color_internal_format = rt->is_transparent ? GL_RGBA8 : GL_RGB10_A2;
rt->color_format = GL_RGBA;
rt->color_type = rt->is_transparent ? GL_UNSIGNED_BYTE : GL_UNSIGNED_INT_2_10_10_10_REV;
@@ -1232,17 +1455,29 @@ void TextureStorage::_update_render_target(RenderTarget *rt) {
// color
glGenTextures(1, &rt->color);
- glBindTexture(GL_TEXTURE_2D, rt->color);
-
- glTexImage2D(GL_TEXTURE_2D, 0, rt->color_internal_format, rt->size.x, rt->size.y, 0, rt->color_format, rt->color_type, nullptr);
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ if (rt->view_count > 1 && config->multiview_supported) {
+ glBindTexture(GL_TEXTURE_2D_ARRAY, rt->color);
+ glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, rt->color_internal_format, rt->size.x, rt->size.y, rt->view_count, 0, rt->color_format, rt->color_type, nullptr);
+
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ } else {
+ glBindTexture(GL_TEXTURE_2D, rt->color);
+ glTexImage2D(GL_TEXTURE_2D, 0, rt->color_internal_format, rt->size.x, rt->size.y, 0, rt->color_format, rt->color_type, nullptr);
- 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_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);
+ if (rt->view_count > 1 && config->multiview_supported) {
+ glFramebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, rt->color, 0, 0, rt->view_count);
+ } else {
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
+ }
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
@@ -1261,8 +1496,15 @@ void TextureStorage::_update_render_target(RenderTarget *rt) {
texture->format = rt->image_format;
texture->real_format = rt->image_format;
- texture->type = Texture::TYPE_2D;
- texture->target = GL_TEXTURE_2D;
+ if (rt->view_count > 1 && config->multiview_supported) {
+ texture->type = Texture::TYPE_LAYERED;
+ texture->target = GL_TEXTURE_2D_ARRAY;
+ texture->layers = rt->view_count;
+ } else {
+ texture->type = Texture::TYPE_2D;
+ texture->target = GL_TEXTURE_2D;
+ texture->layers = 1;
+ }
texture->gl_format_cache = rt->color_format;
texture->gl_type_cache = GL_UNSIGNED_BYTE;
texture->gl_internal_format_cache = rt->color_internal_format;
@@ -1405,13 +1647,14 @@ void TextureStorage::render_target_set_size(RID p_render_target, int p_width, in
RenderTarget *rt = render_target_owner.get_or_null(p_render_target);
ERR_FAIL_COND(!rt);
- if (p_width == rt->size.x && p_height == rt->size.y) {
+ if (p_width == rt->size.x && p_height == rt->size.y && p_view_count == rt->view_count) {
return;
}
_clear_render_target(rt);
rt->size = Size2i(p_width, p_height);
+ rt->view_count = p_view_count;
_update_render_target(rt);
}
diff --git a/drivers/gles3/storage/texture_storage.h b/drivers/gles3/storage/texture_storage.h
index 7e083e48e8..dbe39428ac 100644
--- a/drivers/gles3/storage/texture_storage.h
+++ b/drivers/gles3/storage/texture_storage.h
@@ -324,6 +324,7 @@ private:
struct RenderTarget {
Point2i position = Point2i(0, 0);
Size2i size = Size2i(0, 0);
+ uint32_t view_count = 1;
int mipmap_count = 1;
RID self;
GLuint fbo = 0;
@@ -371,6 +372,38 @@ private:
Ref<Image> _get_gl_image_and_format(const Ref<Image> &p_image, Image::Format p_format, 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;
+ /* TEXTURE ATLAS API */
+
+ struct TextureAtlas {
+ struct Texture {
+ int users;
+ Rect2 uv_rect;
+ };
+
+ struct SortItem {
+ RID texture;
+ Size2i pixel_size;
+ Size2i size;
+ Point2i pos;
+
+ bool operator<(const SortItem &p_item) const {
+ //sort larger to smaller
+ if (size.height == p_item.size.height) {
+ return size.width > p_item.size.width;
+ } else {
+ return size.height > p_item.size.height;
+ }
+ }
+ };
+
+ HashMap<RID, Texture> textures;
+ bool dirty = true;
+
+ GLuint texture = 0;
+ GLuint framebuffer = 0;
+ Size2i size;
+ } texture_atlas;
+
/* Render Target API */
mutable RID_Owner<RenderTarget> render_target_owner;
@@ -473,6 +506,25 @@ public:
void texture_bind(RID p_texture, uint32_t p_texture_no);
RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const;
+ /* TEXTURE ATLAS API */
+
+ void update_texture_atlas();
+
+ GLuint texture_atlas_get_texture() const;
+ _FORCE_INLINE_ Rect2 texture_atlas_get_texture_rect(RID p_texture) {
+ TextureAtlas::Texture *t = texture_atlas.textures.getptr(p_texture);
+ if (!t) {
+ return Rect2();
+ }
+
+ return t->uv_rect;
+ }
+
+ void texture_add_to_texture_atlas(RID p_texture);
+ void texture_remove_from_texture_atlas(RID p_texture);
+ void texture_atlas_mark_dirty_on_texture(RID p_texture);
+ void texture_atlas_remove_texture(RID p_texture);
+
/* DECAL API */
virtual RID decal_allocate() override;
diff --git a/drivers/gles3/storage/utilities.cpp b/drivers/gles3/storage/utilities.cpp
index 16bacf1829..0a04f0d4d0 100644
--- a/drivers/gles3/storage/utilities.cpp
+++ b/drivers/gles3/storage/utilities.cpp
@@ -302,6 +302,7 @@ void Utilities::update_dirty_resources() {
MaterialStorage::get_singleton()->_update_queued_materials();
//MeshStorage::get_singleton()->_update_dirty_skeletons();
MeshStorage::get_singleton()->_update_dirty_multimeshes();
+ TextureStorage::get_singleton()->update_texture_atlas();
}
void Utilities::set_debug_generate_wireframes(bool p_generate) {
@@ -355,4 +356,13 @@ String Utilities::get_video_adapter_api_version() const {
return (const char *)glGetString(GL_VERSION);
}
+Size2i Utilities::get_maximum_viewport_size() const {
+ Config *config = Config::get_singleton();
+ if (!config) {
+ return Size2i();
+ }
+
+ return Size2i(config->max_viewport_size, config->max_viewport_size);
+}
+
#endif // GLES3_ENABLED
diff --git a/drivers/gles3/storage/utilities.h b/drivers/gles3/storage/utilities.h
index e054f2f816..936ac35cc9 100644
--- a/drivers/gles3/storage/utilities.h
+++ b/drivers/gles3/storage/utilities.h
@@ -150,6 +150,8 @@ public:
virtual String get_video_adapter_vendor() const override;
virtual RenderingDevice::DeviceType get_video_adapter_type() const override;
virtual String get_video_adapter_api_version() const override;
+
+ virtual Size2i get_maximum_viewport_size() const override;
};
} // namespace GLES3
diff --git a/drivers/png/png_driver_common.cpp b/drivers/png/png_driver_common.cpp
index bc4bb3782b..79641464d8 100644
--- a/drivers/png/png_driver_common.cpp
+++ b/drivers/png/png_driver_common.cpp
@@ -119,7 +119,7 @@ Error png_to_image(const uint8_t *p_source, size_t p_size, bool p_force_linear,
ERR_FAIL_COND_V(!success, ERR_FILE_CORRUPT);
//print_line("png width: "+itos(png_img.width)+" height: "+itos(png_img.height));
- p_image->create(png_img.width, png_img.height, false, dest_format, buffer);
+ p_image->set_data(png_img.width, png_img.height, false, dest_format, buffer);
return OK;
}
diff --git a/drivers/unix/net_socket_posix.cpp b/drivers/unix/net_socket_posix.cpp
index 72ae609fb4..c6b327eeee 100644
--- a/drivers/unix/net_socket_posix.cpp
+++ b/drivers/unix/net_socket_posix.cpp
@@ -179,8 +179,8 @@ NetSocketPosix::~NetSocketPosix() {
close();
}
-// Silent a warning reported in #27594
-
+// Silence a warning reported in GH-27594.
+// EAGAIN and EWOULDBLOCK have the same value on most platforms, but it's not guaranteed.
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp
index 10d65b83db..fc06291a3a 100644
--- a/drivers/unix/os_unix.cpp
+++ b/drivers/unix/os_unix.cpp
@@ -145,6 +145,10 @@ void OS_Unix::finalize_core() {
NetSocketPosix::cleanup();
}
+Vector<String> OS_Unix::get_video_adapter_driver_info() const {
+ return Vector<String>();
+}
+
String OS_Unix::get_stdin_string(bool p_block) {
if (p_block) {
char buff[1024];
diff --git a/drivers/unix/os_unix.h b/drivers/unix/os_unix.h
index fce962e32c..ce06a52a95 100644
--- a/drivers/unix/os_unix.h
+++ b/drivers/unix/os_unix.h
@@ -51,6 +51,8 @@ protected:
public:
OS_Unix();
+ virtual Vector<String> get_video_adapter_driver_info() const override;
+
virtual String get_stdin_string(bool p_block) override;
virtual Error get_entropy(uint8_t *r_buffer, int p_bytes) override;
diff --git a/drivers/unix/thread_posix.cpp b/drivers/unix/thread_posix.cpp
index f6adbee108..5154feb478 100644
--- a/drivers/unix/thread_posix.cpp
+++ b/drivers/unix/thread_posix.cpp
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)
+#if defined(UNIX_ENABLED)
#include "thread_posix.h"
@@ -73,4 +73,4 @@ void init_thread_posix() {
Thread::_set_platform_functions({ .set_name = set_name });
}
-#endif // UNIX_ENABLED || PTHREAD_ENABLED
+#endif // UNIX_ENABLED
diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp
index 9b193056c2..de29363556 100644
--- a/drivers/vulkan/rendering_device_vulkan.cpp
+++ b/drivers/vulkan/rendering_device_vulkan.cpp
@@ -1655,9 +1655,7 @@ RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const T
image_create_info.pNext = nullptr;
image_create_info.flags = 0;
-#ifndef _MSC_VER
-#warning TODO check for support via RenderingDevice to enable on mobile when possible
-#endif
+ // TODO: Check for support via RenderingDevice to enable on mobile when possible.
#ifndef ANDROID_ENABLED
@@ -5172,9 +5170,9 @@ Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Ve
uint32_t offset = 0;
uint8_t *binptr = ret.ptrw();
binptr[0] = 'G';
- binptr[1] = 'V';
+ binptr[1] = 'S';
binptr[2] = 'B';
- binptr[3] = 'D'; // Godot vulkan binary data.
+ binptr[3] = 'D'; // Godot Shader Binary Data.
offset += 4;
encode_uint32(SHADER_BINARY_VERSION, binptr + offset);
offset += sizeof(uint32_t);
@@ -5235,7 +5233,7 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_
uint32_t read_offset = 0;
// Consistency check.
ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID());
- ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'V' || binptr[2] != 'B' || binptr[3] != 'D', RID());
+ ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', RID());
uint32_t bin_version = decode_uint32(binptr + 4);
ERR_FAIL_COND_V(bin_version != SHADER_BINARY_VERSION, RID());
@@ -6561,7 +6559,7 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma
ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
- rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
+ rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enabled;
rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
@@ -9393,7 +9391,7 @@ void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_de
ERR_CONTINUE(err != OK);
}
- max_descriptors_per_pool = GLOBAL_DEF("rendering/rendering_device/descriptor_pools/max_descriptors_per_pool", 64);
+ max_descriptors_per_pool = GLOBAL_DEF("rendering/rendering_device/vulkan/max_descriptors_per_pool", 64);
// Check to make sure DescriptorPoolKey is good.
static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
@@ -9688,6 +9686,10 @@ uint64_t RenderingDeviceVulkan::limit_get(Limit p_limit) const {
return limits.maxComputeWorkGroupSize[1];
case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
return limits.maxComputeWorkGroupSize[2];
+ case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
+ return limits.maxViewportDimensions[0];
+ case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
+ return limits.maxViewportDimensions[1];
case LIMIT_SUBGROUP_SIZE: {
VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities();
return subgroup_capabilities.size;
diff --git a/drivers/vulkan/vulkan_context.cpp b/drivers/vulkan/vulkan_context.cpp
index 1ab8914624..9ee5a67471 100644
--- a/drivers/vulkan/vulkan_context.cpp
+++ b/drivers/vulkan/vulkan_context.cpp
@@ -48,15 +48,119 @@
VulkanHooks *VulkanContext::vulkan_hooks = nullptr;
-VkResult VulkanContext::vkCreateRenderPass2KHR(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass) {
- if (fpCreateRenderPass2KHR == nullptr) {
- fpCreateRenderPass2KHR = (PFN_vkCreateRenderPass2KHR)vkGetInstanceProcAddr(inst, "vkCreateRenderPass2KHR");
+Vector<VkAttachmentReference> VulkanContext::_convert_VkAttachmentReference2(uint32_t p_count, const VkAttachmentReference2 *p_refs) {
+ Vector<VkAttachmentReference> att_refs;
+
+ if (p_refs != nullptr) {
+ for (uint32_t i = 0; i < p_count; i++) {
+ // We lose aspectMask in this conversion but we don't use it currently.
+
+ VkAttachmentReference ref = {
+ p_refs[i].attachment, /* attachment */
+ p_refs[i].layout /* layout */
+ };
+
+ att_refs.push_back(ref);
+ }
}
- if (fpCreateRenderPass2KHR == nullptr) {
- return VK_ERROR_EXTENSION_NOT_PRESENT;
+ return att_refs;
+}
+
+VkResult VulkanContext::vkCreateRenderPass2KHR(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass) {
+ if (has_renderpass2_ext) {
+ if (fpCreateRenderPass2KHR == nullptr) {
+ fpCreateRenderPass2KHR = (PFN_vkCreateRenderPass2KHR)vkGetDeviceProcAddr(p_device, "vkCreateRenderPass2KHR");
+ }
+
+ if (fpCreateRenderPass2KHR == nullptr) {
+ return VK_ERROR_EXTENSION_NOT_PRESENT;
+ } else {
+ return (fpCreateRenderPass2KHR)(p_device, p_create_info, p_allocator, p_render_pass);
+ }
} else {
- return (fpCreateRenderPass2KHR)(p_device, p_create_info, p_allocator, p_render_pass);
+ // need to fall back on vkCreateRenderPass
+
+ const void *next = p_create_info->pNext; // ATM we only support multiview which should work if supported.
+
+ Vector<VkAttachmentDescription> attachments;
+ for (uint32_t i = 0; i < p_create_info->attachmentCount; i++) {
+ // Basically the old layout just misses type and next.
+ VkAttachmentDescription att = {
+ p_create_info->pAttachments[i].flags, /* flags */
+ p_create_info->pAttachments[i].format, /* format */
+ p_create_info->pAttachments[i].samples, /* samples */
+ p_create_info->pAttachments[i].loadOp, /* loadOp */
+ p_create_info->pAttachments[i].storeOp, /* storeOp */
+ p_create_info->pAttachments[i].stencilLoadOp, /* stencilLoadOp */
+ p_create_info->pAttachments[i].stencilStoreOp, /* stencilStoreOp */
+ p_create_info->pAttachments[i].initialLayout, /* initialLayout */
+ p_create_info->pAttachments[i].finalLayout /* finalLayout */
+ };
+
+ attachments.push_back(att);
+ }
+
+ Vector<VkSubpassDescription> subpasses;
+ for (uint32_t i = 0; i < p_create_info->subpassCount; i++) {
+ // Here we need to do more, again it's just stripping out type and next
+ // but we have VkAttachmentReference2 to convert to VkAttachmentReference.
+ // Also viewmask is not supported but we don't use it outside of multiview.
+
+ Vector<VkAttachmentReference> input_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].inputAttachmentCount, p_create_info->pSubpasses[i].pInputAttachments);
+ Vector<VkAttachmentReference> color_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pColorAttachments);
+ Vector<VkAttachmentReference> resolve_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pResolveAttachments);
+ Vector<VkAttachmentReference> depth_attachments = _convert_VkAttachmentReference2(p_create_info->pSubpasses[i].colorAttachmentCount, p_create_info->pSubpasses[i].pDepthStencilAttachment);
+
+ VkSubpassDescription subpass = {
+ p_create_info->pSubpasses[i].flags, /* flags */
+ p_create_info->pSubpasses[i].pipelineBindPoint, /* pipelineBindPoint */
+ p_create_info->pSubpasses[i].inputAttachmentCount, /* inputAttachmentCount */
+ input_attachments.size() == 0 ? nullptr : input_attachments.ptr(), /* pInputAttachments */
+ p_create_info->pSubpasses[i].colorAttachmentCount, /* colorAttachmentCount */
+ color_attachments.size() == 0 ? nullptr : color_attachments.ptr(), /* pColorAttachments */
+ resolve_attachments.size() == 0 ? nullptr : resolve_attachments.ptr(), /* pResolveAttachments */
+ depth_attachments.size() == 0 ? nullptr : depth_attachments.ptr(), /* pDepthStencilAttachment */
+ p_create_info->pSubpasses[i].preserveAttachmentCount, /* preserveAttachmentCount */
+ p_create_info->pSubpasses[i].pPreserveAttachments /* pPreserveAttachments */
+ };
+
+ subpasses.push_back(subpass);
+ }
+
+ Vector<VkSubpassDependency> dependencies;
+ for (uint32_t i = 0; i < p_create_info->dependencyCount; i++) {
+ // We lose viewOffset here but again I don't believe we use this anywhere.
+ VkSubpassDependency dep = {
+ p_create_info->pDependencies[i].srcSubpass, /* srcSubpass */
+ p_create_info->pDependencies[i].dstSubpass, /* dstSubpass */
+ p_create_info->pDependencies[i].srcStageMask, /* srcStageMask */
+ p_create_info->pDependencies[i].dstStageMask, /* dstStageMask */
+ p_create_info->pDependencies[i].srcAccessMask, /* srcAccessMask */
+ p_create_info->pDependencies[i].dstAccessMask, /* dstAccessMask */
+ p_create_info->pDependencies[i].dependencyFlags, /* dependencyFlags */
+ };
+
+ dependencies.push_back(dep);
+ }
+
+ // CorrelatedViewMask is not supported in vkCreateRenderPass but we
+ // currently only use this for multiview.
+ // We'll need to look into this.
+
+ VkRenderPassCreateInfo create_info = {
+ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, /* sType */
+ next, /* pNext*/
+ p_create_info->flags, /* flags */
+ (uint32_t)attachments.size(), /* attachmentCount */
+ attachments.ptr(), /* pAttachments */
+ (uint32_t)subpasses.size(), /* subpassCount */
+ subpasses.ptr(), /* pSubpasses */
+ (uint32_t)dependencies.size(), /* */
+ dependencies.ptr(), /* */
+ };
+
+ return vkCreateRenderPass(device, &create_info, p_allocator, p_render_pass);
}
}
@@ -613,9 +717,12 @@ Error VulkanContext::_check_capabilities() {
VkPhysicalDeviceProperties2 physicalDeviceProperties{};
void *nextptr = nullptr;
- subgroupProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES;
- subgroupProperties.pNext = nextptr;
- nextptr = &subgroupProperties;
+ if (!(vulkan_major == 1 && vulkan_minor == 0)) {
+ subgroupProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES;
+ subgroupProperties.pNext = nextptr;
+
+ nextptr = &subgroupProperties;
+ }
if (multiview_capabilities.is_supported) {
multiviewProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES;
@@ -1060,6 +1167,7 @@ Error VulkanContext::_create_physical_device(VkSurfaceKHR p_surface) {
extension_names[enabled_extension_count++] = VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME;
}
if (!strcmp(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME, device_extensions[i].extensionName)) {
+ has_renderpass2_ext = true;
extension_names[enabled_extension_count++] = VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME;
}
if (enabled_extension_count >= MAX_EXTENSIONS) {
@@ -1702,18 +1810,22 @@ Error VulkanContext::_update_swap_chain(Window *window) {
preTransform = surfCapabilities.currentTransform;
}
- // Find a supported composite alpha mode - one of these is guaranteed to be set.
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
- VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
- VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
- VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
- VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
- VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
- };
- for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
- if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
- compositeAlpha = compositeAlphaFlags[i];
- break;
+
+ if (OS::get_singleton()->is_layered_allowed() || !(surfCapabilities.supportedCompositeAlpha & compositeAlpha)) {
+ // Find a supported composite alpha mode - one of these is guaranteed to be set.
+ VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
+ VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
+ VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
+ VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
+ VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
+ };
+
+ for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
+ if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
+ compositeAlpha = compositeAlphaFlags[i];
+ break;
+ }
}
}
diff --git a/drivers/vulkan/vulkan_context.h b/drivers/vulkan/vulkan_context.h
index 7389e86ad7..b47aec1de1 100644
--- a/drivers/vulkan/vulkan_context.h
+++ b/drivers/vulkan/vulkan_context.h
@@ -188,6 +188,7 @@ private:
uint32_t enabled_extension_count = 0;
const char *extension_names[MAX_EXTENSIONS];
bool enabled_debug_utils = false;
+ bool has_renderpass2_ext = false;
/**
* True if VK_EXT_debug_report extension is used. VK_EXT_debug_report is deprecated but it is
@@ -257,6 +258,8 @@ private:
Error _create_swap_chain();
Error _create_semaphores();
+ Vector<VkAttachmentReference> _convert_VkAttachmentReference2(uint32_t p_count, const VkAttachmentReference2 *p_refs);
+
protected:
virtual const char *_get_platform_surface_extension() const = 0;
diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp
index fb90b776cf..d6636606d2 100644
--- a/drivers/wasapi/audio_driver_wasapi.cpp
+++ b/drivers/wasapi/audio_driver_wasapi.cpp
@@ -127,6 +127,11 @@ static bool default_capture_device_changed = false;
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#endif
+#if defined(__GNUC__)
+// Workaround GCC warning from -Wcast-function-type.
+#define GetProcAddress (void *)GetProcAddress
+#endif
+
class CMMNotificationClient : public IMMNotificationClient {
LONG _cRef = 1;
IMMDeviceEnumerator *_pEnumerator = nullptr;
@@ -201,6 +206,20 @@ public:
static CMMNotificationClient notif_client;
+typedef const char *(CDECL *PWineGetVersionPtr)(void);
+
+bool AudioDriverWASAPI::is_running_on_wine() {
+ HMODULE nt_lib = LoadLibraryW(L"ntdll.dll");
+ if (!nt_lib) {
+ return false;
+ }
+
+ PWineGetVersionPtr wine_get_version = (PWineGetVersionPtr)GetProcAddress(nt_lib, "wine_get_version");
+ FreeLibrary(nt_lib);
+
+ return (bool)wine_get_version;
+}
+
Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_capture, bool reinit) {
WAVEFORMATEX *pwfex;
IMMDeviceEnumerator *enumerator = nullptr;
@@ -285,6 +304,10 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c
}
using_audio_client_3 = !p_capture; // IID_IAudioClient3 is only used for adjustable output latency (not input)
+ if (using_audio_client_3 && is_running_on_wine()) {
+ using_audio_client_3 = false;
+ print_verbose("WASAPI: Wine detected, falling back to IAudioClient interface");
+ }
if (using_audio_client_3) {
hr = device->Activate(IID_IAudioClient3, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);
if (hr != S_OK) {
diff --git a/drivers/wasapi/audio_driver_wasapi.h b/drivers/wasapi/audio_driver_wasapi.h
index c30a54c042..e9f2794e97 100644
--- a/drivers/wasapi/audio_driver_wasapi.h
+++ b/drivers/wasapi/audio_driver_wasapi.h
@@ -79,6 +79,8 @@ class AudioDriverWASAPI : public AudioDriver {
SafeFlag exit_thread;
+ static bool is_running_on_wine();
+
static _FORCE_INLINE_ void write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample);
static _FORCE_INLINE_ int32_t read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i);
static void thread_func(void *p_udata);
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 5c4ef35f1c..8a2d23d32d 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -6204,7 +6204,7 @@ void AnimationTrackEditor::_edit_menu_pressed(int p_option) {
if (do_bake && !animation->track_is_compressed(i)) {
Animation::InterpolationType it = animation->track_get_interpolation_type(i);
if (it == Animation::INTERPOLATION_NEAREST) {
- continue; // Nearest and Angle interpolation cannot be baked.
+ continue; // Nearest interpolation cannot be baked.
}
// Special case for angle interpolation.
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index b73b49a434..e328f76545 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -230,6 +230,14 @@ void FindReplaceBar::_replace_all() {
Point2i prev_match = Point2(-1, -1);
bool selection_enabled = text_editor->has_selection(0);
+ if (!is_selection_only()) {
+ text_editor->deselect();
+ selection_enabled = false;
+ } else {
+ result_line = -1;
+ result_col = -1;
+ }
+
Point2i selection_begin, selection_end;
if (selection_enabled) {
selection_begin = Point2i(text_editor->get_selection_from_line(0), text_editor->get_selection_from_column(0));
@@ -238,9 +246,6 @@ void FindReplaceBar::_replace_all() {
int vsval = text_editor->get_v_scroll();
- text_editor->set_caret_line(0, false, true, 0, 0);
- text_editor->set_caret_column(0, true, 0);
-
String repl_text = get_replace_text();
int search_text_len = get_search_text().length();
@@ -253,7 +258,11 @@ void FindReplaceBar::_replace_all() {
if (selection_enabled && is_selection_only()) {
text_editor->set_caret_line(selection_begin.width, false, true, 0, 0);
text_editor->set_caret_column(selection_begin.height, true, 0);
+ } else {
+ text_editor->set_caret_line(0, false, true, 0, 0);
+ text_editor->set_caret_column(0, true, 0);
}
+
if (search_current()) {
do {
// replace area
@@ -269,7 +278,7 @@ void FindReplaceBar::_replace_all() {
text_editor->unfold_line(result_line);
text_editor->select(result_line, result_col, result_line, match_to.y, 0);
- if (selection_enabled && is_selection_only()) {
+ if (selection_enabled) {
if (match_from < selection_begin || match_to > selection_end) {
break; // Done.
}
@@ -297,11 +306,9 @@ void FindReplaceBar::_replace_all() {
text_editor->set_caret_line(orig_cursor.x, false, true, 0, 0);
text_editor->set_caret_column(orig_cursor.y, true, 0);
- if (selection_enabled && is_selection_only()) {
+ if (selection_enabled) {
// Reselect.
text_editor->select(selection_begin.x, selection_begin.y, selection_end.x, selection_end.y, 0);
- } else {
- text_editor->deselect(0);
}
text_editor->set_v_scroll(vsval);
@@ -314,21 +321,28 @@ void FindReplaceBar::_replace_all() {
needs_to_count_results = true;
}
-void FindReplaceBar::_get_search_from(int &r_line, int &r_col) {
- r_line = text_editor->get_caret_line(0);
- r_col = text_editor->get_caret_column(0);
+void FindReplaceBar::_get_search_from(int &r_line, int &r_col, bool p_is_searching_next) {
+ if (!text_editor->has_selection(0) || is_selection_only()) {
+ r_line = text_editor->get_caret_line(0);
+ r_col = text_editor->get_caret_column(0);
- if (text_editor->has_selection(0) && is_selection_only()) {
+ if (!p_is_searching_next && r_line == result_line && r_col >= result_col && r_col <= result_col + get_search_text().length()) {
+ r_col = result_col;
+ }
return;
}
- if (r_line == result_line && r_col >= result_col && r_col <= result_col + get_search_text().length()) {
- r_col = result_col;
+ if (p_is_searching_next) {
+ r_line = text_editor->get_selection_to_line();
+ r_col = text_editor->get_selection_to_column();
+ } else {
+ r_line = text_editor->get_selection_from_line();
+ r_col = text_editor->get_selection_from_column();
}
}
void FindReplaceBar::_update_results_count() {
- if (!needs_to_count_results && (result_line != -1)) {
+ if (!needs_to_count_results && (result_line != -1) && results_count_to_current > 0) {
results_count_to_current += (flags & TextEdit::SEARCH_BACKWARDS) ? -1 : 1;
if (results_count_to_current > results_count) {
@@ -340,9 +354,6 @@ void FindReplaceBar::_update_results_count() {
return;
}
- results_count = 0;
- results_count_to_current = 0;
-
String searched = get_search_text();
if (searched.is_empty()) {
return;
@@ -350,6 +361,8 @@ void FindReplaceBar::_update_results_count() {
needs_to_count_results = false;
+ results_count = 0;
+
for (int i = 0; i < text_editor->get_line_count(); i++) {
String line_text = text_editor->get_line(i);
@@ -373,8 +386,13 @@ void FindReplaceBar::_update_results_count() {
results_count++;
- if (i == result_line && col_pos == result_col) {
- results_count_to_current = results_count;
+ if (i == result_line) {
+ if (col_pos == result_col) {
+ results_count_to_current = results_count;
+ } else if (col_pos < result_col && col_pos + searched.length() > result_col) {
+ col_pos = result_col;
+ results_count_to_current = results_count;
+ }
}
col_pos += searched.length();
@@ -392,10 +410,10 @@ void FindReplaceBar::_update_matches_label() {
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 if (results_count_to_current == -1) {
+ matches_label->set_text(vformat(TTRN("%d match", "%d matches", results_count), results_count));
} else {
- matches_label->set_text(vformat(TTR("%d of %d matches"), results_count_to_current, results_count));
+ matches_label->set_text(vformat(TTRN("%d of %d match", "%d of %d matches", results_count), results_count_to_current, results_count));
}
}
}
@@ -417,6 +435,10 @@ bool FindReplaceBar::search_current() {
}
bool FindReplaceBar::search_prev() {
+ if (is_selection_only() && !replace_all_mode) {
+ return false;
+ }
+
if (!is_visible()) {
popup_search(true);
}
@@ -435,9 +457,6 @@ bool FindReplaceBar::search_prev() {
int line, col;
_get_search_from(line, col);
- if (text_editor->has_selection(0)) {
- col--; // Skip currently selected word.
- }
col -= text.length();
if (col < 0) {
@@ -452,17 +471,15 @@ bool FindReplaceBar::search_prev() {
}
bool FindReplaceBar::search_next() {
+ if (is_selection_only() && !replace_all_mode) {
+ return false;
+ }
+
if (!is_visible()) {
popup_search(true);
}
flags = 0;
- String text;
- if (replace_all_mode) {
- text = get_replace_text();
- } else {
- text = get_search_text();
- }
if (is_whole_words()) {
flags |= TextEdit::SEARCH_WHOLE_WORDS;
@@ -472,18 +489,7 @@ bool FindReplaceBar::search_next() {
}
int line, col;
- _get_search_from(line, col);
-
- if (line == result_line && col == result_col) {
- col += text.length();
- if (col > text_editor->get_line(line).length()) {
- line += 1;
- if (line >= text_editor->get_line_count()) {
- line = 0;
- }
- col = 0;
- }
- }
+ _get_search_from(line, col, true);
return _search(flags, line, col);
}
@@ -513,8 +519,10 @@ void FindReplaceBar::_show_search(bool p_focus_replace, bool p_show_only) {
search_text->call_deferred(SNAME("grab_focus"));
}
- if (text_editor->has_selection(0) && !selection_only->is_pressed()) {
+ if (text_editor->has_selection(0) && !is_selection_only()) {
search_text->set_text(text_editor->get_selected_text(0));
+ result_line = text_editor->get_selection_from_line();
+ result_col = text_editor->get_selection_from_column();
}
if (!get_search_text().is_empty()) {
@@ -538,6 +546,7 @@ void FindReplaceBar::popup_search(bool p_show_only) {
replace_text->hide();
hbc_button_replace->hide();
hbc_option_replace->hide();
+ selection_only->set_pressed(false);
_show_search(false, p_show_only);
}
diff --git a/editor/code_editor.h b/editor/code_editor.h
index c3279e8764..ded7518287 100644
--- a/editor/code_editor.h
+++ b/editor/code_editor.h
@@ -92,7 +92,7 @@ class FindReplaceBar : public HBoxContainer {
bool replace_all_mode = false;
bool preserve_cursor = false;
- void _get_search_from(int &r_line, int &r_col);
+ void _get_search_from(int &r_line, int &r_col, bool p_is_searching_next = false);
void _update_results_count();
void _update_matches_label();
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index 258ce434f6..de7f5c8b88 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -37,6 +37,7 @@
#include "editor/editor_undo_redo_manager.h"
#include "editor/scene_tree_dock.h"
#include "plugins/script_editor_plugin.h"
+#include "scene/resources/packed_scene.h"
static Node *_find_first_script(Node *p_root, Node *p_node) {
if (p_node != p_root && p_node->get_owner() != p_root) {
@@ -160,6 +161,9 @@ void ConnectDialog::_tree_node_selected() {
}
dst_path = source->get_path_to(current);
+ if (!edit_mode) {
+ set_dst_method(generate_method_callback_name(source, signal, current));
+ }
_update_ok_enabled();
}
@@ -205,6 +209,45 @@ void ConnectDialog::_remove_bind() {
cdbinds->params.remove_at(idx);
cdbinds->notify_changed();
}
+/*
+ * Automatically generates a name for the callback method.
+ */
+StringName ConnectDialog::generate_method_callback_name(Node *p_source, String p_signal_name, Node *p_target) {
+ String node_name = p_source->get_name();
+ for (int i = 0; i < node_name.length(); i++) { // TODO: Regex filter may be cleaner.
+ char32_t c = node_name[i];
+ if (!is_ascii_identifier_char(c)) {
+ if (c == ' ') {
+ // Replace spaces with underlines.
+ c = '_';
+ } else {
+ // Remove any other characters.
+ node_name.remove_at(i);
+ i--;
+ continue;
+ }
+ }
+ node_name[i] = c;
+ }
+
+ Dictionary subst;
+ subst["NodeName"] = node_name.to_pascal_case();
+ subst["nodeName"] = node_name.to_camel_case();
+ subst["node_name"] = node_name.to_snake_case();
+
+ subst["SignalName"] = p_signal_name.to_pascal_case();
+ subst["signalName"] = p_signal_name.to_camel_case();
+ subst["signal_name"] = p_signal_name.to_snake_case();
+
+ String dst_method;
+ if (p_source == p_target) {
+ dst_method = String(EDITOR_GET("interface/editors/default_signal_callback_to_self_name")).format(subst);
+ } else {
+ dst_method = String(EDITOR_GET("interface/editors/default_signal_callback_name")).format(subst);
+ }
+
+ return dst_method;
+}
/*
* Enables or disables the connect button. The connect button is enabled if a
@@ -371,6 +414,7 @@ void ConnectDialog::popup_dialog(const String &p_for_signal) {
first_popup = false;
_advanced_pressed();
}
+
popup_centered();
}
@@ -690,9 +734,11 @@ void ConnectionsDock::_disconnect_all() {
while (child) {
Connection connection = child->get_metadata(0);
- ConnectDialog::ConnectionData cd = connection;
- undo_redo->add_do_method(selected_node, "disconnect", cd.signal, cd.get_callable());
- undo_redo->add_undo_method(selected_node, "connect", cd.signal, cd.get_callable(), cd.binds, cd.flags);
+ if (!_is_connection_inherited(connection)) {
+ ConnectDialog::ConnectionData cd = connection;
+ undo_redo->add_do_method(selected_node, "disconnect", cd.signal, cd.get_callable());
+ undo_redo->add_undo_method(selected_node, "connect", cd.signal, cd.get_callable(), cd.binds, cd.flags);
+ }
child = child->get_next();
}
@@ -737,49 +783,43 @@ bool ConnectionsDock::_is_item_signal(TreeItem &p_item) {
return (p_item.get_parent() == tree->get_root() || p_item.get_parent()->get_parent() == tree->get_root());
}
+bool ConnectionsDock::_is_connection_inherited(Connection &p_connection) {
+ Node *scene_root = EditorNode::get_singleton()->get_edited_scene();
+ Ref<PackedScene> scn = ResourceLoader::load(scene_root->get_scene_file_path());
+ ERR_FAIL_NULL_V(scn, false);
+
+ Ref<SceneState> state = scn->get_state();
+ ERR_FAIL_NULL_V(state, false);
+
+ Node *source = Object::cast_to<Node>(p_connection.signal.get_object());
+ Node *target = Object::cast_to<Node>(p_connection.callable.get_object());
+
+ const NodePath source_path = scene_root->get_path_to(source);
+ const NodePath target_path = scene_root->get_path_to(target);
+ const StringName signal_name = p_connection.signal.get_name();
+ const StringName method_name = p_connection.callable.get_method();
+
+ // If it cannot be found in PackedScene, this connection was inherited.
+ return !state->has_connection(source_path, signal_name, target_path, method_name, true);
+}
+
/*
* Open connection dialog with TreeItem data to CREATE a brand-new connection.
*/
void ConnectionsDock::_open_connection_dialog(TreeItem &p_item) {
String signal_name = p_item.get_metadata(0).operator Dictionary()["name"];
const String &signal_name_ref = signal_name;
- String node_name = selected_node->get_name();
- for (int i = 0; i < node_name.length(); i++) { // TODO: Regex filter may be cleaner.
- char32_t c = node_name[i];
- if (!is_ascii_identifier_char(c)) {
- if (c == ' ') {
- // Replace spaces with underlines.
- c = '_';
- } else {
- // Remove any other characters.
- node_name.remove_at(i);
- i--;
- continue;
- }
- }
- node_name[i] = c;
- }
Node *dst_node = selected_node->get_owner() ? selected_node->get_owner() : selected_node;
if (!dst_node || dst_node->get_script().is_null()) {
dst_node = _find_first_script(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root());
}
- Dictionary subst;
- subst["NodeName"] = node_name.to_pascal_case();
- subst["nodeName"] = node_name.to_camel_case();
- subst["node_name"] = node_name.to_snake_case();
- subst["SignalName"] = signal_name.to_pascal_case();
- subst["signalName"] = signal_name.to_camel_case();
- subst["signal_name"] = signal_name.to_snake_case();
-
- String dst_method = String(EDITOR_GET("interface/editors/default_signal_callback_name")).format(subst);
-
ConnectDialog::ConnectionData cd;
cd.source = selected_node;
cd.signal = StringName(signal_name_ref);
cd.target = dst_node;
- cd.method = StringName(dst_method);
+ cd.method = ConnectDialog::generate_method_callback_name(cd.source, signal_name, cd.target);
connect_dialog->popup_dialog(signal_name_ref);
connect_dialog->init(cd);
connect_dialog->set_title(TTR("Connect a Signal to a Method"));
@@ -849,6 +889,19 @@ void ConnectionsDock::_handle_signal_menu_option(int p_option) {
}
}
+void ConnectionsDock::_signal_menu_about_to_popup() {
+ TreeItem *signal_item = tree->get_selected();
+
+ bool disable_disconnect_all = true;
+ for (int i = 0; i < signal_item->get_child_count(); i++) {
+ if (!signal_item->get_child(i)->has_meta("_inherited_connection")) {
+ disable_disconnect_all = false;
+ }
+ }
+
+ signal_menu->set_item_disabled(slot_menu->get_item_index(DISCONNECT_ALL), disable_disconnect_all);
+}
+
void ConnectionsDock::_handle_slot_menu_option(int p_option) {
TreeItem *item = tree->get_selected();
@@ -871,6 +924,13 @@ void ConnectionsDock::_handle_slot_menu_option(int p_option) {
}
}
+void ConnectionsDock::_slot_menu_about_to_popup() {
+ bool connection_is_inherited = tree->get_selected()->has_meta("_inherited_connection");
+
+ slot_menu->set_item_disabled(slot_menu->get_item_index(EDIT), connection_is_inherited);
+ slot_menu->set_item_disabled(slot_menu->get_item_index(DISCONNECT), connection_is_inherited);
+}
+
void ConnectionsDock::_rmb_pressed(Vector2 p_position, MouseButton p_button) {
if (p_button != MouseButton::RIGHT) {
return;
@@ -984,7 +1044,7 @@ void ConnectionsDock::update_tree() {
name = base;
}
- if (!icon.is_valid()) {
+ if (icon.is_null()) {
icon = get_theme_icon(SNAME("Object"), SNAME("EditorIcons"));
}
@@ -1116,6 +1176,12 @@ void ConnectionsDock::update_tree() {
connection_item->set_text(0, path);
connection_item->set_metadata(0, connection);
connection_item->set_icon(0, get_theme_icon(SNAME("Slot"), SNAME("EditorIcons")));
+
+ if (_is_connection_inherited(connection)) {
+ // The scene inherits this connection.
+ connection_item->set_custom_color(0, get_theme_color(SNAME("warning_color"), SNAME("Editor")));
+ connection_item->set_meta("_inherited_connection", true);
+ }
}
}
@@ -1168,6 +1234,7 @@ ConnectionsDock::ConnectionsDock() {
signal_menu = memnew(PopupMenu);
add_child(signal_menu);
signal_menu->connect("id_pressed", callable_mp(this, &ConnectionsDock::_handle_signal_menu_option));
+ signal_menu->connect("about_to_popup", callable_mp(this, &ConnectionsDock::_signal_menu_about_to_popup));
signal_menu->add_item(TTR("Connect..."), CONNECT);
signal_menu->add_item(TTR("Disconnect All"), DISCONNECT_ALL);
signal_menu->add_item(TTR("Copy Name"), COPY_NAME);
@@ -1175,6 +1242,7 @@ ConnectionsDock::ConnectionsDock() {
slot_menu = memnew(PopupMenu);
add_child(slot_menu);
slot_menu->connect("id_pressed", callable_mp(this, &ConnectionsDock::_handle_slot_menu_option));
+ slot_menu->connect("about_to_popup", callable_mp(this, &ConnectionsDock::_slot_menu_about_to_popup));
slot_menu->add_item(TTR("Edit..."), EDIT);
slot_menu->add_item(TTR("Go to Method"), GO_TO_SCRIPT);
slot_menu->add_item(TTR("Disconnect"), DISCONNECT);
@@ -1187,6 +1255,7 @@ ConnectionsDock::ConnectionsDock() {
add_theme_constant_override("separation", 3 * EDSCALE);
EDITOR_DEF("interface/editors/default_signal_callback_name", "_on_{node_name}_{signal_name}");
+ EDITOR_DEF("interface/editors/default_signal_callback_to_self_name", "_on_{signal_name}");
}
ConnectionsDock::~ConnectionsDock() {
diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h
index db2f855617..126a0ca828 100644
--- a/editor/connections_dialog.h
+++ b/editor/connections_dialog.h
@@ -144,6 +144,7 @@ protected:
static void _bind_methods();
public:
+ static StringName generate_method_callback_name(Node *p_source, String p_signal_name, Node *p_target);
Node *get_source() const;
StringName get_signal_name() const;
NodePath get_dst_path() const;
@@ -211,13 +212,16 @@ class ConnectionsDock : public VBoxContainer {
void _tree_item_selected();
void _tree_item_activated();
bool _is_item_signal(TreeItem &p_item);
+ bool _is_connection_inherited(Connection &p_connection);
void _open_connection_dialog(TreeItem &p_item);
void _open_connection_dialog(ConnectDialog::ConnectionData p_cd);
void _go_to_script(TreeItem &p_item);
void _handle_signal_menu_option(int p_option);
+ void _signal_menu_about_to_popup();
void _handle_slot_menu_option(int p_option);
+ void _slot_menu_about_to_popup();
void _rmb_pressed(Vector2 p_position, MouseButton p_button);
void _close();
diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp
index ceca428306..7a4e58c6f9 100644
--- a/editor/create_dialog.cpp
+++ b/editor/create_dialog.cpp
@@ -752,9 +752,7 @@ CreateDialog::CreateDialog() {
favorites->connect("cell_selected", callable_mp(this, &CreateDialog::_favorite_selected));
favorites->connect("item_activated", callable_mp(this, &CreateDialog::_favorite_activated));
favorites->add_theme_constant_override("draw_guides", 1);
-#ifndef _MSC_VER
-#warning cannot forward drag data to a non control, must be fixed
-#endif
+ // Cannot forward drag data to a non control, must be fixed.
//favorites->set_drag_forwarding(this);
fav_vb->add_margin_child(TTR("Favorites:"), favorites, true);
diff --git a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
index 809c0c2cff..ae8752eb6d 100644
--- a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
+++ b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
@@ -656,7 +656,7 @@ int DebugAdapterProtocol::parse_variant(const Variant &p_var) {
bool DebugAdapterProtocol::process_message(const String &p_text) {
JSON json;
- ERR_FAIL_COND_V_MSG(json.parse(p_text) != OK, true, "Mal-formed message!");
+ ERR_FAIL_COND_V_MSG(json.parse(p_text) != OK, true, "Malformed message!");
Dictionary params = json.get_data();
bool completed = true;
diff --git a/editor/debugger/editor_profiler.cpp b/editor/debugger/editor_profiler.cpp
index a882275375..dfa2b8e70f 100644
--- a/editor/debugger/editor_profiler.cpp
+++ b/editor/debugger/editor_profiler.cpp
@@ -308,9 +308,7 @@ void EditorProfiler::_update_plot() {
}
}
- Ref<Image> img;
- img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGBA8, graph_image);
+ Ref<Image> img = Image::create_from_data(w, h, false, Image::FORMAT_RGBA8, graph_image);
if (reset_texture) {
if (graph_texture.is_null()) {
diff --git a/editor/debugger/editor_visual_profiler.cpp b/editor/debugger/editor_visual_profiler.cpp
index 8e7135f1c5..8552c8e9ef 100644
--- a/editor/debugger/editor_visual_profiler.cpp
+++ b/editor/debugger/editor_visual_profiler.cpp
@@ -298,9 +298,7 @@ void EditorVisualProfiler::_update_plot() {
}
}
- Ref<Image> img;
- img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGBA8, graph_image);
+ Ref<Image> img = Image::create_from_data(w, h, false, Image::FORMAT_RGBA8, graph_image);
if (reset_texture) {
if (graph_texture.is_null()) {
diff --git a/editor/editor_build_profile.cpp b/editor/editor_build_profile.cpp
index 0f0ab4a339..7fd27692b0 100644
--- a/editor/editor_build_profile.cpp
+++ b/editor/editor_build_profile.cpp
@@ -255,8 +255,7 @@ Error EditorBuildProfile::save_to_file(const String &p_path) {
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'.");
- JSON json;
- String text = json.stringify(data, "\t");
+ String text = JSON::stringify(data, "\t");
f->store_string(text);
return OK;
}
diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index 6f34c677db..c28bb18891 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -2259,7 +2259,7 @@ void EditorFileSystem::move_group_file(const String &p_path, const String &p_new
ResourceUID::ID EditorFileSystem::_resource_saver_get_resource_id_for_path(const String &p_path, bool p_generate) {
if (!p_path.is_resource_file() || p_path.begins_with(ProjectSettings::get_singleton()->get_project_data_path())) {
- //saved externally (configuration file) or internal file, do not assign an ID.
+ // Saved externally (configuration file) or internal file, do not assign an ID.
return ResourceUID::INVALID_ID;
}
@@ -2267,15 +2267,21 @@ ResourceUID::ID EditorFileSystem::_resource_saver_get_resource_id_for_path(const
int cpos = -1;
if (!singleton->_find_file(p_path, &fs, cpos)) {
+ // Fallback to ResourceLoader if filesystem cache fails (can happen during scanning etc.).
+ ResourceUID::ID fallback = ResourceLoader::get_resource_uid(p_path);
+ if (fallback != ResourceUID::INVALID_ID) {
+ return fallback;
+ }
+
if (p_generate) {
- return ResourceUID::get_singleton()->create_id(); //just create a new one, we will be notified of save anyway and fetch the right UUID at that time, to keep things simple.
+ return ResourceUID::get_singleton()->create_id(); // Just create a new one, we will be notified of save anyway and fetch the right UUID at that time, to keep things simple.
} else {
return ResourceUID::INVALID_ID;
}
} else if (fs->files[cpos]->uid != ResourceUID::INVALID_ID) {
return fs->files[cpos]->uid;
} else if (p_generate) {
- return ResourceUID::get_singleton()->create_id(); //just create a new one, we will be notified of save anyway and fetch the right UUID at that time, to keep things simple.
+ return ResourceUID::get_singleton()->create_id(); // Just create a new one, we will be notified of save anyway and fetch the right UUID at that time, to keep things simple.
} else {
return ResourceUID::INVALID_ID;
}
@@ -2422,7 +2428,7 @@ EditorFileSystem::EditorFileSystem() {
scan_total = 0;
update_script_classes_queued.clear();
- ResourceUID::get_singleton()->clear(); //will be updated on scan
+ MessageQueue::get_singleton()->push_callable(callable_mp(ResourceUID::get_singleton(), &ResourceUID::clear)); // Will be updated on scan.
ResourceSaver::set_get_resource_id_for_path(_resource_saver_get_resource_id_for_path);
}
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 288ee4fa8f..8ee82888f3 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -1181,7 +1181,8 @@ void EditorNode::_vp_resized() {
}
void EditorNode::_titlebar_resized() {
- const Size2 &margin = DisplayServer::get_singleton()->window_get_safe_title_margins(DisplayServer::MAIN_WINDOW_ID);
+ DisplayServer::get_singleton()->window_set_window_buttons_offset(Vector2i(menu_hb->get_global_position().y + menu_hb->get_size().y / 2, menu_hb->get_global_position().y + menu_hb->get_size().y / 2), DisplayServer::MAIN_WINDOW_ID);
+ const Vector3i &margin = DisplayServer::get_singleton()->window_get_safe_title_margins(DisplayServer::MAIN_WINDOW_ID);
if (left_menu_spacer) {
int w = (gui_base->is_layout_rtl()) ? margin.y : margin.x;
left_menu_spacer->set_custom_minimum_size(Size2(w, 0));
@@ -1190,6 +1191,9 @@ void EditorNode::_titlebar_resized() {
int w = (gui_base->is_layout_rtl()) ? margin.x : margin.y;
right_menu_spacer->set_custom_minimum_size(Size2(w, 0));
}
+ if (menu_hb) {
+ menu_hb->set_custom_minimum_size(Size2(0, margin.z - menu_hb->get_global_position().y));
+ }
}
void EditorNode::_version_button_pressed() {
@@ -1614,7 +1618,7 @@ void EditorNode::_save_scene_with_preview(String p_file, int p_idx) {
// which would result in an invalid texture.
if (c3d == 0 && c2d == 0) {
img.instantiate();
- img->create(1, 1, false, Image::FORMAT_RGB8);
+ img->initialize_data(1, 1, false, Image::FORMAT_RGB8);
} else if (c3d < c2d) {
Ref<ViewportTexture> viewport_texture = scene_root->get_texture();
if (viewport_texture->get_width() > 0 && viewport_texture->get_height() > 0) {
@@ -5905,7 +5909,7 @@ void EditorNode::_update_renderer_color() {
if (renderer->get_text() == "gl_compatibility") {
renderer->add_theme_color_override("font_color", Color::hex(0x5586a4ff));
} else if (renderer->get_text() == "forward_plus" || renderer->get_text() == "mobile") {
- renderer->add_theme_color_override("font_color", theme_base->get_theme_color(SNAME("vulkan_color"), SNAME("Editor")));
+ renderer->add_theme_color_override("font_color", theme_base->get_theme_color(SNAME("highend_color"), SNAME("Editor")));
}
}
@@ -6177,10 +6181,17 @@ EditorNode::EditorNode() {
// Define a minimum window size to prevent UI elements from overlapping or being cut off.
DisplayServer::get_singleton()->window_set_min_size(Size2(1024, 600) * EDSCALE);
- ResourceLoader::set_abort_on_missing_resources(false);
FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
EditorFileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EditorSettings::get_singleton()->get("filesystem/file_dialog/display_mode").operator int());
+
+ int swap_cancel_ok = EDITOR_GET("interface/editor/accept_dialog_cancel_ok_buttons");
+ if (swap_cancel_ok != 0) { // 0 is auto, set in register_scene based on DisplayServer.
+ // Swap on means OK first.
+ AcceptDialog::set_swap_cancel_ok(swap_cancel_ok == 2);
+ }
+
+ ResourceLoader::set_abort_on_missing_resources(false);
ResourceLoader::set_error_notify_func(this, _load_error_notify);
ResourceLoader::set_dependency_error_notify_func(this, _dependency_error_report);
@@ -7560,7 +7571,6 @@ EditorNode::EditorNode() {
// Extend menu bar to window title.
if (can_expand) {
- DisplayServer::get_singleton()->window_set_window_buttons_offset(Vector2i(menu_hb->get_minimum_size().y / 2, menu_hb->get_minimum_size().y / 2), DisplayServer::MAIN_WINDOW_ID);
DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE, true, DisplayServer::MAIN_WINDOW_ID);
menu_hb->set_can_move_window(true);
}
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index 155802d16c..899fa69be1 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -90,7 +90,9 @@ void EditorPropertyText::update_property() {
String s = get_edited_object()->get(get_edited_property());
updating = true;
if (text->get_text() != s) {
+ int caret = text->get_caret_column();
text->set_text(s);
+ text->set_caret_column(caret);
}
text->set_editable(!is_read_only());
updating = false;
@@ -760,8 +762,13 @@ void EditorPropertyEnum::_option_selected(int p_which) {
}
void EditorPropertyEnum::update_property() {
- int64_t which = get_edited_object()->get(get_edited_property());
+ Variant current = get_edited_object()->get(get_edited_property());
+ if (current.get_type() == Variant::NIL) {
+ options->select(-1);
+ return;
+ }
+ int64_t which = current;
for (int i = 0; i < options->get_item_count(); i++) {
if (which == (int64_t)options->get_item_metadata(i)) {
options->select(i);
diff --git a/editor/editor_properties_array_dict.cpp b/editor/editor_properties_array_dict.cpp
index d98ad117d7..7cc42f4d24 100644
--- a/editor/editor_properties_array_dict.cpp
+++ b/editor/editor_properties_array_dict.cpp
@@ -510,7 +510,7 @@ void EditorPropertyArray::_notification(int p_what) {
change_type->add_separator();
change_type->add_icon_item(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), TTR("Remove Item"), Variant::VARIANT_MAX);
- if (Object::cast_to<Button>(button_add_item)) {
+ if (button_add_item) {
button_add_item->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
} break;
@@ -1205,7 +1205,7 @@ void EditorPropertyDictionary::_notification(int p_what) {
change_type->add_separator();
change_type->add_icon_item(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), TTR("Remove Item"), Variant::VARIANT_MAX);
- if (Object::cast_to<Button>(button_add_item)) {
+ if (button_add_item) {
button_add_item->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
} break;
@@ -1431,7 +1431,7 @@ void EditorPropertyLocalizableString::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_THEME_CHANGED:
case NOTIFICATION_ENTER_TREE: {
- if (Object::cast_to<Button>(button_add_item)) {
+ if (button_add_item) {
button_add_item->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
} break;
diff --git a/editor/editor_resource_picker.cpp b/editor/editor_resource_picker.cpp
index 01816b7205..5545dc4ee2 100644
--- a/editor/editor_resource_picker.cpp
+++ b/editor/editor_resource_picker.cpp
@@ -958,6 +958,7 @@ EditorResourcePicker::EditorResourcePicker(bool p_hide_assign_button_controls) {
preview_rect->set_offset(SIDE_TOP, 1);
preview_rect->set_offset(SIDE_BOTTOM, -1);
preview_rect->set_offset(SIDE_RIGHT, -1);
+ preview_rect->set_texture_filter(TEXTURE_FILTER_NEAREST_WITH_MIPMAPS);
assign_button->add_child(preview_rect);
}
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index 0c01fcb869..5bdfd8d377 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -438,6 +438,9 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
EDITOR_SETTING_USAGE(Variant::BOOL, PROPERTY_HINT_NONE, "interface/editor/single_window_mode", false, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED)
_initial_set("interface/editor/mouse_extra_buttons_navigate_history", true);
_initial_set("interface/editor/save_each_scene_on_quit", true); // Regression
+ EDITOR_SETTING_USAGE(Variant::INT, PROPERTY_HINT_ENUM, "interface/editor/accept_dialog_cancel_ok_buttons", 0,
+ vformat("Auto (%s),Cancel First,OK First", DisplayServer::get_singleton()->get_swap_cancel_ok() ? "OK First" : "Cancel First"),
+ PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
#ifdef DEV_ENABLED
EDITOR_SETTING(Variant::INT, PROPERTY_HINT_ENUM, "interface/editor/show_internal_errors_in_toast_notifications", 0, "Auto (Enabled),Enabled,Disabled")
#else
diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp
index 5edb6d877c..1cdfceebc8 100644
--- a/editor/editor_spin_slider.cpp
+++ b/editor/editor_spin_slider.cpp
@@ -143,7 +143,7 @@ void EditorSpinSlider::gui_input(const Ref<InputEvent> &p_event) {
}
Ref<InputEventKey> k = p_event;
- if (k.is_valid() && k->is_pressed() && k->is_action("ui_accept")) {
+ if (k.is_valid() && k->is_pressed() && k->is_action("ui_accept", true)) {
_focus_entered();
}
}
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 27ac57216a..1d9e320be1 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -564,9 +564,9 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
theme->set_color("readonly_color", "Editor", readonly_color);
if (!dark_theme) {
- theme->set_color("vulkan_color", "Editor", Color::hex(0xad1128ff));
+ theme->set_color("highend_color", "Editor", Color::hex(0xad1128ff));
} else {
- theme->set_color("vulkan_color", "Editor", Color(1.0, 0.0, 0.0));
+ theme->set_color("highend_color", "Editor", Color(1.0, 0.0, 0.0));
}
const int thumb_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
theme->set_constant("scale", "Editor", EDSCALE);
diff --git a/editor/editor_zoom_widget.cpp b/editor/editor_zoom_widget.cpp
index 88e99d9b30..8e820f41ee 100644
--- a/editor/editor_zoom_widget.cpp
+++ b/editor/editor_zoom_widget.cpp
@@ -161,13 +161,19 @@ void EditorZoomWidget::_bind_methods() {
ADD_SIGNAL(MethodInfo("zoom_changed", PropertyInfo(Variant::FLOAT, "zoom")));
}
+void EditorZoomWidget::set_shortcut_context(Node *p_node) const {
+ zoom_minus->set_shortcut_context(p_node);
+ zoom_plus->set_shortcut_context(p_node);
+ zoom_reset->set_shortcut_context(p_node);
+}
+
EditorZoomWidget::EditorZoomWidget() {
// Zoom buttons
zoom_minus = memnew(Button);
zoom_minus->set_flat(true);
add_child(zoom_minus);
zoom_minus->connect("pressed", callable_mp(this, &EditorZoomWidget::_button_zoom_minus));
- zoom_minus->set_shortcut(ED_SHORTCUT("canvas_item_editor/zoom_minus", TTR("Zoom Out"), KeyModifierMask::CMD_OR_CTRL | Key::MINUS));
+ zoom_minus->set_shortcut(ED_SHORTCUT_ARRAY("canvas_item_editor/zoom_minus", TTR("Zoom Out"), { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::MINUS), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_SUBTRACT) }));
zoom_minus->set_shortcut_context(this);
zoom_minus->set_focus_mode(FOCUS_NONE);
@@ -189,7 +195,7 @@ EditorZoomWidget::EditorZoomWidget() {
zoom_plus->set_flat(true);
add_child(zoom_plus);
zoom_plus->connect("pressed", callable_mp(this, &EditorZoomWidget::_button_zoom_plus));
- zoom_plus->set_shortcut(ED_SHORTCUT("canvas_item_editor/zoom_plus", TTR("Zoom In"), KeyModifierMask::CMD_OR_CTRL | Key::EQUAL)); // Usually direct access key for PLUS
+ zoom_plus->set_shortcut(ED_SHORTCUT_ARRAY("canvas_item_editor/zoom_plus", TTR("Zoom In"), { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::EQUAL), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_ADD) }));
zoom_plus->set_shortcut_context(this);
zoom_plus->set_focus_mode(FOCUS_NONE);
diff --git a/editor/editor_zoom_widget.h b/editor/editor_zoom_widget.h
index 4690a57a2b..995b9e1808 100644
--- a/editor/editor_zoom_widget.h
+++ b/editor/editor_zoom_widget.h
@@ -57,6 +57,8 @@ public:
float get_zoom();
void set_zoom(float p_zoom);
void set_zoom_by_increments(int p_increment_count, bool p_integer_only = false);
+ // Sets the shortcut context for the zoom buttons. By default their context is this EditorZoomWidget control.
+ void set_shortcut_context(Node *p_node) const;
};
#endif // EDITOR_ZOOM_WIDGET_H
diff --git a/editor/event_listener_line_edit.cpp b/editor/event_listener_line_edit.cpp
index 14e482432a..e4c35a5b81 100644
--- a/editor/event_listener_line_edit.cpp
+++ b/editor/event_listener_line_edit.cpp
@@ -59,8 +59,9 @@ void EventListenerLineEdit::gui_input(const Ref<InputEvent> &p_event) {
// First event will be an event which is used to focus this control - i.e. a mouse click, or a tab press.
// Ignore the first one so that clicking into the LineEdit does not override the current event.
// Ignore is reset to true when the control is unfocused.
- if (ignore) {
- ignore = false;
+ // This class also specially handles grab_focus() calls.
+ if (ignore_next_event) {
+ ignore_next_event = false;
return;
}
@@ -85,7 +86,7 @@ void EventListenerLineEdit::_on_focus() {
}
void EventListenerLineEdit::_on_unfocus() {
- ignore = true;
+ ignore_next_event = true;
set_placeholder(TTR("Filter by event..."));
}
@@ -109,6 +110,12 @@ int EventListenerLineEdit::get_allowed_input_types() const {
return allowed_input_types;
}
+void EventListenerLineEdit::grab_focus() {
+ // If we grab focus through code, we don't need to ignore the first event!
+ ignore_next_event = false;
+ Control::grab_focus();
+}
+
void EventListenerLineEdit::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
diff --git a/editor/event_listener_line_edit.h b/editor/event_listener_line_edit.h
index 5b415e8a2d..c4cd5e4511 100644
--- a/editor/event_listener_line_edit.h
+++ b/editor/event_listener_line_edit.h
@@ -44,7 +44,7 @@ class EventListenerLineEdit : public LineEdit {
GDCLASS(EventListenerLineEdit, LineEdit)
int allowed_input_types = INPUT_KEY | INPUT_MOUSE_BUTTON | INPUT_JOY_BUTTON | INPUT_JOY_MOTION;
- bool ignore = true;
+ bool ignore_next_event = true;
bool share_keycodes = false;
Ref<InputEvent> event;
@@ -67,6 +67,8 @@ public:
void set_allowed_input_types(int input_types);
int get_allowed_input_types() const;
+ void grab_focus();
+
public:
EventListenerLineEdit();
};
diff --git a/editor/export/editor_export_platform.h b/editor/export/editor_export_platform.h
index 88dc7bd5cd..5db79b98d1 100644
--- a/editor/export/editor_export_platform.h
+++ b/editor/export/editor_export_platform.h
@@ -144,6 +144,7 @@ public:
};
virtual Ref<EditorExportPreset> create_preset();
+ virtual bool is_executable(const String &p_path) const { return false; }
virtual void clear_messages() { messages.clear(); }
virtual void add_message(ExportMessageType p_type, const String &p_category, const String &p_message) {
diff --git a/editor/export/editor_export_platform_pc.cpp b/editor/export/editor_export_platform_pc.cpp
index 8538414523..c5b61e9b03 100644
--- a/editor/export/editor_export_platform_pc.cpp
+++ b/editor/export/editor_export_platform_pc.cpp
@@ -185,10 +185,12 @@ Error EditorExportPlatformPC::export_project_data(const Ref<EditorExportPreset>
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().path_join(src_path.get_file());
+ target_path = p_path.get_base_dir();
} else {
- target_path = p_path.get_base_dir().path_join(so_files[i].target).path_join(src_path.get_file());
+ target_path = p_path.get_base_dir().path_join(so_files[i].target);
+ da->make_dir_recursive(target_path);
}
+ target_path = target_path.path_join(src_path.get_file());
if (da->dir_exists(src_path)) {
err = da->make_dir_recursive(target_path);
diff --git a/editor/export/project_export.cpp b/editor/export/project_export.cpp
index 05a17c9951..9b5e76bcd7 100644
--- a/editor/export/project_export.cpp
+++ b/editor/export/project_export.cpp
@@ -1015,9 +1015,7 @@ ProjectExportDialog::ProjectExportDialog() {
preset_vb->add_child(mc);
mc->set_v_size_flags(Control::SIZE_EXPAND_FILL);
presets = memnew(ItemList);
-#ifndef _MSC_VER
-#warning must reimplement drag forward
-#endif
+ // TODO: Must reimplement drag forwarding.
//presets->set_drag_forwarding(this);
mc->add_child(presets);
presets->connect("item_selected", callable_mp(this, &ProjectExportDialog::_edit_preset));
diff --git a/editor/groups_editor.cpp b/editor/groups_editor.cpp
index dac86acae4..f11e328087 100644
--- a/editor/groups_editor.cpp
+++ b/editor/groups_editor.cpp
@@ -39,6 +39,24 @@
#include "scene/gui/label.h"
#include "scene/resources/packed_scene.h"
+static bool can_edit(Node *p_node, String p_group) {
+ Node *n = p_node;
+ bool can_edit = true;
+ while (n) {
+ Ref<SceneState> ss = (n == EditorNode::get_singleton()->get_edited_scene()) ? n->get_scene_inherited_state() : n->get_scene_instance_state();
+ if (ss.is_valid()) {
+ int path = ss->find_node_by_path(n->get_path_to(p_node));
+ if (path != -1) {
+ if (ss->is_node_in_group(path, p_group)) {
+ can_edit = false;
+ }
+ }
+ }
+ n = n->get_owner();
+ }
+ return can_edit;
+}
+
void GroupDialog::_group_selected() {
nodes_to_add->clear();
add_node_root = nodes_to_add->create_item();
@@ -94,7 +112,7 @@ void GroupDialog::_load_nodes(Node *p_current) {
Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(p_current, "Node");
node->set_icon(0, icon);
- if (!_can_edit(p_current, selected_group)) {
+ if (!can_edit(p_current, selected_group)) {
node->set_selectable(0, false);
node->set_custom_color(0, groups->get_theme_color(SNAME("disabled_font_color"), SNAME("Editor")));
}
@@ -105,24 +123,6 @@ void GroupDialog::_load_nodes(Node *p_current) {
}
}
-bool GroupDialog::_can_edit(Node *p_node, String p_group) {
- Node *n = p_node;
- bool can_edit = true;
- while (n) {
- Ref<SceneState> ss = (n == EditorNode::get_singleton()->get_edited_scene()) ? n->get_scene_inherited_state() : n->get_scene_instance_state();
- if (ss.is_valid()) {
- int path = ss->find_node_by_path(n->get_path_to(p_node));
- if (path != -1) {
- if (ss->is_node_in_group(path, p_group)) {
- can_edit = false;
- }
- }
- }
- n = n->get_owner();
- }
- return can_edit;
-}
-
void GroupDialog::_add_pressed() {
TreeItem *selected = nodes_to_add->get_next_selected(nullptr);
@@ -218,19 +218,14 @@ void GroupDialog::_add_group_text_changed(const String &p_new_text) {
}
void GroupDialog::_group_renamed() {
- TreeItem *renamed_group = groups->get_edited();
+ TreeItem *renamed_group = groups->get_selected();
if (!renamed_group) {
return;
}
const String name = renamed_group->get_text(0).strip_edges();
- for (TreeItem *E = groups_root->get_first_child(); E; E = E->get_next()) {
- if (E != renamed_group && E->get_text(0) == name) {
- renamed_group->set_text(0, selected_group);
- error->set_text(TTR("Group name already exists."));
- error->popup_centered();
- return;
- }
+ if (name == selected_group) {
+ return;
}
if (name.is_empty()) {
@@ -240,6 +235,15 @@ void GroupDialog::_group_renamed() {
return;
}
+ for (TreeItem *E = groups_root->get_first_child(); E; E = E->get_next()) {
+ if (E != renamed_group && E->get_text(0) == name) {
+ renamed_group->set_text(0, selected_group);
+ error->set_text(TTR("Group name already exists."));
+ error->popup_centered();
+ return;
+ }
+ }
+
renamed_group->set_text(0, name); // Spaces trimmed.
undo_redo->create_action(TTR("Rename Group"));
@@ -248,7 +252,7 @@ void GroupDialog::_group_renamed() {
scene_tree->get_nodes_in_group(selected_group, &nodes);
bool removed_all = true;
for (Node *node : nodes) {
- if (_can_edit(node, selected_group)) {
+ if (can_edit(node, selected_group)) {
undo_redo->add_do_method(node, "remove_from_group", selected_group);
undo_redo->add_undo_method(node, "remove_from_group", name);
undo_redo->add_do_method(node, "add_to_group", name, true);
@@ -324,7 +328,7 @@ void GroupDialog::_modify_group_pressed(Object *p_item, int p_column, int p_id,
scene_tree->get_nodes_in_group(name, &nodes);
bool removed_all = true;
for (Node *E : nodes) {
- if (_can_edit(E, name)) {
+ if (can_edit(E, name)) {
undo_redo->add_do_method(E, "remove_from_group", name);
undo_redo->add_undo_method(E, "add_to_group", name, true);
} else {
@@ -571,7 +575,7 @@ GroupDialog::GroupDialog() {
set_title(TTR("Group Editor"));
- error = memnew(ConfirmationDialog);
+ error = memnew(AcceptDialog);
add_child(error);
error->set_ok_button_text(TTR("Close"));
@@ -584,14 +588,12 @@ void GroupsEditor::_add_group(const String &p_group) {
if (!node) {
return;
}
-
const String name = group_name->get_text().strip_edges();
- if (name.is_empty()) {
- return;
- }
group_name->clear();
if (node->is_in_group(name)) {
+ error->set_text(TTR("Group name already exists."));
+ error->popup_centered();
return;
}
@@ -609,6 +611,65 @@ void GroupsEditor::_add_group(const String &p_group) {
undo_redo->commit_action();
}
+void GroupsEditor::_group_selected() {
+ if (!tree->is_anything_selected()) {
+ return;
+ }
+ selected_group = tree->get_selected()->get_text(0);
+}
+
+void GroupsEditor::_group_renamed() {
+ if (!node || !can_edit(node, selected_group)) {
+ return;
+ }
+
+ TreeItem *ti = tree->get_selected();
+ if (!ti) {
+ return;
+ }
+
+ const String name = ti->get_text(0).strip_edges();
+ if (name == selected_group) {
+ return;
+ }
+
+ if (name.is_empty()) {
+ ti->set_text(0, selected_group);
+ error->set_text(TTR("Invalid group name."));
+ error->popup_centered();
+ return;
+ }
+
+ for (TreeItem *E = groups_root->get_first_child(); E; E = E->get_next()) {
+ if (E != ti && E->get_text(0) == name) {
+ ti->set_text(0, selected_group);
+ error->set_text(TTR("Group name already exists."));
+ error->popup_centered();
+ return;
+ }
+ }
+
+ ti->set_text(0, name); // Spaces trimmed.
+
+ undo_redo->create_action(TTR("Rename Group"));
+
+ undo_redo->add_do_method(node, "remove_from_group", selected_group);
+ undo_redo->add_undo_method(node, "remove_from_group", name);
+ undo_redo->add_do_method(node, "add_to_group", name, true);
+ undo_redo->add_undo_method(node, "add_to_group", selected_group, true);
+
+ undo_redo->add_do_method(this, "_group_selected");
+ undo_redo->add_undo_method(this, "_group_selected");
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(this, "update_tree");
+
+ // To force redraw of scene tree.
+ undo_redo->add_do_method(SceneTreeDock::get_singleton()->get_tree_editor(), "update_tree");
+ undo_redo->add_undo_method(SceneTreeDock::get_singleton()->get_tree_editor(), "update_tree");
+
+ undo_redo->commit_action();
+}
+
void GroupsEditor::_modify_group(Object *p_item, int p_column, int p_id, MouseButton p_button) {
if (p_button != MouseButton::LEFT) {
return;
@@ -624,7 +685,7 @@ void GroupsEditor::_modify_group(Object *p_item, int p_column, int p_id, MouseBu
}
switch (p_id) {
case DELETE_GROUP: {
- String name = ti->get_text(0);
+ const String name = ti->get_text(0);
undo_redo->create_action(TTR("Remove from Group"));
undo_redo->add_do_method(node, "remove_from_group", name);
@@ -666,6 +727,7 @@ void GroupsEditor::update_tree() {
groups.sort_custom<_GroupInfoComparator>();
TreeItem *root = tree->create_item();
+ groups_root = root;
for (const GroupInfo &gi : groups) {
if (!gi.persistent) {
@@ -692,6 +754,7 @@ void GroupsEditor::update_tree() {
TreeItem *item = tree->create_item(root);
item->set_text(0, gi.name);
+ item->set_editable(0, true);
if (can_be_deleted) {
item->add_button(0, get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), DELETE_GROUP);
item->add_button(0, get_theme_icon(SNAME("ActionCopy"), SNAME("EditorIcons")), COPY_GROUP);
@@ -717,6 +780,7 @@ void GroupsEditor::_show_group_dialog() {
void GroupsEditor::_bind_methods() {
ClassDB::bind_method("update_tree", &GroupsEditor::update_tree);
+ ClassDB::bind_method("_group_selected", &GroupsEditor::_group_selected);
}
GroupsEditor::GroupsEditor() {
@@ -749,13 +813,21 @@ GroupsEditor::GroupsEditor() {
add->connect("pressed", callable_mp(this, &GroupsEditor::_add_group).bind(String()));
tree = memnew(Tree);
+ vbc->add_child(tree);
tree->set_hide_root(true);
+ tree->set_allow_reselect(true);
+ tree->set_allow_rmb_select(true);
tree->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- vbc->add_child(tree);
+ tree->connect("item_selected", callable_mp(this, &GroupsEditor::_group_selected));
tree->connect("button_clicked", callable_mp(this, &GroupsEditor::_modify_group));
+ tree->connect("item_edited", callable_mp(this, &GroupsEditor::_group_renamed));
tree->add_theme_constant_override("draw_guides", 1);
add_theme_constant_override("separation", 3 * EDSCALE);
+ error = memnew(AcceptDialog);
+ add_child(error);
+ error->get_ok_button()->set_text(TTR("Close"));
+
_group_name_changed("");
}
diff --git a/editor/groups_editor.h b/editor/groups_editor.h
index 8bbea4e652..5d012a3501 100644
--- a/editor/groups_editor.h
+++ b/editor/groups_editor.h
@@ -44,7 +44,7 @@ class EditorUndoRedoManager;
class GroupDialog : public AcceptDialog {
GDCLASS(GroupDialog, AcceptDialog);
- ConfirmationDialog *error = nullptr;
+ AcceptDialog *error = nullptr;
SceneTree *scene_tree = nullptr;
TreeItem *groups_root = nullptr;
@@ -88,8 +88,6 @@ class GroupDialog : public AcceptDialog {
void _modify_group_pressed(Object *p_item, int p_column, int p_id, MouseButton p_button);
void _delete_group_item(const String &p_name);
- bool _can_edit(Node *p_node, String p_group);
-
void _load_groups(Node *p_current);
void _load_nodes(Node *p_current);
@@ -113,8 +111,10 @@ class GroupsEditor : public VBoxContainer {
GDCLASS(GroupsEditor, VBoxContainer);
Node *node = nullptr;
+ TreeItem *groups_root = nullptr;
GroupDialog *group_dialog = nullptr;
+ AcceptDialog *error = nullptr;
LineEdit *group_name = nullptr;
Button *add = nullptr;
@@ -122,11 +122,16 @@ class GroupsEditor : public VBoxContainer {
Ref<EditorUndoRedoManager> undo_redo;
+ String selected_group;
+
void update_tree();
void _add_group(const String &p_group = "");
void _modify_group(Object *p_item, int p_column, int p_id, MouseButton p_button);
void _group_name_changed(const String &p_new_text);
+ void _group_selected();
+ void _group_renamed();
+
void _show_group_dialog();
protected:
diff --git a/editor/icons/BoneMapHumanBody.svg b/editor/icons/BoneMapHumanBody.svg
index 2c2c5db1f6..8674157aaa 100644
--- a/editor/icons/BoneMapHumanBody.svg
+++ b/editor/icons/BoneMapHumanBody.svg
@@ -1 +1,26 @@
-<svg enable-background="new 0 0 1024 1024" height="1024" viewBox="0 0 1024 1024" width="1024" xmlns="http://www.w3.org/2000/svg"><path d="m0 0h1024v1024h-1024z" fill="#3f3f3f"/><path d="m926.5 217.162c-11.5-2-26.03 4.547-37.5 6.5-15.723 2.678-25.238 3.24-33.333 5.167-1.227.292-3.103.763-5.792.958 0 0-.019.16-.052.437-36.819.994-106.823-6.062-138.156-2.062-23.816 3.041-86.334-5.667-105.667-6-13.911-.239-59.292-4.583-71.75-2.5-.667-4.083-1.5-10.75.95-17.468 14.881-7.246 27.229-21.569 35.341-38.467.922 4.424 6.252 4.929 12.459-14.231 5.662-17.478 2.324-22.254-2.313-22.525.172-2.056.279-4.105.313-6.142.788-48.041-15-78.667-69-78.667s-69.787 30.626-69 78.667c.033 2.036.141 4.086.313 6.142-4.637.271-7.975 5.048-2.313 22.525 6.207 19.16 11.537 18.655 12.459 14.231 8.113 16.897 20.461 31.221 35.342 38.467 2.449 6.718 1.617 13.385.949 17.468-12.457-2.083-57.838 2.261-71.75 2.5-19.332.333-81.85 9.041-105.666 6-31.333-4-101.337 3.056-138.156 2.062-.033-.276-.053-.437-.053-.437-2.689-.195-4.564-.666-5.791-.958-8.096-1.927-17.611-2.489-33.334-5.167-11.469-1.953-26-8.5-37.5-6.5-3.367.586 6 9.834 15.5 12.334 13.635 3.588 25.25 10.666 36 13.166-2.25 3.75-15.59 7.063-23 12-5.336 3.557 6.5 6.5 12 5 20.842-5.684 22.973.389 37.514-9.019 30.078 4.078 102.537 20.514 122.154 14.186 12.457-4.018 100.332 7.083 142.332 5.833 6.039-.18 1.656 65.563 2 73.5 3 69-16.842 133.135-18.666 169.667-1.92 38.42-3.42 57.919 7.666 131.333 6.967 46.126-2.521 82.079-2 94 6 137 29 172 4 221-14 27.44 67.449 26.958 65 9-3.012-22.092-12.666-22.333-10.666-46.333 1.896-22.768 16.049-151.298 8.666-206.667-2-15 0-26 2-66 2.355-47.101 7-88 14-123 7 35 11.645 75.899 14 123 2 40 4 51 2 66-7.383 55.369 6.77 183.899 8.667 206.667 2 24-7.654 24.241-10.667 46.333-2.449 17.958 79 18.44 65-9-25-49-2-84 4-221 .522-11.921-8.966-47.874-2-94 11.086-73.414 9.586-92.913 7.667-131.333-1.824-36.532-21.667-100.667-18.667-169.667.345-7.938-4.039-73.68 2-73.5 42 1.25 129.876-9.852 142.333-5.833 19.616 6.328 92.076-10.107 122.153-14.186 14.541 9.407 16.673 3.335 37.514 9.019 5.5 1.5 17.336-1.443 12-5-7.409-4.937-20.75-8.25-23-12 10.75-2.5 22.366-9.578 36.001-13.166 9.5-2.5 18.866-11.748 15.499-12.334z" fill="#b2b2b2"/></svg>
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 15.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
+ y="0px" width="1024px" height="1024px" viewBox="0 0 1024 1024" enable-background="new 0 0 1024 1024" xml:space="preserve">
+<path fill="#3F3F3F" d="M0,0h1024v1024H0V0z"/>
+<path fill="#B2B2B2" d="M512,536.162c7,35,11.645,66.898,14,114c2,40,4,51,2,66c-7.384,55.369,6.77,183.898,8.666,206.667
+ c2,24-7.653,24.241-10.666,46.333c-2.449,17.958,79,18.439,65-9c-25-49-2-84,4-221c0.521-11.921-8.967-47.874-2-94
+ c11.086-73.414,8.42-107.242,6.5-145.662c-1.245-31.973-1-56.963-9-138.963c-0.976-10.002,5.915-79.268,11.954-79.088
+ c42,1.25,97.313-5.009,118.145-14.68c28.901,3.73,97.81-12.047,127.887-16.126c14.541,9.407,16.673,3.335,37.515,9.019
+ c5.5,1.5,17.336-1.443,12-5c-7.409-4.937-20.75-8.25-23-12c10.75-2.5,22.365-9.578,36-13.166c9.5-2.5,18.866-11.748,15.5-12.334l0,0
+ c-11.5-2-26.03,4.547-37.5,6.5c-15.724,2.678-25.238,3.24-33.334,5.167c-1.227,0.292-3.103,0.763-5.791,0.958
+ c0,0-0.02,0.16-0.053,0.437c-36.818,0.994-80.322-9.724-130.31-5.569c-34.026-3.925-94.181-5.16-113.513-5.493
+ c-13.911-0.239-59.293-2.583-71.75-0.5c-0.668-4.083-1.5-9.75,0.949-16.468c14.881-7.246,19.188-17.796,27.301-34.694
+ c0.922,4.424,6.252,4.929,12.459-14.231c5.661-17.478,2.323-22.254-2.313-22.525c0.172-2.056,0.279-4.105,0.313-6.142
+ C573.746,76.562,566,42.163,512,42.163s-61.746,34.399-60.959,82.44c0.034,2.037,0.142,4.086,0.313,6.142
+ c-4.637,0.271-7.975,5.047-2.313,22.525c6.207,19.16,11.537,18.655,12.459,14.231c8.112,16.898,12.42,27.448,27.301,34.694
+ c2.449,6.718,1.617,12.385,0.949,16.468c-12.457-2.083-57.839,0.261-71.75,0.5c-19.332,0.333-79.486,1.568-113.513,5.493
+ c-49.987-4.155-93.491,6.563-130.31,5.569c-0.033-0.277-0.053-0.437-0.053-0.437c-2.688-0.195-4.564-0.666-5.791-0.958
+ c-8.096-1.927-17.61-2.489-33.334-5.167c-11.47-1.953-26-8.5-37.5-6.5l0,0c-3.366,0.586,6,9.834,15.5,12.334
+ c13.635,3.588,25.25,10.666,36,13.166c-2.25,3.75-15.591,7.063-23,12c-5.336,3.557,6.5,6.5,12,5
+ c20.842-5.684,22.974,0.388,37.515-9.019c30.077,4.079,98.985,19.857,127.887,16.126c20.832,9.671,76.145,15.93,118.145,14.68
+ c6.039-0.18,12.93,69.085,11.954,79.088c-8,82-7.755,106.99-9,138.963c-1.92,38.419-4.586,72.248,6.5,145.662
+ c6.967,46.126-2.521,82.079-2,94c6,137,29,172,4,221c-14,27.439,67.449,26.958,65,9c-3.013-22.092-12.666-22.333-10.666-46.333
+ c1.896-22.769,16.05-151.298,8.666-206.667c-2-15,0-26,2-66C500.356,603.061,505,571.162,512,536.162z"/>
+</svg>
diff --git a/editor/icons/Line.svg b/editor/icons/Line.svg
new file mode 100644
index 0000000000..c7b1f8a701
--- /dev/null
+++ b/editor/icons/Line.svg
@@ -0,0 +1 @@
+<svg height="12" viewBox="0 0 12 12" width="12" xmlns="http://www.w3.org/2000/svg"><path d="m2 1050.4 8-8" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-width="2" transform="translate(0 -1040.4)"/></svg>
diff --git a/editor/import/collada.cpp b/editor/import/collada.cpp
index 7cf35c519b..c54b10842f 100644
--- a/editor/import/collada.cpp
+++ b/editor/import/collada.cpp
@@ -848,6 +848,8 @@ void Collada::_parse_curve_geometry(XMLParser &parser, String p_id, String p_nam
CurveData &curvedata = state.curve_data_map[p_id];
curvedata.name = p_name;
+ String closed = parser.get_attribute_value_safe("closed").to_lower();
+ curvedata.closed = closed == "true" || closed == "1";
COLLADA_PRINT("curve name: " + p_name);
diff --git a/editor/import/editor_import_collada.cpp b/editor/import/editor_import_collada.cpp
index 8d44329022..6890a46193 100644
--- a/editor/import/editor_import_collada.cpp
+++ b/editor/import/editor_import_collada.cpp
@@ -1090,6 +1090,12 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres
c->set_point_tilt(i, tilts->array[i]);
}
}
+ if (cd.closed && pc > 1) {
+ Vector3 pos = c->get_point_position(0);
+ Vector3 in = c->get_point_in(0);
+ Vector3 out = c->get_point_out(0);
+ c->add_point(pos, in, out, -1);
+ }
curve_cache[ng->source] = c;
path->set_curve(c);
diff --git a/editor/import/resource_importer_layered_texture.cpp b/editor/import/resource_importer_layered_texture.cpp
index 9dafa47c1c..2acb3a6b4e 100644
--- a/editor/import/resource_importer_layered_texture.cpp
+++ b/editor/import/resource_importer_layered_texture.cpp
@@ -135,7 +135,7 @@ String ResourceImporterLayeredTexture::get_preset_name(int p_idx) const {
}
void ResourceImporterLayeredTexture::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Lossless (PNG),Lossy (WebP),Video RAM (S3TC/ETC/BPTC),Uncompressed,Basis Universal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Lossless,Lossy,VRAM Compressed,VRAM Uncompressed,Basis Universal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1));
r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "compress/lossy_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.7));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/hdr_compression", PROPERTY_HINT_ENUM, "Disabled,Opaque Only,Always"), 1));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/bptc_ldr", PROPERTY_HINT_ENUM, "Disabled,Enabled,RGBA Only"), 0));
@@ -186,9 +186,7 @@ void ResourceImporterLayeredTexture::_save_tex(Vector<Ref<Image>> p_images, cons
int mm_d = MAX(1, d >> 1);
for (int i = 0; i < mm_d; i++) {
- Ref<Image> mm;
- mm.instantiate();
- mm->create(mm_w, mm_h, false, p_images[0]->get_format());
+ Ref<Image> mm = Image::create_empty(mm_w, mm_h, false, p_images[0]->get_format());
Vector3 pos;
pos.z = float(i) * float(d) / float(mm_d) + 0.5;
for (int x = 0; x < mm_w; x++) {
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index b5798a5784..756d61f712 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -953,43 +953,49 @@ Node *ResourceImporterScene::_pre_fix_animations(Node *p_node, Node *p_root, con
if (Object::cast_to<AnimationPlayer>(p_node)) {
AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
+ List<StringName> anims;
+ ap->get_animation_list(&anims);
- Array animation_clips;
- {
- int clip_count = node_settings["clips/amount"];
+ for (const StringName &name : anims) {
+ Ref<Animation> anim = ap->get_animation(name);
+ Array animation_slices;
- for (int i = 0; i < clip_count; i++) {
- String name = node_settings["clip_" + itos(i + 1) + "/name"];
- int from_frame = node_settings["clip_" + itos(i + 1) + "/start_frame"];
- int end_frame = node_settings["clip_" + itos(i + 1) + "/end_frame"];
- Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)node_settings["clip_" + itos(i + 1) + "/loop_mode"]);
- bool save_to_file = node_settings["clip_" + itos(i + 1) + "/save_to_file/enabled"];
- bool save_to_path = node_settings["clip_" + itos(i + 1) + "/save_to_file/path"];
- bool save_to_file_keep_custom = node_settings["clip_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"];
+ if (p_animation_data.has(name)) {
+ Dictionary anim_settings = p_animation_data[name];
+ int slices_count = anim_settings["slices/amount"];
+
+ for (int i = 0; i < slices_count; i++) {
+ String slice_name = anim_settings["slice_" + itos(i + 1) + "/name"];
+ int from_frame = anim_settings["slice_" + itos(i + 1) + "/start_frame"];
+ int end_frame = anim_settings["slice_" + itos(i + 1) + "/end_frame"];
+ Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)anim_settings["slice_" + itos(i + 1) + "/loop_mode"]);
+ bool save_to_file = anim_settings["slice_" + itos(i + 1) + "/save_to_file/enabled"];
+ bool save_to_path = anim_settings["slice_" + itos(i + 1) + "/save_to_file/path"];
+ bool save_to_file_keep_custom = anim_settings["slice_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"];
+
+ animation_slices.push_back(slice_name);
+ animation_slices.push_back(from_frame / p_animation_fps);
+ animation_slices.push_back(end_frame / p_animation_fps);
+ animation_slices.push_back(loop_mode);
+ animation_slices.push_back(save_to_file);
+ animation_slices.push_back(save_to_path);
+ animation_slices.push_back(save_to_file_keep_custom);
+ }
+ }
- animation_clips.push_back(name);
- animation_clips.push_back(from_frame / p_animation_fps);
- animation_clips.push_back(end_frame / p_animation_fps);
- animation_clips.push_back(loop_mode);
- animation_clips.push_back(save_to_file);
- animation_clips.push_back(save_to_path);
- animation_clips.push_back(save_to_file_keep_custom);
+ if (animation_slices.size() > 0) {
+ _create_slices(ap, anim, animation_slices, true);
}
}
- if (animation_clips.size()) {
- _create_clips(ap, animation_clips, true);
- } else {
- List<StringName> anims;
- ap->get_animation_list(&anims);
- AnimationImportTracks import_tracks_mode[TRACK_CHANNEL_MAX] = {
- AnimationImportTracks(int(node_settings["import_tracks/position"])),
- AnimationImportTracks(int(node_settings["import_tracks/rotation"])),
- AnimationImportTracks(int(node_settings["import_tracks/scale"]))
- };
- if (anims.size() > 1 && (import_tracks_mode[0] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[1] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[2] != ANIMATION_IMPORT_TRACKS_IF_PRESENT)) {
- _optimize_track_usage(ap, import_tracks_mode);
- }
+ AnimationImportTracks import_tracks_mode[TRACK_CHANNEL_MAX] = {
+ AnimationImportTracks(int(node_settings["import_tracks/position"])),
+ AnimationImportTracks(int(node_settings["import_tracks/rotation"])),
+ AnimationImportTracks(int(node_settings["import_tracks/scale"]))
+ };
+
+ if (anims.size() > 1 && (import_tracks_mode[0] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[1] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[2] != ANIMATION_IMPORT_TRACKS_IF_PRESENT)) {
+ _optimize_track_usage(ap, import_tracks_mode);
}
}
@@ -1408,144 +1414,138 @@ Ref<Animation> ResourceImporterScene::_save_animation_to_file(Ref<Animation> ani
return anim;
}
-void ResourceImporterScene::_create_clips(AnimationPlayer *anim, const Array &p_clips, bool p_bake_all) {
- if (!anim->has_animation("default")) {
- ERR_FAIL_COND_MSG(p_clips.size() > 0, "To create clips, animations must be named \"default\".");
- return;
- }
+void ResourceImporterScene::_create_slices(AnimationPlayer *ap, Ref<Animation> anim, const Array &p_slices, bool p_bake_all) {
+ Ref<AnimationLibrary> al = ap->get_animation_library(ap->find_animation_library(anim));
- Ref<Animation> default_anim = anim->get_animation("default");
- Ref<AnimationLibrary> al = anim->get_animation_library(anim->find_animation(default_anim));
-
- for (int i = 0; i < p_clips.size(); i += 7) {
- String name = p_clips[i];
- float from = p_clips[i + 1];
- float to = p_clips[i + 2];
- Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)p_clips[i + 3]);
- bool save_to_file = p_clips[i + 4];
- String save_to_path = p_clips[i + 5];
- bool keep_current = p_clips[i + 6];
+ for (int i = 0; i < p_slices.size(); i += 7) {
+ String name = p_slices[i];
+ float from = p_slices[i + 1];
+ float to = p_slices[i + 2];
+ Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)p_slices[i + 3]);
+ bool save_to_file = p_slices[i + 4];
+ String save_to_path = p_slices[i + 5];
+ bool keep_current = p_slices[i + 6];
if (from >= to) {
continue;
}
Ref<Animation> new_anim = memnew(Animation);
- for (int j = 0; j < default_anim->get_track_count(); j++) {
+ for (int j = 0; j < anim->get_track_count(); j++) {
List<float> keys;
- int kc = default_anim->track_get_key_count(j);
+ int kc = anim->track_get_key_count(j);
int dtrack = -1;
for (int k = 0; k < kc; k++) {
- float kt = default_anim->track_get_key_time(j, k);
+ float kt = anim->track_get_key_time(j, k);
if (kt >= from && kt < to) {
//found a key within range, so create track
if (dtrack == -1) {
- new_anim->add_track(default_anim->track_get_type(j));
+ new_anim->add_track(anim->track_get_type(j));
dtrack = new_anim->get_track_count() - 1;
- new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
+ new_anim->track_set_path(dtrack, anim->track_get_path(j));
if (kt > (from + 0.01) && k > 0) {
- if (default_anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
+ if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
Vector3 p;
- default_anim->position_track_interpolate(j, from, &p);
+ anim->position_track_interpolate(j, from, &p);
new_anim->position_track_insert_key(dtrack, 0, p);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
Quaternion r;
- default_anim->rotation_track_interpolate(j, from, &r);
+ anim->rotation_track_interpolate(j, from, &r);
new_anim->rotation_track_insert_key(dtrack, 0, r);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
Vector3 s;
- default_anim->scale_track_interpolate(j, from, &s);
+ anim->scale_track_interpolate(j, from, &s);
new_anim->scale_track_insert_key(dtrack, 0, s);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
- Variant var = default_anim->value_track_interpolate(j, from);
+ } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
+ Variant var = anim->value_track_interpolate(j, from);
new_anim->track_insert_key(dtrack, 0, var);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
float interp;
- default_anim->blend_shape_track_interpolate(j, from, &interp);
+ anim->blend_shape_track_interpolate(j, from, &interp);
new_anim->blend_shape_track_insert_key(dtrack, 0, interp);
}
}
}
- if (default_anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
+ if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
Vector3 p;
- default_anim->position_track_get_key(j, k, &p);
+ anim->position_track_get_key(j, k, &p);
new_anim->position_track_insert_key(dtrack, kt - from, p);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
Quaternion r;
- default_anim->rotation_track_get_key(j, k, &r);
+ anim->rotation_track_get_key(j, k, &r);
new_anim->rotation_track_insert_key(dtrack, kt - from, r);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
Vector3 s;
- default_anim->scale_track_get_key(j, k, &s);
+ anim->scale_track_get_key(j, k, &s);
new_anim->scale_track_insert_key(dtrack, kt - from, s);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
- Variant var = default_anim->track_get_key_value(j, k);
+ } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
+ Variant var = anim->track_get_key_value(j, k);
new_anim->track_insert_key(dtrack, kt - from, var);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
float interp;
- default_anim->blend_shape_track_get_key(j, k, &interp);
+ anim->blend_shape_track_get_key(j, k, &interp);
new_anim->blend_shape_track_insert_key(dtrack, kt - from, interp);
}
}
if (dtrack != -1 && kt >= to) {
- if (default_anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
+ if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
Vector3 p;
- default_anim->position_track_interpolate(j, to, &p);
+ anim->position_track_interpolate(j, to, &p);
new_anim->position_track_insert_key(dtrack, to - from, p);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
Quaternion r;
- default_anim->rotation_track_interpolate(j, to, &r);
+ anim->rotation_track_interpolate(j, to, &r);
new_anim->rotation_track_insert_key(dtrack, to - from, r);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
Vector3 s;
- default_anim->scale_track_interpolate(j, to, &s);
+ anim->scale_track_interpolate(j, to, &s);
new_anim->scale_track_insert_key(dtrack, to - from, s);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
- Variant var = default_anim->value_track_interpolate(j, to);
+ } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
+ Variant var = anim->value_track_interpolate(j, to);
new_anim->track_insert_key(dtrack, to - from, var);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
float interp;
- default_anim->blend_shape_track_interpolate(j, to, &interp);
+ anim->blend_shape_track_interpolate(j, to, &interp);
new_anim->blend_shape_track_insert_key(dtrack, to - from, interp);
}
}
}
if (dtrack == -1 && p_bake_all) {
- new_anim->add_track(default_anim->track_get_type(j));
+ new_anim->add_track(anim->track_get_type(j));
dtrack = new_anim->get_track_count() - 1;
- new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
- if (default_anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
+ new_anim->track_set_path(dtrack, anim->track_get_path(j));
+ if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
Vector3 p;
- default_anim->position_track_interpolate(j, from, &p);
+ anim->position_track_interpolate(j, from, &p);
new_anim->position_track_insert_key(dtrack, 0, p);
- default_anim->position_track_interpolate(j, to, &p);
+ anim->position_track_interpolate(j, to, &p);
new_anim->position_track_insert_key(dtrack, to - from, p);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
Quaternion r;
- default_anim->rotation_track_interpolate(j, from, &r);
+ anim->rotation_track_interpolate(j, from, &r);
new_anim->rotation_track_insert_key(dtrack, 0, r);
- default_anim->rotation_track_interpolate(j, to, &r);
+ anim->rotation_track_interpolate(j, to, &r);
new_anim->rotation_track_insert_key(dtrack, to - from, r);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
Vector3 s;
- default_anim->scale_track_interpolate(j, from, &s);
+ anim->scale_track_interpolate(j, from, &s);
new_anim->scale_track_insert_key(dtrack, 0, s);
- default_anim->scale_track_interpolate(j, to, &s);
+ anim->scale_track_interpolate(j, to, &s);
new_anim->scale_track_insert_key(dtrack, to - from, s);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
- Variant var = default_anim->value_track_interpolate(j, from);
+ } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
+ Variant var = anim->value_track_interpolate(j, from);
new_anim->track_insert_key(dtrack, 0, var);
- Variant to_var = default_anim->value_track_interpolate(j, to);
+ Variant to_var = anim->value_track_interpolate(j, to);
new_anim->track_insert_key(dtrack, to - from, to_var);
- } else if (default_anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
+ } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
float interp;
- default_anim->blend_shape_track_interpolate(j, from, &interp);
+ anim->blend_shape_track_interpolate(j, from, &interp);
new_anim->blend_shape_track_insert_key(dtrack, 0, interp);
- default_anim->blend_shape_track_interpolate(j, to, &interp);
+ anim->blend_shape_track_interpolate(j, to, &interp);
new_anim->blend_shape_track_insert_key(dtrack, to - from, interp);
}
}
@@ -1562,7 +1562,7 @@ void ResourceImporterScene::_create_clips(AnimationPlayer *anim, const Array &p_
}
}
- al->remove_animation("default"); // Remove default (no longer needed).
+ al->remove_animation(ap->find_animation(anim)); // Remove original animation (no longer needed).
}
void ResourceImporterScene::_optimize_animations(AnimationPlayer *anim, float p_max_vel_error, float p_max_ang_error, int p_prc_error) {
@@ -1642,6 +1642,17 @@ void ResourceImporterScene::get_internal_import_options(InternalImportCategory p
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "save_to_file/path", PROPERTY_HINT_SAVE_FILE, "*.res,*.tres"), ""));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/keep_custom_tracks"), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slices/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
+
+ for (int i = 0; i < 256; i++) {
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/name"), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/start_frame"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/end_frame"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Pingpong"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/save_to_file/path", PROPERTY_HINT_SAVE_FILE, ".res,*.tres"), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"), false));
+ }
} break;
case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
@@ -1654,17 +1665,6 @@ void ResourceImporterScene::get_internal_import_options(InternalImportCategory p
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/position", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/rotation", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/scale", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slices/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
-
- for (int i = 0; i < 256; i++) {
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/name"), ""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/start_frame"), 0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/end_frame"), 0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Pingpong"), 0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/save_to_file/path", PROPERTY_HINT_SAVE_FILE, ".res,*.tres"), ""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"), false));
- }
} break;
case INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE: {
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
@@ -1767,6 +1767,13 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor
if (p_option == "save_to_file/path" || p_option == "save_to_file/keep_custom_tracks") {
return p_options["save_to_file/enabled"];
}
+ if (p_option.begins_with("slice_")) {
+ int max_slice = p_options["slices/amount"];
+ int slice = p_option.get_slice("_", 1).to_int() - 1;
+ if (slice >= max_slice) {
+ return false;
+ }
+ }
} break;
case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
if (p_option.begins_with("optimizer/") && p_option != "optimizer/enabled" && !bool(p_options["optimizer/enabled"])) {
@@ -1775,14 +1782,6 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor
if (p_option.begins_with("compression/") && p_option != "compression/enabled" && !bool(p_options["compression/enabled"])) {
return false;
}
-
- if (p_option.begins_with("slice_")) {
- int max_slice = p_options["slices/amount"];
- int slice = p_option.get_slice("_", 1).to_int() - 1;
- if (slice >= max_slice) {
- return false;
- }
- }
} break;
case INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE: {
const bool use_retarget = p_options["retarget/bone_map"].get_validated_object() != nullptr;
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index 386519bc59..5f64330453 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -283,7 +283,7 @@ public:
Node *_post_fix_animations(Node *p_node, Node *p_root, const Dictionary &p_node_data, const Dictionary &p_animation_data, float p_animation_fps);
Ref<Animation> _save_animation_to_file(Ref<Animation> anim, bool p_save_to_file, String p_save_to_path, bool p_keep_custom_tracks);
- void _create_clips(AnimationPlayer *anim, const Array &p_clips, bool p_bake_all);
+ void _create_slices(AnimationPlayer *ap, Ref<Animation> anim, const Array &p_clips, bool p_bake_all);
void _optimize_animations(AnimationPlayer *anim, float p_max_vel_error, float p_max_ang_error, int p_prc_error);
void _compress_animations(AnimationPlayer *anim, int p_page_size_kb);
@@ -474,7 +474,7 @@ Transform3D ResourceImporterScene::get_collision_shapes_transform(const M &p_opt
}
if (p_options.has(SNAME("primitive/rotation"))) {
- transform.basis.set_euler((p_options[SNAME("primitive/rotation")].operator Vector3() / 180.0) * Math_PI);
+ transform.basis = Basis::from_euler(p_options[SNAME("primitive/rotation")].operator Vector3() * (Math_PI / 180.0));
}
}
return transform;
diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp
index 73f1c0b39b..ed3f1ff489 100644
--- a/editor/import/resource_importer_texture.cpp
+++ b/editor/import/resource_importer_texture.cpp
@@ -233,7 +233,8 @@ void ResourceImporterTexture::get_import_options(const String &p_path, List<Impo
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));
- if (p_path.get_extension() == "svg") {
+ // Do path based customization only if a path was passed.
+ if (p_path.is_empty() || p_path.get_extension() == "svg") {
r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "svg/scale", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 1.0));
// Editor use only, applies to SVG.
diff --git a/editor/import/resource_importer_texture_atlas.cpp b/editor/import/resource_importer_texture_atlas.cpp
index 9171f04f42..bf22a9377e 100644
--- a/editor/import/resource_importer_texture_atlas.cpp
+++ b/editor/import/resource_importer_texture_atlas.cpp
@@ -273,9 +273,7 @@ Error ResourceImporterTextureAtlas::import_group_file(const String &p_group_file
EditorAtlasPacker::chart_pack(charts, atlas_width, atlas_height);
//blit the atlas
- Ref<Image> new_atlas;
- new_atlas.instantiate();
- new_atlas->create(atlas_width, atlas_height, false, Image::FORMAT_RGBA8);
+ Ref<Image> new_atlas = Image::create_empty(atlas_width, atlas_height, false, Image::FORMAT_RGBA8);
for (int i = 0; i < pack_data_files.size(); i++) {
PackData &pack_data = pack_data_files.write[i];
diff --git a/editor/input_event_configuration_dialog.cpp b/editor/input_event_configuration_dialog.cpp
index ed9a5898fb..c577c61db7 100644
--- a/editor/input_event_configuration_dialog.cpp
+++ b/editor/input_event_configuration_dialog.cpp
@@ -533,6 +533,10 @@ String InputEventConfigurationDialog::_get_device_string(int p_device) const {
void InputEventConfigurationDialog::_notification(int p_what) {
switch (p_what) {
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ event_listener->grab_focus();
+ } break;
+
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED: {
input_list_search->set_right_icon(input_list_search->get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index dc84c08506..b4737976d8 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -128,14 +128,11 @@ void AnimationPlayerEditor::_notification(int p_what) {
{
Ref<Image> autoplay_img = autoplay_icon->get_image();
Ref<Image> reset_img = reset_icon->get_image();
- Ref<Image> autoplay_reset_img;
Size2 icon_size = autoplay_img->get_size();
- autoplay_reset_img.instantiate();
- autoplay_reset_img->create(icon_size.x * 2, icon_size.y, false, autoplay_img->get_format());
+ Ref<Image> autoplay_reset_img = Image::create_empty(icon_size.x * 2, icon_size.y, false, autoplay_img->get_format());
autoplay_reset_img->blit_rect(autoplay_img, Rect2i(Point2i(), icon_size), Point2i());
autoplay_reset_img->blit_rect(reset_img, Rect2i(Point2i(), icon_size), Point2i(icon_size.x, 0));
- autoplay_reset_icon.instantiate();
- autoplay_reset_icon->set_image(autoplay_reset_img);
+ autoplay_reset_icon = ImageTexture::create_from_image(autoplay_reset_img);
}
stop->set_icon(get_theme_icon(SNAME("Stop"), SNAME("EditorIcons")));
@@ -302,6 +299,8 @@ void AnimationPlayerEditor::_animation_selected(int p_which) {
AnimationPlayerEditor::get_singleton()->get_track_editor()->update_keying();
_animation_key_editor_seek(timeline_position, false);
+
+ emit_signal("animation_selected", current);
}
void AnimationPlayerEditor::_animation_new() {
@@ -720,7 +719,18 @@ void AnimationPlayerEditor::set_state(const Dictionary &p_state) {
if (p_state.has("player")) {
Node *n = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["player"]);
if (Object::cast_to<AnimationPlayer>(n) && EditorNode::get_singleton()->get_editor_selection()->is_selected(n)) {
+ if (player) {
+ if (player->is_connected("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated))) {
+ player->disconnect("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated));
+ }
+ }
player = Object::cast_to<AnimationPlayer>(n);
+ if (player) {
+ if (!player->is_connected("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated))) {
+ player->connect("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated));
+ }
+ }
+
_update_player();
EditorNode::get_singleton()->make_bottom_panel_item_visible(this);
set_process(true);
@@ -982,9 +992,18 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
if (player && pin->is_pressed()) {
return; // Ignore, pinned.
}
+
+ if (player) {
+ if (player->is_connected("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated))) {
+ player->disconnect("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated));
+ }
+ }
player = p_player;
if (player) {
+ if (!player->is_connected("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated))) {
+ player->connect("animation_libraries_updated", callable_mp(this, &AnimationPlayerEditor::_animation_libraries_updated));
+ }
_update_player();
if (onion.enabled) {
@@ -1151,6 +1170,10 @@ void AnimationPlayerEditor::_animation_player_changed(Object *p_pl) {
}
}
+void AnimationPlayerEditor::_animation_libraries_updated() {
+ _animation_player_changed(player);
+}
+
void AnimationPlayerEditor::_list_changed() {
if (is_visible_in_tree()) {
_update_player();
@@ -1545,6 +1568,7 @@ void AnimationPlayerEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_animation_edit"), &AnimationPlayerEditor::_animation_edit);
ClassDB::bind_method(D_METHOD("_animation_resource_edit"), &AnimationPlayerEditor::_animation_resource_edit);
ClassDB::bind_method(D_METHOD("_animation_player_changed"), &AnimationPlayerEditor::_animation_player_changed);
+ ClassDB::bind_method(D_METHOD("_animation_libraries_updated"), &AnimationPlayerEditor::_animation_libraries_updated);
ClassDB::bind_method(D_METHOD("_list_changed"), &AnimationPlayerEditor::_list_changed);
ClassDB::bind_method(D_METHOD("_animation_duplicate"), &AnimationPlayerEditor::_animation_duplicate);
@@ -1552,6 +1576,8 @@ void AnimationPlayerEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_prepare_onion_layers_2"), &AnimationPlayerEditor::_prepare_onion_layers_2);
ClassDB::bind_method(D_METHOD("_start_onion_skinning"), &AnimationPlayerEditor::_start_onion_skinning);
ClassDB::bind_method(D_METHOD("_stop_onion_skinning"), &AnimationPlayerEditor::_stop_onion_skinning);
+
+ ADD_SIGNAL(MethodInfo("animation_selected", PropertyInfo(Variant::STRING, "name")));
}
AnimationPlayerEditor *AnimationPlayerEditor::singleton = nullptr;
diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h
index 448a0639b1..ae570e53f3 100644
--- a/editor/plugins/animation_player_editor_plugin.h
+++ b/editor/plugins/animation_player_editor_plugin.h
@@ -195,6 +195,7 @@ class AnimationPlayerEditor : public VBoxContainer {
void _blend_edited();
void _animation_player_changed(Object *p_pl);
+ void _animation_libraries_updated();
void _animation_key_editor_seek(float p_pos, bool p_drag, bool p_timeline_only = false);
void _animation_key_editor_anim_len_changed(float p_len);
diff --git a/editor/plugins/bone_map_editor_plugin.h b/editor/plugins/bone_map_editor_plugin.h
index 55261ab477..16e5403978 100644
--- a/editor/plugins/bone_map_editor_plugin.h
+++ b/editor/plugins/bone_map_editor_plugin.h
@@ -206,7 +206,6 @@ class BoneMapEditor : public VBoxContainer {
BoneMapper *bone_mapper = nullptr;
void fetch_objects();
- void clear_editors();
void create_editors();
protected:
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 6e108a9a72..fe33a91a41 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -5060,6 +5060,7 @@ CanvasItemEditor::CanvasItemEditor() {
zoom_widget = memnew(EditorZoomWidget);
controls_vb->add_child(zoom_widget);
zoom_widget->set_anchors_and_offsets_preset(Control::PRESET_TOP_LEFT, Control::PRESET_MODE_MINSIZE, 2 * EDSCALE);
+ zoom_widget->set_shortcut_context(this);
zoom_widget->connect("zoom_changed", callable_mp(this, &CanvasItemEditor::_update_zoom));
panner.instantiate();
@@ -5316,7 +5317,7 @@ CanvasItemEditor::CanvasItemEditor() {
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/frame_selection", TTR("Frame Selection"), KeyModifierMask::SHIFT | Key::F), VIEW_FRAME_TO_SELECTION);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/clear_guides", TTR("Clear Guides")), CLEAR_GUIDES);
p->add_separator();
- p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/preview_canvas_scale", TTR("Preview Canvas Scale"), KeyModifierMask::SHIFT | KeyModifierMask::CMD_OR_CTRL | Key::P), PREVIEW_CANVAS_SCALE);
+ p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/preview_canvas_scale", TTR("Preview Canvas Scale")), PREVIEW_CANVAS_SCALE);
main_menu_hbox->add_child(memnew(VSeparator));
@@ -5454,6 +5455,15 @@ void CanvasItemEditorPlugin::set_state(const Dictionary &p_state) {
canvas_item_editor->set_state(p_state);
}
+void CanvasItemEditorPlugin::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ connect("scene_changed", callable_mp((CanvasItem *)canvas_item_editor->get_viewport_control(), &CanvasItem::queue_redraw).unbind(1));
+ connect("scene_closed", callable_mp((CanvasItem *)canvas_item_editor->get_viewport_control(), &CanvasItem::queue_redraw).unbind(1));
+ } break;
+ }
+}
+
CanvasItemEditorPlugin::CanvasItemEditorPlugin() {
canvas_item_editor = memnew(CanvasItemEditor);
canvas_item_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h
index b731d3cc7d..3ade048e4b 100644
--- a/editor/plugins/canvas_item_editor_plugin.h
+++ b/editor/plugins/canvas_item_editor_plugin.h
@@ -563,6 +563,9 @@ class CanvasItemEditorPlugin : public EditorPlugin {
CanvasItemEditor *canvas_item_editor = nullptr;
+protected:
+ void _notification(int p_what);
+
public:
virtual String get_name() const override { return "2D"; }
bool has_main_screen() const override { return true; }
diff --git a/editor/plugins/curve_editor_plugin.cpp b/editor/plugins/curve_editor_plugin.cpp
index 8d1df0b32c..434e6a92e3 100644
--- a/editor/plugins/curve_editor_plugin.cpp
+++ b/editor/plugins/curve_editor_plugin.cpp
@@ -805,7 +805,7 @@ Ref<Texture2D> CurvePreviewGenerator::generate(const Ref<Resource> &p_from, cons
img_ref.instantiate();
Image &im = **img_ref;
- im.create(thumbnail_size, thumbnail_size / 2, false, Image::FORMAT_RGBA8);
+ im.initialize_data(thumbnail_size, thumbnail_size / 2, false, Image::FORMAT_RGBA8);
Color bg_color(0.1, 0.1, 0.1, 1.0);
diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp
index 59b8f31720..836f76ac4f 100644
--- a/editor/plugins/editor_preview_plugins.cpp
+++ b/editor/plugins/editor_preview_plugins.cpp
@@ -210,9 +210,7 @@ Ref<Texture2D> EditorBitmapPreviewPlugin::generate(const Ref<Resource> &p_from,
}
}
- Ref<Image> img;
- img.instantiate();
- img->create(bm->get_size().width, bm->get_size().height, false, Image::FORMAT_L8, data);
+ Ref<Image> img = Image::create_from_data(bm->get_size().width, bm->get_size().height, false, Image::FORMAT_L8, data);
if (img->is_compressed()) {
if (img->decompress() != OK) {
@@ -483,10 +481,8 @@ Ref<Texture2D> EditorScriptPreviewPlugin::generate(const Ref<Resource> &p_from,
int line = 0;
int col = 0;
- Ref<Image> img;
- img.instantiate();
int thumbnail_size = MAX(p_size.x, p_size.y);
- img->create(thumbnail_size, thumbnail_size, false, Image::FORMAT_RGBA8);
+ Ref<Image> img = Image::create_empty(thumbnail_size, thumbnail_size, false, Image::FORMAT_RGBA8);
Color bg_color = EditorSettings::get_singleton()->get("text_editor/theme/highlighting/background_color");
Color keyword_color = EditorSettings::get_singleton()->get("text_editor/theme/highlighting/keyword_color");
@@ -660,9 +656,7 @@ Ref<Texture2D> EditorAudioStreamPreviewPlugin::generate(const Ref<Resource> &p_f
//post_process_preview(img);
- Ref<Image> image;
- image.instantiate();
- image->create(w, h, false, Image::FORMAT_RGB8, img);
+ Ref<Image> image = Image::create_from_data(w, h, false, Image::FORMAT_RGB8, img);
return ImageTexture::create_from_image(image);
}
diff --git a/editor/plugins/font_config_plugin.cpp b/editor/plugins/font_config_plugin.cpp
index ba11479714..58256ae549 100644
--- a/editor/plugins/font_config_plugin.cpp
+++ b/editor/plugins/font_config_plugin.cpp
@@ -154,7 +154,7 @@ void EditorPropertyFontMetaOverride::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED: {
- if (Object::cast_to<Button>(button_add)) {
+ if (button_add) {
button_add->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
} break;
@@ -549,7 +549,7 @@ void EditorPropertyOTFeatures::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED: {
- if (Object::cast_to<Button>(button_add)) {
+ if (button_add) {
button_add->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
} break;
diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.cpp b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
index 1b2afe2151..891b9efa4f 100644
--- a/editor/plugins/gpu_particles_2d_editor_plugin.cpp
+++ b/editor/plugins/gpu_particles_2d_editor_plugin.cpp
@@ -299,7 +299,7 @@ void GPUParticles2DEditorPlugin::_generate_emission_mask() {
}
img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGF, texdata);
+ img->set_data(w, h, false, Image::FORMAT_RGF, texdata);
pm->set_emission_point_texture(ImageTexture::create_from_image(img));
pm->set_emission_point_count(vpc);
@@ -315,7 +315,7 @@ void GPUParticles2DEditorPlugin::_generate_emission_mask() {
}
img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGBA8, colordata);
+ img->set_data(w, h, false, Image::FORMAT_RGBA8, colordata);
pm->set_emission_color_texture(ImageTexture::create_from_image(img));
}
@@ -335,7 +335,7 @@ void GPUParticles2DEditorPlugin::_generate_emission_mask() {
}
img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGF, normdata);
+ img->set_data(w, h, false, Image::FORMAT_RGF, normdata);
pm->set_emission_normal_texture(ImageTexture::create_from_image(img));
} else {
diff --git a/editor/plugins/node_3d_editor_gizmos.cpp b/editor/plugins/node_3d_editor_gizmos.cpp
index 7194cd9d27..26af5e3f2d 100644
--- a/editor/plugins/node_3d_editor_gizmos.cpp
+++ b/editor/plugins/node_3d_editor_gizmos.cpp
@@ -4751,9 +4751,9 @@ void CollisionShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
if (err == OK) {
Vector<Vector3> points2;
points2.resize(md.edges.size() * 2);
- for (int i = 0; i < md.edges.size(); i++) {
- points2.write[i * 2 + 0] = md.vertices[md.edges[i].a];
- points2.write[i * 2 + 1] = md.vertices[md.edges[i].b];
+ for (uint32_t i = 0; i < md.edges.size(); i++) {
+ points2.write[i * 2 + 0] = md.vertices[md.edges[i].vertex_a];
+ points2.write[i * 2 + 1] = md.vertices[md.edges[i].vertex_b];
}
p_gizmo->add_lines(points2, material);
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 4430877b8a..3c9d93f13a 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -2400,6 +2400,9 @@ void Node3DEditorViewport::_project_settings_changed() {
const bool use_taa = GLOBAL_GET("rendering/anti_aliasing/quality/use_taa");
viewport->set_use_taa(use_taa);
+ const bool transparent_background = GLOBAL_GET("rendering/transparent_background");
+ viewport->set_transparent_background(transparent_background);
+
const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
viewport->set_use_debanding(use_debanding);
@@ -2432,6 +2435,7 @@ void Node3DEditorViewport::_notification(int p_what) {
bool vp_visible = is_visible_in_tree();
set_process(vp_visible);
+ set_physics_process(vp_visible);
if (vp_visible) {
orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
@@ -2655,6 +2659,21 @@ void Node3DEditorViewport::_notification(int p_what) {
}
} break;
+ case NOTIFICATION_PHYSICS_PROCESS: {
+ if (!update_preview_node) {
+ return;
+ }
+ if (preview_node->is_inside_tree()) {
+ preview_node_pos = _get_instance_position(preview_node_viewport_pos);
+ Transform3D preview_gl_transform = Transform3D(Basis(), preview_node_pos);
+ preview_node->set_global_transform(preview_gl_transform);
+ if (!preview_node->is_visible()) {
+ preview_node->show();
+ }
+ }
+ update_preview_node = false;
+ } break;
+
case NOTIFICATION_ENTER_TREE: {
surface->connect("draw", callable_mp(this, &Node3DEditorViewport::_draw));
surface->connect("gui_input", callable_mp(this, &Node3DEditorViewport::_sinput));
@@ -2967,7 +2986,7 @@ void Node3DEditorViewport::_menu_option(int p_option) {
Transform3D xform;
if (orthogonal) {
xform = sp->get_global_transform();
- xform.basis.set_euler(camera_transform.basis.get_euler());
+ xform.basis = Basis::from_euler(camera_transform.basis.get_euler());
} else {
xform = camera_transform;
xform.scale_basis(sp->get_scale());
@@ -3762,7 +3781,7 @@ AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, boo
if (child) {
AABB child_bounds = _calculate_spatial_bounds(child, false);
- if (bounds.size == Vector3() && Object::cast_to<Node3D>(p_parent)) {
+ if (bounds.size == Vector3() && p_parent) {
bounds = child_bounds;
} else {
bounds.merge_with(child_bounds);
@@ -3770,7 +3789,7 @@ AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, boo
}
}
- if (bounds.size == Vector3() && !Object::cast_to<Node3D>(p_parent)) {
+ if (bounds.size == Vector3() && !p_parent) {
bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
}
@@ -4026,7 +4045,7 @@ bool Node3DEditorViewport::_create_instance(Node *parent, String &path, const Po
gl_transform = parent_node3d->get_global_gizmo_transform();
}
- gl_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
+ gl_transform.origin = spatial_editor->snap_point(preview_node_pos);
gl_transform.basis *= node3d->get_transform().basis;
editor_data->get_undo_redo()->add_do_method(instantiated_scene, "set_global_transform", gl_transform);
@@ -4090,7 +4109,9 @@ void Node3DEditorViewport::_perform_drop_data() {
}
}
-bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
+bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
+ preview_node_viewport_pos = p_point;
+
bool can_instantiate = false;
if (!preview_node->is_inside_tree() && spatial_editor->get_preview_material().is_null()) {
@@ -4154,6 +4175,7 @@ bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant
}
if (can_instantiate) {
_create_preview_node(files);
+ preview_node->hide();
}
}
} else {
@@ -4163,8 +4185,7 @@ bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant
}
if (can_instantiate) {
- Transform3D gl_transform = Transform3D(Basis(), _get_instance_position(p_point));
- preview_node->set_global_transform(gl_transform);
+ update_preview_node = true;
return true;
}
@@ -4773,10 +4794,9 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, int p
view_menu->get_popup()->connect("id_pressed", callable_mp(this, &Node3DEditorViewport::_menu_option));
display_submenu->connect("id_pressed", callable_mp(this, &Node3DEditorViewport::_menu_option));
view_menu->set_disable_shortcuts(true);
-#ifndef _MSC_VER
-#warning this needs to be fixed
-#endif
- //if (OS::get_singleton()->get_current_video_driver() == OS::VIDEO_DRIVER_GLES2) {
+
+ // TODO: Re-evaluate with new OpenGL3 renderer, and implement.
+ //if (OS::get_singleton()->get_current_video_driver() == OS::RENDERING_DRIVER_OPENGL3) {
if (false) {
// Alternate display modes only work when using the Vulkan renderer; make this explicit.
const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
@@ -6930,6 +6950,10 @@ HashSet<RID> _get_physics_bodies_rid(Node *node) {
}
void Node3DEditor::snap_selected_nodes_to_floor() {
+ do_snap_selected_nodes_to_floor = true;
+}
+
+void Node3DEditor::_snap_selected_nodes_to_floor() {
const List<Node *> &selection = editor_selection->get_selected_node_list();
Dictionary snap_data;
@@ -6967,9 +6991,10 @@ void Node3DEditor::snap_selected_nodes_to_floor() {
}
}
if (!found_valid_shape && vi.size()) {
- AABB aabb = (*vi.begin())->get_transformed_aabb();
+ VisualInstance3D *begin = *vi.begin();
+ AABB aabb = begin->get_global_transform().xform(begin->get_aabb());
for (const VisualInstance3D *I : vi) {
- aabb.merge_with(I->get_transformed_aabb());
+ aabb.merge_with(I->get_global_transform().xform(I->get_aabb()));
}
Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
from = aabb.position + size;
@@ -7227,6 +7252,13 @@ void Node3DEditor::_notification(int p_what) {
tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
}
} break;
+
+ case NOTIFICATION_PHYSICS_PROCESS: {
+ if (do_snap_selected_nodes_to_floor) {
+ _snap_selected_nodes_to_floor();
+ do_snap_selected_nodes_to_floor = false;
+ }
+ }
}
}
@@ -7583,7 +7615,7 @@ void Node3DEditor::_preview_settings_changed() {
{ // preview sun
Transform3D t;
- t.basis = Basis(Vector3(sun_rotation.x, sun_rotation.y, 0));
+ t.basis = Basis::from_euler(Vector3(sun_rotation.x, sun_rotation.y, 0));
preview_sun->set_transform(t);
sun_direction->queue_redraw();
preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value());
@@ -8347,10 +8379,12 @@ void Node3DEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
spatial_editor->show();
spatial_editor->set_process(true);
+ spatial_editor->set_physics_process(true);
} else {
spatial_editor->hide();
spatial_editor->set_process(false);
+ spatial_editor->set_physics_process(false);
}
}
diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h
index c76f534c22..7dbe153efd 100644
--- a/editor/plugins/node_3d_editor_plugin.h
+++ b/editor/plugins/node_3d_editor_plugin.h
@@ -193,6 +193,9 @@ private:
void _menu_option(int p_option);
void _set_auto_orthogonal();
Node3D *preview_node = nullptr;
+ bool update_preview_node = false;
+ Point2 preview_node_viewport_pos;
+ Vector3 preview_node_pos;
AABB *preview_bounds = nullptr;
Vector<String> selected_files;
AcceptDialog *accept = nullptr;
@@ -413,7 +416,7 @@ private:
bool _create_instance(Node *parent, String &path, const Point2 &p_point);
void _perform_drop_data();
- bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
void _project_settings_changed();
@@ -720,6 +723,9 @@ private:
void _selection_changed();
void _refresh_menu_icons();
+ bool do_snap_selected_nodes_to_floor = false;
+ void _snap_selected_nodes_to_floor();
+
// Preview Sun and Environment
uint32_t world_env_count = 0;
@@ -767,7 +773,7 @@ private:
WorldEnvironment *preview_environment = nullptr;
bool preview_env_dangling = false;
Ref<Environment> environment;
- Ref<CameraAttributesPhysical> camera_attributes;
+ Ref<CameraAttributesPractical> camera_attributes;
Ref<ProceduralSkyMaterial> sky_material;
bool sun_environ_updating = false;
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 58a0160010..7d7ef9245f 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -1598,9 +1598,24 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const
return nullptr;
}
-void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
+static String _quote_drop_data(const String &str) {
+ // This function prepares a string for being "dropped" into the script editor.
+ // The string can be a resource path, node path or property name.
+
+ const bool using_single_quotes = EDITOR_GET("text_editor/completion/use_single_quotes");
+
+ String escaped = str.c_escape();
+ // If string is double quoted, there is no need to escape single quotes.
+ // We can revert the extra escaping added in c_escape().
+ if (!using_single_quotes) {
+ escaped = escaped.replace("\\'", "\'");
+ }
+
+ return escaped.quote(using_single_quotes ? "'" : "\"");
+}
+
+void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
Dictionary d = p_data;
CodeEdit *te = code_editor->get_text_editor();
@@ -1638,9 +1653,9 @@ void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data
}
if (preload) {
- text_to_drop += "preload(" + String(files[i]).c_escape().quote(quote_style) + ")";
+ text_to_drop += "preload(" + _quote_drop_data(String(files[i])) + ")";
} else {
- text_to_drop += String(files[i]).c_escape().quote(quote_style);
+ text_to_drop += _quote_drop_data(String(files[i]));
}
}
@@ -1686,7 +1701,7 @@ void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data
}
for (const String &segment : path.split("/")) {
if (!segment.is_valid_identifier()) {
- path = path.c_escape().quote(quote_style);
+ path = _quote_drop_data(path);
break;
}
}
@@ -1721,7 +1736,7 @@ void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data
for (const String &segment : path.split("/")) {
if (!segment.is_valid_identifier()) {
- path = path.c_escape().quote(quote_style);
+ path = _quote_drop_data(path);
break;
}
}
@@ -1737,7 +1752,9 @@ void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data
if (d.has("type") && String(d["type"]) == "obj_property") {
te->remove_secondary_carets();
- const String text_to_drop = String(d["property"]).c_escape().quote(quote_style);
+ // It is unclear whether properties may contain single or double quotes.
+ // Assume here that double-quotes may not exist. We are escaping single-quotes if necessary.
+ const String text_to_drop = _quote_drop_data(String(d["property"]));
te->set_caret_line(row);
te->set_caret_column(col);
@@ -1978,18 +1995,6 @@ void ScriptTextEditor::_enable_code_editor() {
add_child(connection_info_dialog);
- edit_hb->add_child(search_menu);
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT);
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV);
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE);
- search_menu->get_popup()->add_separator();
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES);
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES);
- search_menu->get_popup()->add_separator();
- search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
- search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
-
edit_hb->add_child(edit_menu);
edit_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_prepare_edit_menu));
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO);
@@ -2000,38 +2005,73 @@ void ScriptTextEditor::_enable_code_editor() {
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE);
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL);
+ edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_selection"), EDIT_DUPLICATE_SELECTION);
+ edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/delete_line"), EDIT_DELETE_LINE);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/fold_all_lines"), EDIT_FOLD_ALL_LINES);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES);
+ {
+ PopupMenu *sub_menu = memnew(PopupMenu);
+ sub_menu->set_name("line_menu");
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/delete_line"), EDIT_DELETE_LINE);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
+ sub_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
+ edit_menu->get_popup()->add_child(sub_menu);
+ edit_menu->get_popup()->add_submenu_item(TTR("Line"), "line_menu");
+ }
+ {
+ PopupMenu *sub_menu = memnew(PopupMenu);
+ sub_menu->set_name("folding_menu");
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/fold_all_lines"), EDIT_FOLD_ALL_LINES);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES);
+ sub_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
+ edit_menu->get_popup()->add_child(sub_menu);
+ edit_menu->get_popup()->add_submenu_item(TTR("Folding"), "folding_menu");
+ }
edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_selection"), EDIT_DUPLICATE_SELECTION);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_completion_query"), EDIT_COMPLETE);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_tabs"), EDIT_CONVERT_INDENT_TO_TABS);
- edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
+ {
+ PopupMenu *sub_menu = memnew(PopupMenu);
+ sub_menu->set_name("indent_menu");
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_tabs"), EDIT_CONVERT_INDENT_TO_TABS);
+ sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
+ sub_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
+ edit_menu->get_popup()->add_child(sub_menu);
+ edit_menu->get_popup()->add_submenu_item(TTR("Indentation"), "indent_menu");
+ }
edit_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
edit_menu->get_popup()->add_separator();
-
- edit_menu->get_popup()->add_child(convert_case);
- edit_menu->get_popup()->add_submenu_item(TTR("Convert Case"), "convert_case");
- convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_uppercase", TTR("Uppercase"), KeyModifierMask::SHIFT | Key::F4), EDIT_TO_UPPERCASE);
- convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_lowercase", TTR("Lowercase"), KeyModifierMask::SHIFT | Key::F5), EDIT_TO_LOWERCASE);
- convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/capitalize", TTR("Capitalize"), KeyModifierMask::SHIFT | Key::F6), EDIT_CAPITALIZE);
- convert_case->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
-
+ {
+ PopupMenu *sub_menu = memnew(PopupMenu);
+ sub_menu->set_name("convert_case");
+ sub_menu->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_uppercase", TTR("Uppercase"), KeyModifierMask::SHIFT | Key::F4), EDIT_TO_UPPERCASE);
+ sub_menu->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_lowercase", TTR("Lowercase"), KeyModifierMask::SHIFT | Key::F5), EDIT_TO_LOWERCASE);
+ sub_menu->add_shortcut(ED_SHORTCUT("script_text_editor/capitalize", TTR("Capitalize"), KeyModifierMask::SHIFT | Key::F6), EDIT_CAPITALIZE);
+ sub_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
+ edit_menu->get_popup()->add_child(sub_menu);
+ edit_menu->get_popup()->add_submenu_item(TTR("Convert Case"), "convert_case");
+ }
edit_menu->get_popup()->add_child(highlighter_menu);
edit_menu->get_popup()->add_submenu_item(TTR("Syntax Highlighter"), "highlighter_menu");
highlighter_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_change_syntax_highlighter));
+ edit_hb->add_child(search_menu);
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT);
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV);
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE);
+ search_menu->get_popup()->add_separator();
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES);
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES);
+ search_menu->get_popup()->add_separator();
+ search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
+ search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option));
+
_load_theme_settings();
edit_hb->add_child(goto_menu);
@@ -2106,9 +2146,6 @@ ScriptTextEditor::ScriptTextEditor() {
edit_menu->set_switch_on_hover(true);
edit_menu->set_shortcut_context(this);
- convert_case = memnew(PopupMenu);
- convert_case->set_name("convert_case");
-
highlighter_menu = memnew(PopupMenu);
highlighter_menu->set_name("highlighter_menu");
@@ -2153,7 +2190,6 @@ ScriptTextEditor::~ScriptTextEditor() {
memdelete(color_panel);
memdelete(edit_hb);
memdelete(edit_menu);
- memdelete(convert_case);
memdelete(highlighter_menu);
memdelete(search_menu);
memdelete(goto_menu);
diff --git a/editor/plugins/script_text_editor.h b/editor/plugins/script_text_editor.h
index fb02e5c7c4..c165295a8e 100644
--- a/editor/plugins/script_text_editor.h
+++ b/editor/plugins/script_text_editor.h
@@ -79,7 +79,6 @@ class ScriptTextEditor : public ScriptEditorBase {
PopupMenu *breakpoints_menu = nullptr;
PopupMenu *highlighter_menu = nullptr;
PopupMenu *context_menu = nullptr;
- PopupMenu *convert_case = nullptr;
GotoLineDialog *goto_line_dialog = nullptr;
ScriptEditorQuickOpen *quick_open = nullptr;
diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp
index cfece173d6..5dac66d3e1 100644
--- a/editor/plugins/sprite_frames_editor_plugin.cpp
+++ b/editor/plugins/sprite_frames_editor_plugin.cpp
@@ -414,16 +414,16 @@ void SpriteFramesEditor::_notification(int p_what) {
load_sheet->set_icon(get_theme_icon(SNAME("SpriteSheet"), SNAME("EditorIcons")));
copy->set_icon(get_theme_icon(SNAME("ActionCopy"), SNAME("EditorIcons")));
paste->set_icon(get_theme_icon(SNAME("ActionPaste"), SNAME("EditorIcons")));
- empty->set_icon(get_theme_icon(SNAME("InsertBefore"), SNAME("EditorIcons")));
- empty2->set_icon(get_theme_icon(SNAME("InsertAfter"), SNAME("EditorIcons")));
+ empty_before->set_icon(get_theme_icon(SNAME("InsertBefore"), SNAME("EditorIcons")));
+ empty_after->set_icon(get_theme_icon(SNAME("InsertAfter"), SNAME("EditorIcons")));
move_up->set_icon(get_theme_icon(SNAME("MoveLeft"), SNAME("EditorIcons")));
move_down->set_icon(get_theme_icon(SNAME("MoveRight"), SNAME("EditorIcons")));
- _delete->set_icon(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
+ delete_frame->set_icon(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
zoom_out->set_icon(get_theme_icon(SNAME("ZoomLess"), SNAME("EditorIcons")));
zoom_reset->set_icon(get_theme_icon(SNAME("ZoomReset"), SNAME("EditorIcons")));
zoom_in->set_icon(get_theme_icon(SNAME("ZoomMore"), SNAME("EditorIcons")));
- new_anim->set_icon(get_theme_icon(SNAME("New"), SNAME("EditorIcons")));
- remove_anim->set_icon(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
+ add_anim->set_icon(get_theme_icon(SNAME("New"), SNAME("EditorIcons")));
+ delete_anim->set_icon(get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
anim_search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
split_sheet_zoom_out->set_icon(get_theme_icon(SNAME("ZoomLess"), SNAME("EditorIcons")));
split_sheet_zoom_reset->set_icon(get_theme_icon(SNAME("ZoomReset"), SNAME("EditorIcons")));
@@ -1016,19 +1016,19 @@ void SpriteFramesEditor::edit(SpriteFrames *p_frames) {
hide();
}
- new_anim->set_disabled(read_only);
- remove_anim->set_disabled(read_only);
+ add_anim->set_disabled(read_only);
+ delete_anim->set_disabled(read_only);
anim_speed->set_editable(!read_only);
anim_loop->set_disabled(read_only);
load->set_disabled(read_only);
load_sheet->set_disabled(read_only);
copy->set_disabled(read_only);
paste->set_disabled(read_only);
- empty->set_disabled(read_only);
- empty2->set_disabled(read_only);
+ empty_before->set_disabled(read_only);
+ empty_after->set_disabled(read_only);
move_up->set_disabled(read_only);
move_down->set_disabled(read_only);
- _delete->set_disabled(read_only);
+ delete_frame->set_disabled(read_only);
}
void SpriteFramesEditor::set_undo_redo(Ref<EditorUndoRedoManager> p_undo_redo) {
@@ -1187,18 +1187,16 @@ SpriteFramesEditor::SpriteFramesEditor() {
HBoxContainer *hbc_animlist = memnew(HBoxContainer);
sub_vb->add_child(hbc_animlist);
- new_anim = memnew(Button);
- new_anim->set_flat(true);
- new_anim->set_tooltip_text(TTR("New Animation"));
- hbc_animlist->add_child(new_anim);
- new_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_add));
+ add_anim = memnew(Button);
+ add_anim->set_flat(true);
+ hbc_animlist->add_child(add_anim);
+ add_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_add));
- remove_anim = memnew(Button);
- remove_anim->set_flat(true);
- remove_anim->set_tooltip_text(TTR("Remove Animation"));
- hbc_animlist->add_child(remove_anim);
- remove_anim->set_disabled(true);
- remove_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_remove));
+ delete_anim = memnew(Button);
+ delete_anim->set_flat(true);
+ hbc_animlist->add_child(delete_anim);
+ delete_anim->set_disabled(true);
+ delete_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_remove));
anim_search_box = memnew(LineEdit);
hbc_animlist->add_child(anim_search_box);
@@ -1215,6 +1213,11 @@ SpriteFramesEditor::SpriteFramesEditor() {
animations->connect("item_edited", callable_mp(this, &SpriteFramesEditor::_animation_name_edited));
animations->set_allow_reselect(true);
+ add_anim->set_shortcut_context(animations);
+ add_anim->set_shortcut(ED_SHORTCUT("sprite_frames/new_animation", TTR("Add Animation"), KeyModifierMask::CMD_OR_CTRL | Key::N));
+ delete_anim->set_shortcut_context(animations);
+ delete_anim->set_shortcut(ED_SHORTCUT("sprite_frames/delete_animation", TTR("Delete Animation"), Key::KEY_DELETE));
+
HBoxContainer *hbc_anim_speed = memnew(HBoxContainer);
hbc_anim_speed->add_child(memnew(Label(TTR("Speed:"))));
vbc_animlist->add_child(hbc_anim_speed);
@@ -1244,54 +1247,45 @@ SpriteFramesEditor::SpriteFramesEditor() {
load = memnew(Button);
load->set_flat(true);
- load->set_tooltip_text(TTR("Add a Texture from File"));
hbc->add_child(load);
load_sheet = memnew(Button);
load_sheet->set_flat(true);
- load_sheet->set_tooltip_text(TTR("Add Frames from a Sprite Sheet"));
hbc->add_child(load_sheet);
hbc->add_child(memnew(VSeparator));
copy = memnew(Button);
copy->set_flat(true);
- copy->set_tooltip_text(TTR("Copy"));
hbc->add_child(copy);
paste = memnew(Button);
paste->set_flat(true);
- paste->set_tooltip_text(TTR("Paste"));
hbc->add_child(paste);
hbc->add_child(memnew(VSeparator));
- empty = memnew(Button);
- empty->set_flat(true);
- empty->set_tooltip_text(TTR("Insert Empty (Before)"));
- hbc->add_child(empty);
+ empty_before = memnew(Button);
+ empty_before->set_flat(true);
+ hbc->add_child(empty_before);
- empty2 = memnew(Button);
- empty2->set_flat(true);
- empty2->set_tooltip_text(TTR("Insert Empty (After)"));
- hbc->add_child(empty2);
+ empty_after = memnew(Button);
+ empty_after->set_flat(true);
+ hbc->add_child(empty_after);
hbc->add_child(memnew(VSeparator));
move_up = memnew(Button);
move_up->set_flat(true);
- move_up->set_tooltip_text(TTR("Move (Before)"));
hbc->add_child(move_up);
move_down = memnew(Button);
move_down->set_flat(true);
- move_down->set_tooltip_text(TTR("Move (After)"));
hbc->add_child(move_down);
- _delete = memnew(Button);
- _delete->set_flat(true);
- _delete->set_tooltip_text(TTR("Delete"));
- hbc->add_child(_delete);
+ delete_frame = memnew(Button);
+ delete_frame->set_flat(true);
+ hbc->add_child(delete_frame);
hbc->add_spacer();
@@ -1333,13 +1327,40 @@ SpriteFramesEditor::SpriteFramesEditor() {
load->connect("pressed", callable_mp(this, &SpriteFramesEditor::_load_pressed));
load_sheet->connect("pressed", callable_mp(this, &SpriteFramesEditor::_open_sprite_sheet));
- _delete->connect("pressed", callable_mp(this, &SpriteFramesEditor::_delete_pressed));
+ delete_frame->connect("pressed", callable_mp(this, &SpriteFramesEditor::_delete_pressed));
copy->connect("pressed", callable_mp(this, &SpriteFramesEditor::_copy_pressed));
paste->connect("pressed", callable_mp(this, &SpriteFramesEditor::_paste_pressed));
- empty->connect("pressed", callable_mp(this, &SpriteFramesEditor::_empty_pressed));
- empty2->connect("pressed", callable_mp(this, &SpriteFramesEditor::_empty2_pressed));
+ empty_before->connect("pressed", callable_mp(this, &SpriteFramesEditor::_empty_pressed));
+ empty_after->connect("pressed", callable_mp(this, &SpriteFramesEditor::_empty2_pressed));
move_up->connect("pressed", callable_mp(this, &SpriteFramesEditor::_up_pressed));
move_down->connect("pressed", callable_mp(this, &SpriteFramesEditor::_down_pressed));
+
+ load->set_shortcut_context(tree);
+ load->set_shortcut(ED_SHORTCUT("sprite_frames/load_from_file", TTR("Add frame from file"), KeyModifierMask::CMD_OR_CTRL | Key::O));
+ load_sheet->set_shortcut_context(tree);
+ load_sheet->set_shortcut(ED_SHORTCUT("sprite_frames/load_from_sheet", TTR("Add frames from sprite sheet"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::O));
+ delete_frame->set_shortcut_context(tree);
+ delete_frame->set_shortcut(ED_SHORTCUT("sprite_frames/delete", TTR("Delete Frame"), Key::KEY_DELETE));
+ copy->set_shortcut_context(tree);
+ copy->set_shortcut(ED_SHORTCUT("sprite_frames/copy", TTR("Copy Frame"), KeyModifierMask::CMD_OR_CTRL | Key::C));
+ paste->set_shortcut_context(tree);
+ paste->set_shortcut(ED_SHORTCUT("sprite_frames/paste", TTR("Paste Frame"), KeyModifierMask::CMD_OR_CTRL | Key::V));
+ empty_before->set_shortcut_context(tree);
+ empty_before->set_shortcut(ED_SHORTCUT("sprite_frames/empty_before", TTR("Insert Empty (Before Selected)"), KeyModifierMask::ALT | Key::LEFT));
+ empty_after->set_shortcut_context(tree);
+ empty_after->set_shortcut(ED_SHORTCUT("sprite_frames/empty_after", TTR("Insert Empty (After Selected)"), KeyModifierMask::ALT | Key::RIGHT));
+ move_up->set_shortcut_context(tree);
+ move_up->set_shortcut(ED_SHORTCUT("sprite_frames/move_left", TTR("Move Frame Left"), KeyModifierMask::CMD_OR_CTRL | Key::LEFT));
+ move_down->set_shortcut_context(tree);
+ move_down->set_shortcut(ED_SHORTCUT("sprite_frames/move_right", TTR("Move Frame Right"), KeyModifierMask::CMD_OR_CTRL | Key::RIGHT));
+
+ zoom_out->set_shortcut_context(tree);
+ zoom_out->set_shortcut(ED_SHORTCUT_ARRAY("sprite_frames/zoom_out", TTR("Zoom Out"),
+ { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::MINUS), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_SUBTRACT) }));
+ zoom_in->set_shortcut_context(tree);
+ zoom_in->set_shortcut(ED_SHORTCUT_ARRAY("sprite_frames/zoom_in", TTR("Zoom In"),
+ { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::EQUAL), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_ADD) }));
+
file->connect("files_selected", callable_mp(this, &SpriteFramesEditor::_file_load_request).bind(-1));
loading_scene = false;
sel = -1;
diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h
index 092f556c63..5fc3fe4481 100644
--- a/editor/plugins/sprite_frames_editor_plugin.h
+++ b/editor/plugins/sprite_frames_editor_plugin.h
@@ -61,11 +61,11 @@ class SpriteFramesEditor : public HSplitContainer {
Button *load = nullptr;
Button *load_sheet = nullptr;
- Button *_delete = nullptr;
+ Button *delete_frame = nullptr;
Button *copy = nullptr;
Button *paste = nullptr;
- Button *empty = nullptr;
- Button *empty2 = nullptr;
+ Button *empty_before = nullptr;
+ Button *empty_after = nullptr;
Button *move_up = nullptr;
Button *move_down = nullptr;
Button *zoom_out = nullptr;
@@ -75,8 +75,8 @@ class SpriteFramesEditor : public HSplitContainer {
bool loading_scene;
int sel;
- Button *new_anim = nullptr;
- Button *remove_anim = nullptr;
+ Button *add_anim = nullptr;
+ Button *delete_anim = nullptr;
LineEdit *anim_search_box = nullptr;
Tree *animations = nullptr;
diff --git a/editor/plugins/texture_editor_plugin.cpp b/editor/plugins/texture_editor_plugin.cpp
index be382759f5..4aed7a92a2 100644
--- a/editor/plugins/texture_editor_plugin.cpp
+++ b/editor/plugins/texture_editor_plugin.cpp
@@ -29,7 +29,6 @@
/*************************************************************************/
#include "texture_editor_plugin.h"
-
#include "editor/editor_scale.h"
TextureRect *TexturePreview::get_texture_display() {
@@ -123,6 +122,7 @@ TexturePreview::TexturePreview(Ref<Texture2D> p_texture, bool p_show_metadata) {
add_child(checkerboard);
texture_display = memnew(TextureRect);
+ texture_display->set_texture_filter(TEXTURE_FILTER_NEAREST_WITH_MIPMAPS);
texture_display->set_texture(p_texture);
texture_display->set_anchors_preset(TextureRect::PRESET_FULL_RECT);
texture_display->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
diff --git a/editor/plugins/tiles/atlas_merging_dialog.cpp b/editor/plugins/tiles/atlas_merging_dialog.cpp
index d7e08db954..167c6d169b 100644
--- a/editor/plugins/tiles/atlas_merging_dialog.cpp
+++ b/editor/plugins/tiles/atlas_merging_dialog.cpp
@@ -47,9 +47,7 @@ void AtlasMergingDialog::_generate_merged(Vector<Ref<TileSetAtlasSource>> p_atla
merged_mapping.clear();
if (p_atlas_sources.size() >= 2) {
- Ref<Image> output_image;
- output_image.instantiate();
- output_image->create(1, 1, false, Image::FORMAT_RGBA8);
+ Ref<Image> output_image = Image::create_empty(1, 1, false, Image::FORMAT_RGBA8);
// Compute the new texture region size.
Vector2i new_texture_region_size;
diff --git a/editor/plugins/tiles/tile_atlas_view.cpp b/editor/plugins/tiles/tile_atlas_view.cpp
index c823487279..502c34459a 100644
--- a/editor/plugins/tiles/tile_atlas_view.cpp
+++ b/editor/plugins/tiles/tile_atlas_view.cpp
@@ -533,11 +533,11 @@ TileAtlasView::TileAtlasView() {
panel->set_v_size_flags(SIZE_EXPAND_FILL);
add_child(panel);
- // Scrollingsc
zoom_widget = memnew(EditorZoomWidget);
add_child(zoom_widget);
zoom_widget->set_anchors_and_offsets_preset(Control::PRESET_TOP_LEFT, Control::PRESET_MODE_MINSIZE, 2 * EDSCALE);
zoom_widget->connect("zoom_changed", callable_mp(this, &TileAtlasView::_zoom_widget_changed).unbind(1));
+ zoom_widget->set_shortcut_context(this);
button_center_view = memnew(Button);
button_center_view->set_icon(get_theme_icon(SNAME("CenterView"), SNAME("EditorIcons")));
diff --git a/editor/plugins/tiles/tile_data_editors.cpp b/editor/plugins/tiles/tile_data_editors.cpp
index 73ca8b6176..17b9035121 100644
--- a/editor/plugins/tiles/tile_data_editors.cpp
+++ b/editor/plugins/tiles/tile_data_editors.cpp
@@ -831,6 +831,7 @@ GenericTilePolygonEditor::GenericTilePolygonEditor() {
editor_zoom_widget = memnew(EditorZoomWidget);
editor_zoom_widget->set_position(Vector2(5, 5));
editor_zoom_widget->connect("zoom_changed", callable_mp(this, &GenericTilePolygonEditor::_zoom_changed).unbind(1));
+ editor_zoom_widget->set_shortcut_context(this);
root->add_child(editor_zoom_widget);
button_center_view = memnew(Button);
diff --git a/editor/plugins/tiles/tile_map_editor.cpp b/editor/plugins/tiles/tile_map_editor.cpp
index 7cc29dbfad..b9436e17f0 100644
--- a/editor/plugins/tiles/tile_map_editor.cpp
+++ b/editor/plugins/tiles/tile_map_editor.cpp
@@ -460,7 +460,7 @@ void TileMapEditorTilesPlugin::_update_theme() {
source_sort_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("Sort"), SNAME("EditorIcons")));
select_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("ToolSelect"), SNAME("EditorIcons")));
paint_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")));
- line_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("CurveLinear"), SNAME("EditorIcons")));
+ line_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("Line"), SNAME("EditorIcons")));
rect_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("Rectangle"), SNAME("EditorIcons")));
bucket_tool_button->set_icon(tiles_bottom_panel->get_theme_icon(SNAME("Bucket"), SNAME("EditorIcons")));
@@ -2002,6 +2002,7 @@ void TileMapEditorTilesPlugin::_set_source_sort(int p_sort) {
}
TilesEditorPlugin::get_singleton()->set_sorting_option(p_sort);
_update_tile_set_sources_list();
+ EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "tile_source_sort", p_sort);
}
void TileMapEditorTilesPlugin::_bind_methods() {
@@ -2347,27 +2348,27 @@ HashMap<Vector2i, TileMapCell> TileMapEditorTerrainsPlugin::_draw_terrain_path_o
}
HashMap<Vector2i, TileMapCell> output;
- for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &E : terrain_fill_output) {
- if (painted_set.has(E.key)) {
+ for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
+ if (painted_set.has(kv.key)) {
// Paint a random tile with the correct terrain for the painted path.
- output[E.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
+ output[kv.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
} else {
// Avoids updating the painted path from the output if the new pattern is the same as before.
- bool keep_old = false;
- TileMapCell cell = tile_map->get_cell(tile_map_layer, E.key);
+ TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
+ TileMapCell cell = tile_map->get_cell(tile_map_layer, kv.key);
if (cell.source_id != TileSet::INVALID_SOURCE) {
TileSetSource *source = *tile_set->get_source(cell.source_id);
TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
if (atlas_source) {
// Get tile data.
TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
- if (tile_data && tile_data->get_terrains_pattern() == E.value) {
- keep_old = true;
+ if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
+ in_map_terrain_pattern = tile_data->get_terrains_pattern();
}
}
}
- if (!keep_old) {
- output[E.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
+ if (in_map_terrain_pattern != kv.value) {
+ output[kv.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
}
}
}
@@ -2394,24 +2395,28 @@ HashMap<Vector2i, TileMapCell> TileMapEditorTerrainsPlugin::_draw_terrain_patter
}
HashMap<Vector2i, TileMapCell> output;
- for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &E : terrain_fill_output) {
- if (painted_set.has(E.key)) {
+ for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
+ if (painted_set.has(kv.key)) {
// Paint a random tile with the correct terrain for the painted path.
- output[E.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
+ output[kv.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
} else {
// Avoids updating the painted path from the output if the new pattern is the same as before.
- TileMapCell cell = tile_map->get_cell(tile_map_layer, E.key);
+ TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
+ TileMapCell cell = tile_map->get_cell(tile_map_layer, kv.key);
if (cell.source_id != TileSet::INVALID_SOURCE) {
TileSetSource *source = *tile_set->get_source(cell.source_id);
TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
if (atlas_source) {
// Get tile data.
TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
- if (tile_data && !(tile_data->get_terrains_pattern() == E.value)) {
- output[E.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
+ if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
+ in_map_terrain_pattern = tile_data->get_terrains_pattern();
}
}
}
+ if (in_map_terrain_pattern != kv.value) {
+ output[kv.key] = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
+ }
}
}
return output;
@@ -3276,7 +3281,7 @@ void TileMapEditorTerrainsPlugin::_update_tiles_list() {
void TileMapEditorTerrainsPlugin::_update_theme() {
paint_tool_button->set_icon(main_vbox_container->get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")));
- line_tool_button->set_icon(main_vbox_container->get_theme_icon(SNAME("CurveLinear"), SNAME("EditorIcons")));
+ line_tool_button->set_icon(main_vbox_container->get_theme_icon(SNAME("Line"), SNAME("EditorIcons")));
rect_tool_button->set_icon(main_vbox_container->get_theme_icon(SNAME("Rectangle"), SNAME("EditorIcons")));
bucket_tool_button->set_icon(main_vbox_container->get_theme_icon(SNAME("Bucket"), SNAME("EditorIcons")));
diff --git a/editor/plugins/tiles/tiles_editor_plugin.cpp b/editor/plugins/tiles/tiles_editor_plugin.cpp
index 68bc4389a2..6fdc9a80e8 100644
--- a/editor/plugins/tiles/tiles_editor_plugin.cpp
+++ b/editor/plugins/tiles/tiles_editor_plugin.cpp
@@ -66,7 +66,9 @@ void TilesEditorPlugin::_thread() {
pattern_preview_sem.wait();
pattern_preview_mutex.lock();
- if (pattern_preview_queue.size()) {
+ if (pattern_preview_queue.size() == 0) {
+ pattern_preview_mutex.unlock();
+ } else {
QueueItem item = pattern_preview_queue.front()->get();
pattern_preview_queue.pop_front();
pattern_preview_mutex.unlock();
@@ -130,8 +132,6 @@ void TilesEditorPlugin::_thread() {
item.callback.callp(args_ptr, 2, r, error);
viewport->queue_delete();
- } else {
- pattern_preview_mutex.unlock();
}
}
}
@@ -268,8 +268,8 @@ List<int> TilesEditorPlugin::get_sorted_sources(const Ref<TileSet> p_tile_set) c
SourceNameComparator::tile_set = p_tile_set;
List<int> source_ids;
- for (int i = 0; i < tile_set->get_source_count(); i++) {
- source_ids.push_back(tile_set->get_source_id(i));
+ for (int i = 0; i < p_tile_set->get_source_count(); i++) {
+ source_ids.push_back(p_tile_set->get_source_id(i));
}
switch (source_sort) {
diff --git a/editor/plugins/tiles/tiles_editor_plugin.h b/editor/plugins/tiles/tiles_editor_plugin.h
index b1fe6f8df6..bdada9ec90 100644
--- a/editor/plugins/tiles/tiles_editor_plugin.h
+++ b/editor/plugins/tiles/tiles_editor_plugin.h
@@ -122,7 +122,7 @@ public:
// Sorting.
void set_sorting_option(int p_option);
- List<int> get_sorted_sources(const Ref<TileSet> tile_set) const;
+ List<int> get_sorted_sources(const Ref<TileSet> p_tile_set) const;
virtual void edit(Object *p_object) override;
virtual bool handles(Object *p_object) const override;
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index d87513bfe1..d9f8d28067 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -3707,7 +3707,7 @@ void VisualShaderEditor::_notification(int p_what) {
[[fallthrough]];
}
case NOTIFICATION_THEME_CHANGED: {
- highend_label->set_modulate(get_theme_color(SNAME("vulkan_color"), SNAME("Editor")));
+ highend_label->set_modulate(get_theme_color(SNAME("highend_color"), SNAME("Editor")));
node_filter->set_right_icon(Control::get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
@@ -5087,23 +5087,23 @@ VisualShaderEditor::VisualShaderEditor() {
const String &compare_func_desc = TTR("Returns the boolean result of the %s comparison between two parameters.");
- add_options.push_back(AddOption("Equal", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Equal (==)")), { VisualShaderNodeCompare::FUNC_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("GreaterThan", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Greater Than (>)")), { VisualShaderNodeCompare::FUNC_GREATER_THAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("GreaterThanEqual", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Greater Than or Equal (>=)")), { VisualShaderNodeCompare::FUNC_GREATER_THAN_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("Equal (==)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Equal (==)")), { VisualShaderNodeCompare::FUNC_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("GreaterThan (>)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Greater Than (>)")), { VisualShaderNodeCompare::FUNC_GREATER_THAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("GreaterThanEqual (>=)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Greater Than or Equal (>=)")), { VisualShaderNodeCompare::FUNC_GREATER_THAN_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
add_options.push_back(AddOption("If", "Conditional/Functions", "VisualShaderNodeIf", TTR("Returns an associated vector if the provided scalars are equal, greater or less."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("IsInf", "Conditional/Functions", "VisualShaderNodeIs", TTR("Returns the boolean result of the comparison between INF and a scalar parameter."), { VisualShaderNodeIs::FUNC_IS_INF }, VisualShaderNode::PORT_TYPE_BOOLEAN));
add_options.push_back(AddOption("IsNaN", "Conditional/Functions", "VisualShaderNodeIs", TTR("Returns the boolean result of the comparison between NaN and a scalar parameter."), { VisualShaderNodeIs::FUNC_IS_NAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("LessThan", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than (<)")), { VisualShaderNodeCompare::FUNC_LESS_THAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("LessThanEqual", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than or Equal (<=)")), { VisualShaderNodeCompare::FUNC_LESS_THAN_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("NotEqual", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Not Equal (!=)")), { VisualShaderNodeCompare::FUNC_NOT_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("Switch", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated 3D vector if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Switch2D", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated 2D vector if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("SwitchBool", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated boolean if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_BOOLEAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("SwitchFloat", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated floating-point scalar if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_FLOAT }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("SwitchInt", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated integer scalar if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_INT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("SwitchTransform", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated transform if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_TRANSFORM }, VisualShaderNode::PORT_TYPE_TRANSFORM));
-
- add_options.push_back(AddOption("Compare", "Conditional/Common", "VisualShaderNodeCompare", TTR("Returns the boolean result of the comparison between two parameters."), {}, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("LessThan (<)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than (<)")), { VisualShaderNodeCompare::FUNC_LESS_THAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("LessThanEqual (<=)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than or Equal (<=)")), { VisualShaderNodeCompare::FUNC_LESS_THAN_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("NotEqual (!=)", "Conditional/Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Not Equal (!=)")), { VisualShaderNodeCompare::FUNC_NOT_EQUAL }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("Switch (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated 3D vector if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Switch2D (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated 2D vector if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("SwitchBool (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated boolean if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_BOOLEAN }, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("SwitchFloat (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated floating-point scalar if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_FLOAT }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("SwitchInt (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated integer scalar if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_INT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("SwitchTransform (==)", "Conditional/Functions", "VisualShaderNodeSwitch", TTR("Returns an associated transform if the provided boolean value is true or false."), { VisualShaderNodeSwitch::OP_TYPE_TRANSFORM }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+
+ add_options.push_back(AddOption("Compare (==)", "Conditional/Common", "VisualShaderNodeCompare", TTR("Returns the boolean result of the comparison between two parameters."), {}, VisualShaderNode::PORT_TYPE_BOOLEAN));
add_options.push_back(AddOption("Is", "Conditional/Common", "VisualShaderNodeIs", TTR("Returns the boolean result of the comparison between INF (or NaN) and a scalar parameter."), {}, VisualShaderNode::PORT_TYPE_BOOLEAN));
add_options.push_back(AddOption("BooleanConstant", "Conditional/Variables", "VisualShaderNodeBooleanConstant", TTR("Boolean constant."), {}, VisualShaderNode::PORT_TYPE_BOOLEAN));
@@ -5308,7 +5308,7 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("EmitParticle", "Particles", "VisualShaderNodeParticleEmit", "", {}, -1, TYPE_FLAGS_PROCESS | TYPE_FLAGS_PROCESS_CUSTOM | TYPE_FLAGS_COLLIDE, Shader::MODE_PARTICLES));
add_options.push_back(AddOption("ParticleAccelerator", "Particles", "VisualShaderNodeParticleAccelerator", "", {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES));
add_options.push_back(AddOption("ParticleRandomness", "Particles", "VisualShaderNodeParticleRandomness", "", {}, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT | TYPE_FLAGS_PROCESS | TYPE_FLAGS_COLLIDE, Shader::MODE_PARTICLES));
- add_options.push_back(AddOption("MultiplyByAxisAngle", "Particles/Transform", "VisualShaderNodeParticleMultiplyByAxisAngle", TTR("A node for help to multiply a position input vector by rotation using specific axis. Intended to work with emitters."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_EMIT | TYPE_FLAGS_PROCESS | TYPE_FLAGS_COLLIDE, Shader::MODE_PARTICLES));
+ add_options.push_back(AddOption("MultiplyByAxisAngle (*)", "Particles/Transform", "VisualShaderNodeParticleMultiplyByAxisAngle", TTR("A node for help to multiply a position input vector by rotation using specific axis. Intended to work with emitters."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_EMIT | TYPE_FLAGS_PROCESS | TYPE_FLAGS_COLLIDE, Shader::MODE_PARTICLES));
add_options.push_back(AddOption("BoxEmitter", "Particles/Emitters", "VisualShaderNodeParticleBoxEmitter", "", {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES));
add_options.push_back(AddOption("MeshEmitter", "Particles/Emitters", "VisualShaderNodeParticleMeshEmitter", "", {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES));
@@ -5359,10 +5359,10 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Max", "Scalar/Functions", "VisualShaderNodeFloatOp", TTR("Returns the greater of two values."), { VisualShaderNodeFloatOp::OP_MAX }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Min", "Scalar/Functions", "VisualShaderNodeFloatOp", TTR("Returns the lesser of two values."), { VisualShaderNodeFloatOp::OP_MIN }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Mix", "Scalar/Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two scalars."), { VisualShaderNodeMix::OP_TYPE_SCALAR }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("MultiplyAdd", "Scalar/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on scalars."), { VisualShaderNodeMultiplyAdd::OP_TYPE_SCALAR }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Negate", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeFloatFunc::FUNC_NEGATE }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Negate", "Scalar/Functions", "VisualShaderNodeIntFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeIntFunc::FUNC_NEGATE }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("OneMinus", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("1.0 - scalar"), { VisualShaderNodeFloatFunc::FUNC_ONEMINUS }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("MultiplyAdd (a * b + c)", "Scalar/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on scalars."), { VisualShaderNodeMultiplyAdd::OP_TYPE_SCALAR }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Negate (*-1)", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeFloatFunc::FUNC_NEGATE }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Negate (*-1)", "Scalar/Functions", "VisualShaderNodeIntFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeIntFunc::FUNC_NEGATE }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("OneMinus (1-)", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("1.0 - scalar"), { VisualShaderNodeFloatFunc::FUNC_ONEMINUS }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Pow", "Scalar/Functions", "VisualShaderNodeFloatOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeFloatOp::OP_POW }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Radians", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("Converts a quantity in degrees to radians."), { VisualShaderNodeFloatFunc::FUNC_RADIANS }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Reciprocal", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("1.0 / scalar"), { VisualShaderNodeFloatFunc::FUNC_RECIPROCAL }, VisualShaderNode::PORT_TYPE_SCALAR));
@@ -5381,21 +5381,21 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("TanH", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("Returns the hyperbolic tangent of the parameter."), { VisualShaderNodeFloatFunc::FUNC_TANH }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Trunc", "Scalar/Functions", "VisualShaderNodeFloatFunc", TTR("Finds the truncated value of the parameter."), { VisualShaderNodeFloatFunc::FUNC_TRUNC }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Add", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Sums two floating-point scalars."), { VisualShaderNodeFloatOp::OP_ADD }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Add", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Sums two integer scalars."), { VisualShaderNodeIntOp::OP_ADD }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("BitwiseAND", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise AND (a & b) operation for two integers."), { VisualShaderNodeIntOp::OP_BITWISE_AND }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("BitwiseLeftShift", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise left shift (a << b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_LEFT_SHIFT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("BitwiseOR", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise OR (a | b) operation for two integers."), { VisualShaderNodeIntOp::OP_BITWISE_OR }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("BitwiseRightShift", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise right shift (a >> b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_RIGHT_SHIFT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("BitwiseXOR", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise XOR (a ^ b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_XOR }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("Divide", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Divides two floating-point scalars."), { VisualShaderNodeFloatOp::OP_DIV }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Divide", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Divides two integer scalars."), { VisualShaderNodeIntOp::OP_DIV }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("Multiply", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Multiplies two floating-point scalars."), { VisualShaderNodeFloatOp::OP_MUL }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Multiply", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Multiplies two integer scalars."), { VisualShaderNodeIntOp::OP_MUL }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("Add (+)", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Sums two floating-point scalars."), { VisualShaderNodeFloatOp::OP_ADD }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Add (+)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Sums two integer scalars."), { VisualShaderNodeIntOp::OP_ADD }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("BitwiseAND (&)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise AND (a & b) operation for two integers."), { VisualShaderNodeIntOp::OP_BITWISE_AND }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("BitwiseLeftShift (<<)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise left shift (a << b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_LEFT_SHIFT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("BitwiseOR (|)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise OR (a | b) operation for two integers."), { VisualShaderNodeIntOp::OP_BITWISE_OR }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("BitwiseRightShift (>>)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise right shift (a >> b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_RIGHT_SHIFT }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("BitwiseXOR (^)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the result of bitwise XOR (a ^ b) operation on the integer."), { VisualShaderNodeIntOp::OP_BITWISE_XOR }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("Divide (/)", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Divides two floating-point scalars."), { VisualShaderNodeFloatOp::OP_DIV }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Divide (/)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Divides two integer scalars."), { VisualShaderNodeIntOp::OP_DIV }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("Multiply (*)", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Multiplies two floating-point scalars."), { VisualShaderNodeFloatOp::OP_MUL }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Multiply (*)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Multiplies two integer scalars."), { VisualShaderNodeIntOp::OP_MUL }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
add_options.push_back(AddOption("Remainder", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Returns the remainder of the two floating-point scalars."), { VisualShaderNodeFloatOp::OP_MOD }, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Remainder", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Returns the remainder of the two integer scalars."), { VisualShaderNodeIntOp::OP_MOD }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
- add_options.push_back(AddOption("Subtract", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Subtracts two floating-point scalars."), { VisualShaderNodeFloatOp::OP_SUB }, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Subtract", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Subtracts two integer scalars."), { VisualShaderNodeIntOp::OP_SUB }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
+ add_options.push_back(AddOption("Subtract (-)", "Scalar/Operators", "VisualShaderNodeFloatOp", TTR("Subtracts two floating-point scalars."), { VisualShaderNodeFloatOp::OP_SUB }, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Subtract (-)", "Scalar/Operators", "VisualShaderNodeIntOp", TTR("Subtracts two integer scalars."), { VisualShaderNodeIntOp::OP_SUB }, VisualShaderNode::PORT_TYPE_SCALAR_INT));
add_options.push_back(AddOption("FloatConstant", "Scalar/Variables", "VisualShaderNodeFloatConstant", TTR("Scalar floating-point constant."), {}, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("IntConstant", "Scalar/Variables", "VisualShaderNodeIntConstant", TTR("Scalar integer constant."), {}, VisualShaderNode::PORT_TYPE_SCALAR_INT));
@@ -5452,12 +5452,12 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Inverse", "Transform/Functions", "VisualShaderNodeTransformFunc", TTR("Calculates the inverse of a transform."), { VisualShaderNodeTransformFunc::FUNC_INVERSE }, VisualShaderNode::PORT_TYPE_TRANSFORM));
add_options.push_back(AddOption("Transpose", "Transform/Functions", "VisualShaderNodeTransformFunc", TTR("Calculates the transpose of a transform."), { VisualShaderNodeTransformFunc::FUNC_TRANSPOSE }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("Add", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Sums two transforms."), { VisualShaderNodeTransformOp::OP_ADD }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("Divide", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Divides two transforms."), { VisualShaderNodeTransformOp::OP_A_DIV_B }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("Multiply", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Multiplies two transforms."), { VisualShaderNodeTransformOp::OP_AxB }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("MultiplyComp", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Performs per-component multiplication of two transforms."), { VisualShaderNodeTransformOp::OP_AxB_COMP }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("Subtract", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Subtracts two transforms."), { VisualShaderNodeTransformOp::OP_A_MINUS_B }, VisualShaderNode::PORT_TYPE_TRANSFORM));
- add_options.push_back(AddOption("TransformVectorMult", "Transform/Operators", "VisualShaderNodeTransformVecMult", TTR("Multiplies vector by transform."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Add (+)", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Sums two transforms."), { VisualShaderNodeTransformOp::OP_ADD }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+ add_options.push_back(AddOption("Divide (/)", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Divides two transforms."), { VisualShaderNodeTransformOp::OP_A_DIV_B }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+ add_options.push_back(AddOption("Multiply (*)", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Multiplies two transforms."), { VisualShaderNodeTransformOp::OP_AxB }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+ add_options.push_back(AddOption("MultiplyComp (*)", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Performs per-component multiplication of two transforms."), { VisualShaderNodeTransformOp::OP_AxB_COMP }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+ add_options.push_back(AddOption("Subtract (-)", "Transform/Operators", "VisualShaderNodeTransformOp", TTR("Subtracts two transforms."), { VisualShaderNodeTransformOp::OP_A_MINUS_B }, VisualShaderNode::PORT_TYPE_TRANSFORM));
+ add_options.push_back(AddOption("TransformVectorMult (*)", "Transform/Operators", "VisualShaderNodeTransformVecMult", TTR("Multiplies vector by transform."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("TransformConstant", "Transform/Variables", "VisualShaderNodeTransformConstant", TTR("Transform constant."), {}, VisualShaderNode::PORT_TYPE_TRANSFORM));
add_options.push_back(AddOption("TransformParameter", "Transform/Variables", "VisualShaderNodeTransformParameter", TTR("Transform parameter."), {}, VisualShaderNode::PORT_TYPE_TRANSFORM));
@@ -5573,21 +5573,21 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("MixS", "Vector/Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two vectors using scalar."), { VisualShaderNodeMix::OP_TYPE_VECTOR_2D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("MixS", "Vector/Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two vectors using scalar."), { VisualShaderNodeMix::OP_TYPE_VECTOR_3D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("MixS", "Vector/Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two vectors using scalar."), { VisualShaderNodeMix::OP_TYPE_VECTOR_4D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("MultiplyAdd", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("MultiplyAdd", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("MultiplyAdd", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Negate", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Negate", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Negate", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("MultiplyAdd (a * b + c)", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("MultiplyAdd (a * b + c)", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("MultiplyAdd (a * b + c)", "Vector/Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), { VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Negate (*-1)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Negate (*-1)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Negate (*-1)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
add_options.push_back(AddOption("Normalize", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Calculates the normalize product of vector."), { VisualShaderNodeVectorFunc::FUNC_NORMALIZE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("Normalize", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Calculates the normalize product of vector."), { VisualShaderNodeVectorFunc::FUNC_NORMALIZE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Normalize", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Calculates the normalize product of vector."), { VisualShaderNodeVectorFunc::FUNC_NORMALIZE, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("OneMinus", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("OneMinus", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("OneMinus", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Pow", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Pow", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Pow", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("OneMinus (1-)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("OneMinus (1-)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("OneMinus (1-)", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), { VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Pow (^)", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Pow (^)", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Pow (^)", "Vector/Functions", "VisualShaderNodeVectorOp", TTR("Returns the value of the first parameter raised to the power of the second."), { VisualShaderNodeVectorOp::OP_POW, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
add_options.push_back(AddOption("Radians", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Converts a quantity in degrees to radians."), { VisualShaderNodeVectorFunc::FUNC_RADIANS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("Radians", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Converts a quantity in degrees to radians."), { VisualShaderNodeVectorFunc::FUNC_RADIANS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Radians", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Converts a quantity in degrees to radians."), { VisualShaderNodeVectorFunc::FUNC_RADIANS, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
@@ -5632,9 +5632,9 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("StepS", "Vector/Functions", "VisualShaderNodeStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), { VisualShaderNodeStep::OP_TYPE_VECTOR_2D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("StepS", "Vector/Functions", "VisualShaderNodeStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), { VisualShaderNodeStep::OP_TYPE_VECTOR_3D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("StepS", "Vector/Functions", "VisualShaderNodeStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), { VisualShaderNodeStep::OP_TYPE_VECTOR_4D_SCALAR }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Sum", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
- add_options.push_back(AddOption("Sum", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
- add_options.push_back(AddOption("Sum", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
+ add_options.push_back(AddOption("Sum (+)", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
+ add_options.push_back(AddOption("Sum (+)", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
+ add_options.push_back(AddOption("Sum (+)", "Vector/Functions", "VisualShaderNodeDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), { VisualShaderNodeDerivativeFunc::FUNC_SUM, VisualShaderNodeDerivativeFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, true));
add_options.push_back(AddOption("Tan", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), { VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("Tan", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), { VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Tan", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), { VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
@@ -5645,21 +5645,21 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Trunc", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Finds the truncated value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_TRUNC, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Trunc", "Vector/Functions", "VisualShaderNodeVectorFunc", TTR("Finds the truncated value of the parameter."), { VisualShaderNodeVectorFunc::FUNC_TRUNC, VisualShaderNodeVectorFunc::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Add", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 2D vector to 2D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Add", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 3D vector to 3D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Add", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 4D vector to 4D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Divide", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 2D vector by 2D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Divide", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 3D vector by 3D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Divide", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 4D vector by 4D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Multiply", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 2D vector by 2D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Multiply", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 3D vector by 3D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Multiply", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 4D vector by 4D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Add (+)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 2D vector to 2D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Add (+)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 3D vector to 3D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Add (+)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Adds 4D vector to 4D vector."), { VisualShaderNodeVectorOp::OP_ADD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Divide (/)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 2D vector by 2D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Divide (/)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 3D vector by 3D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Divide (/)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Divides 4D vector by 4D vector."), { VisualShaderNodeVectorOp::OP_DIV, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Multiply (*)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 2D vector by 2D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Multiply (*)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 3D vector by 3D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Multiply (*)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Multiplies 4D vector by 4D vector."), { VisualShaderNodeVectorOp::OP_MUL, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
add_options.push_back(AddOption("Remainder", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Returns the remainder of the two 2D vectors."), { VisualShaderNodeVectorOp::OP_MOD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("Remainder", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Returns the remainder of the two 3D vectors."), { VisualShaderNodeVectorOp::OP_MOD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Remainder", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Returns the remainder of the two 4D vectors."), { VisualShaderNodeVectorOp::OP_MOD, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
- add_options.push_back(AddOption("Subtract", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 2D vector from 2D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Subtract", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 3D vector from 3D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
- add_options.push_back(AddOption("Subtract", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 4D vector from 4D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
+ add_options.push_back(AddOption("Subtract (-)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 2D vector from 2D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_2D }, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Subtract (-)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 3D vector from 3D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
+ add_options.push_back(AddOption("Subtract (-)", "Vector/Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 4D vector from 4D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_4D }, VisualShaderNode::PORT_TYPE_VECTOR_4D));
add_options.push_back(AddOption("Vector2Constant", "Vector/Variables", "VisualShaderNodeVec2Constant", TTR("2D vector constant."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D));
add_options.push_back(AddOption("Vector2Parameter", "Vector/Variables", "VisualShaderNodeVec2Parameter", TTR("2D vector parameter."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D));
diff --git a/editor/project_converter_3_to_4.cpp b/editor/project_converter_3_to_4.cpp
index e702ba7020..78f3b4de0e 100644
--- a/editor/project_converter_3_to_4.cpp
+++ b/editor/project_converter_3_to_4.cpp
@@ -302,6 +302,7 @@ static const char *gdscript_function_renames[][2] = {
{ "get_cull_mask_bit", "get_cull_mask_value" }, // Camera3D
{ "get_cursor_position", "get_caret_column" }, // LineEdit
{ "get_d", "get_distance" }, // LineShape2D
+ { "get_depth_bias_enable", "get_depth_bias_enabled" }, // RDPipelineRasterizationState
{ "get_drag_data", "_get_drag_data" }, // Control
{ "get_drag_data_fw", "_get_drag_data_fw" }, // ScriptEditor
{ "get_editor_viewport", "get_editor_main_screen" }, // EditorPlugin
@@ -310,6 +311,7 @@ static const char *gdscript_function_renames[][2] = {
{ "get_error_string", "get_error_message" }, // JSON
{ "get_filename", "get_scene_file_path" }, // Node, WARNING, this may be used in a lot of other places
{ "get_focus_neighbour", "get_focus_neighbor" }, // Control
+ { "get_follow_smoothing", "get_position_smoothing_speed" }, // Camera2D
{ "get_font_types", "get_font_type_list" }, // Theme
{ "get_frame_color", "get_color" }, // ColorRect
{ "get_global_rate_scale", "get_playback_speed_scale" }, // AudioServer
@@ -358,6 +360,7 @@ static const char *gdscript_function_renames[][2] = {
{ "get_render_targetsize", "get_render_target_size" }, // XRInterface
{ "get_resource_type", "_get_resource_type" }, // ResourceFormatLoader
{ "get_result", "get_data" }, //JSON
+ { "get_reverb_bus", "set_reverb_bus_name" }, // Area3D
{ "get_rpc_sender_id", "get_remote_sender_id" }, // Multiplayer API
{ "get_save_extension", "_get_save_extension" }, // EditorImportPlugin
{ "get_scancode", "get_keycode" }, // InputEventKey
@@ -417,6 +420,7 @@ static const char *gdscript_function_renames[][2] = {
{ "is_commiting_action", "is_committing_action" }, // UndoRedo
{ "is_doubleclick", "is_double_click" }, // InputEventMouseButton
{ "is_draw_red", "is_draw_warning" }, // EditorProperty
+ { "is_follow_smoothing_enabled", "is_position_smoothing_enabled" }, // Camera2D
{ "is_h_drag_enabled", "is_drag_horizontal_enabled" }, // Camera2D
{ "is_handle_highlighted", "_is_handle_highlighted" }, // EditorNode3DGizmo, EditorNode3DGizmoPlugin
{ "is_inverting_faces", "get_flip_faces" }, // CSGPrimitive3D
@@ -495,13 +499,16 @@ static const char *gdscript_function_renames[][2] = {
{ "set_cull_mask_bit", "set_cull_mask_value" }, // Camera3D
{ "set_cursor_position", "set_caret_column" }, // LineEdit
{ "set_d", "set_distance" }, // WorldMarginShape2D
+ { "set_depth_bias_enable", "set_depth_bias_enabled" }, // RDPipelineRasterizationState
{ "set_doubleclick", "set_double_click" }, // InputEventMouseButton
{ "set_draw_red", "set_draw_warning" }, // EditorProperty
+ { "set_enable_follow_smoothing", "set_position_smoothing_enabled" }, // Camera2D
{ "set_enabled_focus_mode", "set_focus_mode" }, // BaseButton
{ "set_endian_swap", "set_big_endian" }, // File
{ "set_expand_to_text_length", "set_expand_to_text_length_enabled" }, // LineEdit
{ "set_filename", "set_scene_file_path" }, // Node, WARNING, this may be used in a lot of other places
{ "set_focus_neighbour", "set_focus_neighbor" }, // Control
+ { "set_follow_smoothing", "set_position_smoothing_speed" }, // Camera2D
{ "set_frame_color", "set_color" }, // ColorRect
{ "set_global_rate_scale", "set_playback_speed_scale" }, // AudioServer
{ "set_gravity_distance_scale", "set_gravity_point_distance_scale" }, // Area2D
@@ -525,9 +532,11 @@ static const char *gdscript_function_renames[][2] = {
{ "set_oneshot", "set_one_shot" }, // AnimatedTexture
{ "set_pause_mode", "set_process_mode" }, // Node
{ "set_physical_scancode", "set_physical_keycode" }, // InputEventKey
+ { "set_proximity_fade", "set_proximity_fade_enabled" }, // Material
{ "set_refuse_new_network_connections", "set_refuse_new_connections" }, // Multiplayer API
{ "set_region", "set_region_enabled" }, // Sprite2D, Sprite broke AtlasTexture
{ "set_region_filter_clip", "set_region_filter_clip_enabled" }, // Sprite2D
+ { "set_reverb_bus", "set_reverb_bus_name" }, // Area3D
{ "set_rotate", "set_rotates" }, // PathFollow2D
{ "set_scancode", "set_keycode" }, // InputEventKey
{ "set_shift", "set_shift_pressed" }, // InputEventWithModifiers
@@ -741,12 +750,14 @@ static const char *csharp_function_renames[][2] = {
{ "GetCullMaskBit", "GetCullMaskValue" }, // Camera3D
{ "GetCursorPosition", "GetCaretColumn" }, // LineEdit
{ "GetD", "GetDistance" }, // LineShape2D
+ { "GetDepthBiasEnable", "GetDepthBiasEnabled" }, // RDPipelineRasterizationState
{ "GetDragDataFw", "_GetDragDataFw" }, // ScriptEditor
{ "GetEditorViewport", "GetViewport" }, // EditorPlugin
{ "GetEnabledFocusMode", "GetFocusMode" }, // BaseButton
{ "GetEndianSwap", "IsBigEndian" }, // File
{ "GetErrorString", "GetErrorMessage" }, // JSON
{ "GetFocusNeighbour", "GetFocusNeighbor" }, // Control
+ { "GetFollowSmoothing", "GetFollowSmoothingSpeed" }, // Camera2D
{ "GetFontTypes", "GetFontTypeList" }, // Theme
{ "GetFrameColor", "GetColor" }, // ColorRect
{ "GetGlobalRateScale", "GetPlaybackSpeedScale" }, // AudioServer
@@ -794,6 +805,7 @@ static const char *csharp_function_renames[][2] = {
{ "GetRenderTargetsize", "GetRenderTargetSize" }, // XRInterface
{ "GetResourceType", "_GetResourceType" }, // ResourceFormatLoader
{ "GetResult", "GetData" }, //JSON
+ { "GetReverbBus", "GetReverbBusName" }, // Area3D
{ "GetRpcSenderId", "GetRemoteSenderId" }, // Multiplayer API
{ "GetSaveExtension", "_GetSaveExtension" }, // EditorImportPlugin
{ "GetScancode", "GetKeycode" }, // InputEventKey
@@ -851,6 +863,7 @@ static const char *csharp_function_renames[][2] = {
{ "IsAParentOf", "IsAncestorOf" }, // Node
{ "IsCommitingAction", "IsCommittingAction" }, // UndoRedo
{ "IsDoubleclick", "IsDoubleClick" }, // InputEventMouseButton
+ { "IsFollowSmoothingEnabled", "IsPositionSmoothingEnabled" }, // Camera2D
{ "IsHDragEnabled", "IsDragHorizontalEnabled" }, // Camera2D
{ "IsHandleHighlighted", "_IsHandleHighlighted" }, // EditorNode3DGizmo, EditorNode3DGizmoPlugin
{ "IsNetworkMaster", "IsMultiplayerAuthority" }, // Node
@@ -925,11 +938,14 @@ static const char *csharp_function_renames[][2] = {
{ "SetCullMaskBit", "SetCullMaskValue" }, // Camera3D
{ "SetCursorPosition", "SetCaretColumn" }, // LineEdit
{ "SetD", "SetDistance" }, // WorldMarginShape2D
+ { "SetDepthBiasEnable", "SetDepthBiasEnabled" }, // RDPipelineRasterizationState
{ "SetDoubleclick", "SetDoubleClick" }, // InputEventMouseButton
+ { "SetEnableFollowSmoothing", "SetFollowSmoothingEnabled" }, // Camera2D
{ "SetEnabledFocusMode", "SetFocusMode" }, // BaseButton
{ "SetEndianSwap", "SetBigEndian" }, // File
{ "SetExpandToTextLength", "SetExpandToTextLengthEnabled" }, // LineEdit
{ "SetFocusNeighbour", "SetFocusNeighbor" }, // Control
+ { "SetFollowSmoothing", "SetFollowSmoothingSpeed" }, // Camera2D
{ "SetFrameColor", "SetColor" }, // ColorRect
{ "SetGlobalRateScale", "SetPlaybackSpeedScale" }, // AudioServer
{ "SetGravityDistanceScale", "SetGravityPointDistanceScale" }, // Area2D
@@ -951,9 +967,11 @@ static const char *csharp_function_renames[][2] = {
{ "SetNetworkPeer", "SetMultiplayerPeer" }, // Multiplayer API
{ "SetOneshot", "SetOneShot" }, // AnimatedTexture
{ "SetPhysicalScancode", "SetPhysicalKeycode" }, // InputEventKey
+ { "SetProximityFade", "SetProximityFadeEnabled" }, // Material
{ "SetRefuseNewNetworkConnections", "SetRefuseNewConnections" }, // Multiplayer API
{ "SetRegion", "SetRegionEnabled" }, // Sprite2D, Sprite broke AtlasTexture
{ "SetRegionFilterClip", "SetRegionFilterClipEnabled" }, // Sprite2D
+ { "SetReverbBus", "SetReverbBusName" }, // Area3D
{ "SetRotate", "SetRotates" }, // PathFollow2D
{ "SetScancode", "SetKeycode" }, // InputEventKey
{ "SetShift", "SetShiftPressed" }, // InputEventWithModifiers
@@ -1071,6 +1089,7 @@ static const char *gdscript_properties_renames[][2] = {
{ "close_v_ofs", "close_v_offset" }, // Theme
{ "commentfocus", "comment_focus" }, // Theme
{ "contacts_reported", "max_contacts_reported" }, // RigidBody
+ { "depth_bias_enable", "depth_bias_enabled" }, // RDPipelineRasterizationState
{ "drag_margin_bottom", "drag_bottom_margin" }, // Camera2D
{ "drag_margin_h_enabled", "drag_horizontal_enabled" }, // Camera2D
{ "drag_margin_left", "drag_left_margin" }, // Camera2D
@@ -1113,6 +1132,7 @@ static const char *gdscript_properties_renames[][2] = {
{ "pause_mode", "process_mode" }, // Node
{ "physical_scancode", "physical_keycode" }, // InputEventKey
{ "popup_exclusive", "exclusive" }, // Window
+ { "proximity_fade_enable", "proximity_fade_enabled" }, // Material
{ "rect_position", "position" }, // Control
{ "rect_global_position", "global_position" }, // Control
{ "rect_size", "size" }, // Control
@@ -1123,9 +1143,12 @@ static const char *gdscript_properties_renames[][2] = {
{ "rect_clip_content", "clip_contents" }, // Control
{ "refuse_new_network_connections", "refuse_new_connections" }, // MultiplayerAPI
{ "region_filter_clip", "region_filter_clip_enabled" }, // Sprite2D
+ { "reverb_bus_enable", "reverb_bus_enabled" }, // Area3D
{ "selectedframe", "selected_frame" }, // Theme
{ "size_override_stretch", "size_2d_override_stretch" }, // SubViewport
{ "slips_on_slope", "slide_on_slope" }, // SeparationRayShape2D
+ { "smoothing_enabled", "follow_smoothing_enabled" }, // Camera2D
+ { "smoothing_speed", "position_smoothing_speed" }, // Camera2D
{ "ss_reflections_depth_tolerance", "ssr_depth_tolerance" }, // Environment
{ "ss_reflections_enabled", "ssr_enabled" }, // Environment
{ "ss_reflections_fade_in", "ssr_fade_in" }, // Environment
@@ -1177,6 +1200,7 @@ static const char *csharp_properties_renames[][2] = {
{ "CloseHOfs", "CloseHOffset" }, // Theme
{ "CloseVOfs", "CloseVOffset" }, // Theme
{ "Commentfocus", "CommentFocus" }, // Theme
+ { "DepthBiasEnable", "DepthBiasEnabled" }, // RDPipelineRasterizationState
{ "DragMarginBottom", "DragBottomMargin" }, // Camera2D
{ "DragMarginHEnabled", "DragHorizontalEnabled" }, // Camera2D
{ "DragMarginLeft", "DragLeftMargin" }, // Camera2D
@@ -1212,11 +1236,15 @@ static const char *csharp_properties_renames[][2] = {
{ "PauseMode", "ProcessMode" }, // Node
{ "PhysicalScancode", "PhysicalKeycode" }, // InputEventKey
{ "PopupExclusive", "Exclusive" }, // Window
+ { "ProximityFadeEnable", "ProximityFadeEnabled" }, // Material
{ "RefuseNewNetworkConnections", "RefuseNewConnections" }, // MultiplayerAPI
{ "RegionFilterClip", "RegionFilterClipEnabled" }, // Sprite2D
+ { "ReverbBusEnable", "ReverbBusEnabled" }, // Area3D
{ "Selectedframe", "SelectedFrame" }, // Theme
{ "SizeOverrideStretch", "Size2dOverrideStretch" }, // SubViewport
{ "SlipsOnSlope", "SlideOnSlope" }, // SeparationRayShape2D
+ { "SmoothingEnabled", "FollowSmoothingEnabled" }, // Camera2D
+ { "SmoothingSpeed", "FollowSmoothingSpeed" }, // Camera2D
{ "SsReflectionsDepthTolerance", "SsrDepthTolerance" }, // Environment
{ "SsReflectionsEnabled", "SsrEnabled" }, // Environment
{ "SsReflectionsFadeIn", "SsrFadeIn" }, // Environment
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 05015528c6..5a1eedd8a2 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -143,7 +143,11 @@ private:
install_status_rect->set_texture(new_icon);
}
- set_size(Size2(500, 0) * EDSCALE);
+ Size2i window_size = get_size();
+ Size2 contents_min_size = get_contents_minimum_size();
+ if (window_size.x < contents_min_size.x || window_size.y < contents_min_size.y) {
+ set_size(window_size.max(contents_min_size));
+ }
}
String _test_path() {
@@ -2594,6 +2598,12 @@ ProjectManager::ProjectManager() {
EditorFileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
+ int swap_cancel_ok = EDITOR_GET("interface/editor/accept_dialog_cancel_ok_buttons");
+ if (swap_cancel_ok != 0) { // 0 is auto, set in register_scene based on DisplayServer.
+ // Swap on means OK first.
+ AcceptDialog::set_swap_cancel_ok(swap_cancel_ok == 2);
+ }
+
set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
set_theme(create_custom_theme());
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index acaa4ec3c9..ee358a8064 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -2176,11 +2176,15 @@ void SceneTreeDock::_selection_changed() {
void SceneTreeDock::_do_create(Node *p_parent) {
Variant c = create_dialog->instance_selected();
-
- ERR_FAIL_COND(!c);
Node *child = Object::cast_to<Node>(c);
ERR_FAIL_COND(!child);
+ String new_name = p_parent->validate_child_name(child);
+ if (GLOBAL_GET("editor/node_naming/name_casing").operator int() != NAME_CASING_PASCAL_CASE) {
+ new_name = adjust_name_casing(new_name);
+ }
+ child->set_name(new_name);
+
editor_data->get_undo_redo()->create_action_for_history(TTR("Create Node"), editor_data->get_current_edited_scene_history_id());
if (edited_scene) {
@@ -2191,7 +2195,6 @@ void SceneTreeDock::_do_create(Node *p_parent) {
editor_data->get_undo_redo()->add_do_reference(child);
editor_data->get_undo_redo()->add_undo_method(p_parent, "remove_child", child);
- String new_name = p_parent->validate_child_name(child);
EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
editor_data->get_undo_redo()->add_do_method(ed, "live_debug_create_node", edited_scene->get_path_to(p_parent), child->get_class(), new_name);
editor_data->get_undo_redo()->add_undo_method(ed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(p_parent)).path_join(new_name)));
diff --git a/main/main.cpp b/main/main.cpp
index 08a9b4c310..dbaf42b3e4 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -1808,6 +1808,8 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
"0,33200,1,or_greater")); // No negative numbers
GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
+ GLOBAL_DEF("display/window/ios/hide_status_bar", true);
+ GLOBAL_DEF("display/window/ios/suppress_ui_gesture", true);
GLOBAL_DEF("input_devices/pointing/ios/touch_delay", 0.15);
ProjectSettings::get_singleton()->set_custom_property_info("input_devices/pointing/ios/touch_delay",
PropertyInfo(Variant::FLOAT,
@@ -1954,9 +1956,15 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
{
String display_driver = DisplayServer::get_create_function_name(display_driver_idx);
+ Vector2i *window_position = nullptr;
+ Vector2i position = init_custom_pos;
+ if (init_use_custom_pos) {
+ window_position = &position;
+ }
+
// rendering_driver now held in static global String in main and initialized in setup()
Error err;
- display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_size, err);
+ display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, err);
if (err != OK || display_server == nullptr) {
// We can't use this display server, try other ones as fallback.
// Skip headless (always last registered) because that's not what users
@@ -1965,7 +1973,7 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
if (i == display_driver_idx) {
continue; // Don't try the same twice.
}
- display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_size, err);
+ display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, err);
if (err == OK && display_server != nullptr) {
break;
}
@@ -2127,7 +2135,7 @@ Error Main::setup2(Thread::ID p_main_tid_override) {
} else {
// Create a 1×1 transparent image. This will effectively hide the splash image.
boot_logo.instantiate();
- boot_logo->create(1, 1, false, Image::FORMAT_RGBA8);
+ boot_logo->initialize_data(1, 1, false, Image::FORMAT_RGBA8);
boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0));
}
diff --git a/misc/dist/html/editor.html b/misc/dist/html/editor.html
index c9f3c2cc0d..93afbf085d 100644
--- a/misc/dist/html/editor.html
+++ b/misc/dist/html/editor.html
@@ -1,752 +1,757 @@
<!DOCTYPE html>
-<html xmlns="https://www.w3.org/1999/xhtml" lang="en">
-<head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
- <meta name="author" content="Godot Engine" />
- <meta name="description" content="Use the Godot Engine editor directly in your web browser, without having to install anything." />
- <meta name="mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="application-name" content="Godot" />
- <meta name="apple-mobile-web-app-title" content="Godot" />
- <meta name="theme-color" content="#202531" />
- <meta name="msapplication-navbutton-color" content="#202531" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
- <meta name="msapplication-starturl" content="/latest" />
- <meta property="og:site_name" content="Godot Engine Web Editor" />
- <meta property="og:url" name="twitter:url" content="https://editor.godotengine.org/releases/latest/" />
- <meta property="og:title" name="twitter:title" content="Free and open source 2D and 3D game engine" />
- <meta property="og:description" name="twitter:description" content="Use the Godot Engine editor directly in your web browser, without having to install anything." />
- <meta property="og:image" name="twitter:image" content="https://godotengine.org/themes/godotengine/assets/og_image.png" />
- <meta property="og:type" content="website" />
- <meta name="twitter:card" content="summary" />
- <link id="-gd-engine-icon" rel="icon" type="image/png" href="favicon.png" />
- <link rel="apple-touch-icon" type="image/png" href="favicon.png" />
- <link rel="manifest" href="manifest.json" />
- <title>Godot Engine Web Editor (@GODOT_VERSION@)</title>
- <style>
- *:focus {
- /* More visible outline for better keyboard navigation. */
- outline: 0.125rem solid hsl(220, 100%, 62.5%);
- /* Make the outline always appear above other elements. */
- /* Otherwise, one of its sides can be hidden by tabs in the Download and More layouts. */
- position: relative;
- }
-
- body {
- touch-action: none;
- font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
- margin: 0;
- border: 0 none;
- padding: 0;
- text-align: center;
- background-color: #333b4f;
- overflow: hidden;
- }
-
- a {
- color: hsl(205, 100%, 75%);
- text-decoration-color: hsla(205, 100%, 75%, 0.3);
- text-decoration-thickness: 0.125rem;
- }
-
- a:hover {
- filter: brightness(117.5%);
- }
-
- a:active {
- filter: brightness(82.5%);
- }
-
- .welcome-modal {
- display: none;
- position: fixed;
- z-index: 1;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- overflow: auto;
- background-color: hsla(0, 0%, 0%, 0.5);
- text-align: left;
- }
-
- .welcome-modal-title {
- text-align: center;
- }
-
- .welcome-modal-content {
- background-color: #333b4f;
- box-shadow: 0 0.25rem 0.25rem hsla(0, 0%, 0%, 0.5);
- line-height: 1.5;
- max-width: 38rem;
- margin: 4rem auto 0 auto;
- color: white;
- border-radius: 0.5rem;
- padding: 1rem 1rem 2rem 1rem;
- }
-
- #tabs-buttons {
- /* Match the default background color of the editor window for a seamless appearance. */
- background-color: #202531;
- }
-
- #tab-game {
- /* Use a pure black background to better distinguish the running project */
- /* from the editor window, and to use a more neutral background color (no tint). */
- background-color: black;
- /* Make the background span the entire page height. */
- min-height: 100vh;
- }
-
- #canvas, #gameCanvas {
- display: block;
- margin: 0;
- color: white;
- }
-
- /* Don't show distracting focus outlines for the main tabs' contents. */
- #tab-editor canvas:focus,
- #tab-game canvas:focus,
- #canvas:focus,
- #gameCanvas:focus {
- outline: none;
- }
-
- .godot {
- color: #e0e0e0;
- background-color: #3b3943;
- background-image: linear-gradient(to bottom, #403e48, #35333c);
- border: 1px solid #45434e;
- box-shadow: 0 0 1px 1px #2f2d35;
- }
-
- .btn {
- appearance: none;
- color: #e0e0e0;
- background-color: #262c3b;
- border: 1px solid #202531;
- padding: 0.5rem 1rem;
- margin: 0 0.5rem;
- }
-
- .btn:not(:disabled):hover {
- color: #e0e1e5;
- border-color: #666c7b;
- }
-
- .btn:active {
- border-color: #699ce8;
- color: #699ce8;
- }
-
- .btn:disabled {
- color: #aaa;
- border-color: #242937;
- }
-
- .btn.tab-btn {
- padding: 0.3rem 1rem;
- }
-
- .btn.close-btn {
- padding: 0.3rem 1rem;
- margin-left: -0.75rem;
- font-weight: 700;
- }
-
-
- /* Status display
- * ============== */
-
- #status {
- position: absolute;
- left: 0;
- top: 0;
- right: 0;
- bottom: 0;
- display: flex;
- justify-content: center;
- align-items: center;
- /* don't consume click events - make children visible explicitly */
- visibility: hidden;
- }
-
- #status-progress {
- width: 366px;
- height: 7px;
- background-color: #38363A;
- border: 1px solid #444246;
- padding: 1px;
- box-shadow: 0 0 2px 1px #1B1C22;
- border-radius: 2px;
- visibility: visible;
- }
-
- @media only screen and (orientation:portrait) {
- #status-progress {
- width: 61.8%;
- }
- }
-
- #status-progress-inner {
- height: 100%;
- width: 0;
- box-sizing: border-box;
- transition: width 0.5s linear;
- background-color: #202020;
- border: 1px solid #222223;
- box-shadow: 0 0 1px 1px #27282E;
- border-radius: 3px;
- }
-
- #status-indeterminate {
- visibility: visible;
- position: relative;
- }
-
- #status-indeterminate > div {
- width: 4.5px;
- height: 0;
- border-style: solid;
- border-width: 9px 3px 0 3px;
- border-color: #2b2b2b transparent transparent transparent;
- transform-origin: center 21px;
- position: absolute;
- }
-
- #status-indeterminate > div:nth-child(1) { transform: rotate( 22.5deg); }
- #status-indeterminate > div:nth-child(2) { transform: rotate( 67.5deg); }
- #status-indeterminate > div:nth-child(3) { transform: rotate(112.5deg); }
- #status-indeterminate > div:nth-child(4) { transform: rotate(157.5deg); }
- #status-indeterminate > div:nth-child(5) { transform: rotate(202.5deg); }
- #status-indeterminate > div:nth-child(6) { transform: rotate(247.5deg); }
- #status-indeterminate > div:nth-child(7) { transform: rotate(292.5deg); }
- #status-indeterminate > div:nth-child(8) { transform: rotate(337.5deg); }
-
- #status-notice {
- margin: 0 100px;
- line-height: 1.3;
- visibility: visible;
- padding: 4px 6px;
- visibility: visible;
- }
- </style>
-</head>
-<body>
- <div
- id="welcome-modal"
- class="welcome-modal"
- role="dialog"
- aria-labelledby="welcome-modal-title"
- aria-describedby="welcome-modal-description"
- onclick="if (event.target === this) closeWelcomeModal(false)"
- >
- <div class="welcome-modal-content">
- <h2 id="welcome-modal-title" class="welcome-modal-title">Important - Please read before continuing</h2>
- <div id="welcome-modal-description">
- <p>
- The Godot Web Editor has some limitations compared to the native version.
- Its main focus is education and experimentation;
- <strong>it is not recommended for production</strong>.
- </p>
- <p>
- Refer to the
- <a
- href="https://docs.godotengine.org/en/latest/tutorials/editor/using_the_web_editor.html"
- target="_blank"
- rel="noopener"
- >Web editor documentation</a> for usage instructions and limitations.
- </p>
- </div>
- <div id="welcome-modal-missing-description" style="display: none">
- <p>
- <strong>The following features required by the Godot Web Editor are missing:</strong>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
+ <meta name="author" content="Godot Engine">
+ <meta name="description" content="Use the Godot Engine editor directly in your web browser, without having to install anything.">
+ <meta name="mobile-web-app-capable" content="yes">
+ <meta name="apple-mobile-web-app-capable" content="yes">
+ <meta name="application-name" content="Godot">
+ <meta name="apple-mobile-web-app-title" content="Godot">
+ <meta name="theme-color" content="#202531">
+ <meta name="msapplication-navbutton-color" content="#202531">
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
+ <meta name="msapplication-starturl" content="/latest">
+ <meta property="og:site_name" content="Godot Engine Web Editor">
+ <meta property="og:url" name="twitter:url" content="https://editor.godotengine.org/releases/latest/">
+ <meta property="og:title" name="twitter:title" content="Free and open source 2D and 3D game engine">
+ <meta property="og:description" name="twitter:description" content="Use the Godot Engine editor directly in your web browser, without having to install anything.">
+ <meta property="og:image" name="twitter:image" content="https://godotengine.org/themes/godotengine/assets/og_image.png">
+ <meta property="og:type" content="website">
+ <meta name="twitter:card" content="summary">
+ <link id="-gd-engine-icon" rel="icon" type="image/png" href="favicon.png">
+ <link rel="apple-touch-icon" type="image/png" href="favicon.png">
+ <link rel="manifest" href="manifest.json">
+ <title>Godot Engine Web Editor (@GODOT_VERSION@)</title>
+ <style>
+*:focus {
+ /* More visible outline for better keyboard navigation. */
+ outline: 0.125rem solid hsl(220, 100%, 62.5%);
+ /* Make the outline always appear above other elements. */
+ /* Otherwise, one of its sides can be hidden by tabs in the Download and More layouts. */
+ position: relative;
+}
+
+body {
+ touch-action: none;
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
+ margin: 0;
+ border: 0 none;
+ padding: 0;
+ text-align: center;
+ background-color: #333b4f;
+ overflow: hidden;
+}
+
+a {
+ color: hsl(205, 100%, 75%);
+ text-decoration-color: hsla(205, 100%, 75%, 0.3);
+ text-decoration-thickness: 0.125rem;
+}
+
+a:hover {
+ filter: brightness(117.5%);
+}
+
+a:active {
+ filter: brightness(82.5%);
+}
+
+.welcome-modal {
+ display: none;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: hsla(0, 0%, 0%, 0.5);
+ text-align: left;
+}
+
+.welcome-modal-title {
+ text-align: center;
+}
+
+.welcome-modal-content {
+ background-color: #333b4f;
+ box-shadow: 0 0.25rem 0.25rem hsla(0, 0%, 0%, 0.5);
+ line-height: 1.5;
+ max-width: 38rem;
+ margin: 4rem auto 0 auto;
+ color: white;
+ border-radius: 0.5rem;
+ padding: 1rem 1rem 2rem 1rem;
+}
+
+#tabs-buttons {
+ /* Match the default background color of the editor window for a seamless appearance. */
+ background-color: #202531;
+}
+
+#tab-game {
+ /* Use a pure black background to better distinguish the running project */
+ /* from the editor window, and to use a more neutral background color (no tint). */
+ background-color: black;
+ /* Make the background span the entire page height. */
+ min-height: 100vh;
+}
+
+#canvas, #gameCanvas {
+ display: block;
+ margin: 0;
+ color: white;
+}
+
+/* Don't show distracting focus outlines for the main tabs' contents. */
+#tab-editor canvas:focus,
+#tab-game canvas:focus,
+#canvas:focus,
+#gameCanvas:focus {
+ outline: none;
+}
+
+.godot {
+ color: #e0e0e0;
+ background-color: #3b3943;
+ background-image: linear-gradient(to bottom, #403e48, #35333c);
+ border: 1px solid #45434e;
+ box-shadow: 0 0 1px 1px #2f2d35;
+}
+
+.btn {
+ appearance: none;
+ color: #e0e0e0;
+ background-color: #262c3b;
+ border: 1px solid #202531;
+ padding: 0.5rem 1rem;
+ margin: 0 0.5rem;
+}
+
+.btn:not(:disabled):hover {
+ color: #e0e1e5;
+ border-color: #666c7b;
+}
+
+.btn:active {
+ border-color: #699ce8;
+ color: #699ce8;
+}
+
+.btn:disabled {
+ color: #aaa;
+ border-color: #242937;
+}
+
+.btn.tab-btn {
+ padding: 0.3rem 1rem;
+}
+
+.btn.close-btn {
+ padding: 0.3rem 1rem;
+ margin-left: -0.75rem;
+ font-weight: 700;
+}
+
+/* Status display */
+
+#status {
+ position: absolute;
+ left: 0;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ /* don't consume click events - make children visible explicitly */
+ visibility: hidden;
+}
+
+#status-progress {
+ width: 366px;
+ height: 7px;
+ background-color: #38363A;
+ border: 1px solid #444246;
+ padding: 1px;
+ box-shadow: 0 0 2px 1px #1B1C22;
+ border-radius: 2px;
+ visibility: visible;
+}
+
+@media only screen and (orientation:portrait) {
+ #status-progress {
+ width: 61.8%;
+ }
+}
+
+#status-progress-inner {
+ height: 100%;
+ width: 0;
+ box-sizing: border-box;
+ transition: width 0.5s linear;
+ background-color: #202020;
+ border: 1px solid #222223;
+ box-shadow: 0 0 1px 1px #27282E;
+ border-radius: 3px;
+}
+
+#status-indeterminate {
+ visibility: visible;
+ position: relative;
+}
+
+#status-indeterminate > div {
+ width: 4.5px;
+ height: 0;
+ border-style: solid;
+ border-width: 9px 3px 0 3px;
+ border-color: #2b2b2b transparent transparent transparent;
+ transform-origin: center 21px;
+ position: absolute;
+}
+
+#status-indeterminate > div:nth-child(1) { transform: rotate( 22.5deg); }
+#status-indeterminate > div:nth-child(2) { transform: rotate( 67.5deg); }
+#status-indeterminate > div:nth-child(3) { transform: rotate(112.5deg); }
+#status-indeterminate > div:nth-child(4) { transform: rotate(157.5deg); }
+#status-indeterminate > div:nth-child(5) { transform: rotate(202.5deg); }
+#status-indeterminate > div:nth-child(6) { transform: rotate(247.5deg); }
+#status-indeterminate > div:nth-child(7) { transform: rotate(292.5deg); }
+#status-indeterminate > div:nth-child(8) { transform: rotate(337.5deg); }
+
+#status-notice {
+ margin: 0 100px;
+ line-height: 1.3;
+ visibility: visible;
+ padding: 4px 6px;
+ visibility: visible;
+}
+ </style>
+ </head>
+ <body>
+ <div
+ id="welcome-modal"
+ class="welcome-modal"
+ role="dialog"
+ aria-labelledby="welcome-modal-title"
+ aria-describedby="welcome-modal-description"
+ onclick="if (event.target === this) closeWelcomeModal(false)"
+ >
+ <div class="welcome-modal-content">
+ <h2 id="welcome-modal-title" class="welcome-modal-title">Important - Please read before continuing</h2>
+ <div id="welcome-modal-description">
+ <p>
+ The Godot Web Editor has some limitations compared to the native version.
+ Its main focus is education and experimentation;
+ <strong>it is not recommended for production</strong>.
+ </p>
+ <p>
+ Refer to the
+ <a
+ href="https://docs.godotengine.org/en/latest/tutorials/editor/using_the_web_editor.html"
+ target="_blank"
+ rel="noopener"
+ >Web editor documentation</a> for usage instructions and limitations.
+ </p>
+ </div>
+ <div id="welcome-modal-missing-description" style="display: none">
+ <p>
+ <strong>The following features required by the Godot Web Editor are missing:</strong>
+ </p>
<ul id="welcome-modal-missing-list">
</ul>
- </p>
- <p>
- If you are self-hosting the web editor,
- refer to
- <a
- href="https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_web.html"
- target="_blank"
- rel="noopener"
- >Exporting for the Web</a> for more information.
- </p>
- </div>
- <div style="text-align: center">
- <button id="welcome-modal-dismiss" class="btn" type="button" onclick="closeWelcomeModal(true)" style="margin-top: 1rem">
- OK, don't show again
- </button>
+ <p>
+ If you are self-hosting the web editor,
+ refer to
+ <a
+ href="https://docs.godotengine.org/en/latest/tutorials/export/exporting_for_web.html"
+ target="_blank"
+ rel="noopener"
+ >Exporting for the Web</a> for more information.
+ </p>
+ </div>
+ <div style="text-align: center">
+ <button id="welcome-modal-dismiss" class="btn" type="button" onclick="closeWelcomeModal(true)" style="margin-top: 1rem">
+ OK, don't show again
+ </button>
+ </div>
</div>
</div>
- </div>
- <div id="tabs-buttons">
- <button id="btn-tab-loader" class="btn tab-btn" onclick="showTab('loader')">Loader</button>
- <button id="btn-tab-editor" class="btn tab-btn" disabled="disabled" onclick="showTab('editor')">Editor</button>
- <button id="btn-close-editor" class="btn close-btn" disabled="disabled" onclick="closeEditor()">×</button>
- <button id="btn-tab-game" class="btn tab-btn" disabled="disabled" onclick="showTab('game')">Game</button>
- <button id="btn-close-game" class="btn close-btn" disabled="disabled" onclick="closeGame()">×</button>
- <button id="btn-tab-update" class="btn tab-btn" style="display: none;">Update</button>
- </div>
- <div id="tabs">
- <div id="tab-loader">
- <div style="color: #e0e0e0;" id="persistence">
- <br />
- <img src="logo.svg" alt="Godot Engine logo" width="1024" height="414" style="width: auto; height: auto; max-width: min(85%, 50vh); max-height: 250px" />
- <br />
- @GODOT_VERSION@
- <br />
- <a href="releases/">Need an old version?</a>
- <br />
- <br />
- <br />
- <label for="videoMode" style="margin-right: 1rem">Video driver:</label>
- <select id="videoMode">
- <option value="" selected="selected">Auto</option>
- <option value="opengl3">WebGL 2</option>
- </select>
- <br />
- <br />
- <label for="zip-file" style="margin-right: 1rem">Preload project ZIP:</label> <input id="zip-file" type="file" name="files" style="margin-bottom: 1rem"/>
- <br />
-<a href="demo.zip">(Try this for example)</a>
- <br />
- <br />
- <button id="startButton" class="btn" style="margin-bottom: 4rem; font-weight: 700">Start Godot editor</button>
- <br />
- <button class="btn" onclick="clearPersistence()" style="margin-bottom: 1.5rem">Clear persistent data</button>
- <br />
- <a href="https://docs.godotengine.org/en/latest/tutorials/editor/using_the_web_editor.html">Web editor documentation</a>
- </div>
- </div>
- <div id="tab-editor" style="display: none;">
- <canvas id="editor-canvas" tabindex="1">
- HTML5 canvas appears to be unsupported in the current browser.<br />
- Please try updating or use a different browser.
- </canvas>
- </div>
- <div id="tab-game" style="display: none;">
- <canvas id="game-canvas" tabindex="2">
- HTML5 canvas appears to be unsupported in the current browser.<br />
- Please try updating or use a different browser.
- </canvas>
+ <div id="tabs-buttons">
+ <button id="btn-tab-loader" class="btn tab-btn" onclick="showTab('loader')">Loader</button>
+ <button id="btn-tab-editor" class="btn tab-btn" disabled="disabled" onclick="showTab('editor')">Editor</button>
+ <button id="btn-close-editor" class="btn close-btn" disabled="disabled" onclick="closeEditor()">×</button>
+ <button id="btn-tab-game" class="btn tab-btn" disabled="disabled" onclick="showTab('game')">Game</button>
+ <button id="btn-close-game" class="btn close-btn" disabled="disabled" onclick="closeGame()">×</button>
+ <button id="btn-tab-update" class="btn tab-btn" style="display: none;">Update</button>
</div>
- <div id="tab-status" style="display: none;">
- <div id="status-progress" style="display: none;" oncontextmenu="event.preventDefault();"><div id="status-progress-inner"></div></div>
- <div id="status-indeterminate" style="display: none;" oncontextmenu="event.preventDefault();">
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
+ <div id="tabs">
+ <div id="tab-loader">
+ <div style="color: #e0e0e0;" id="persistence">
+ <br >
+ <img src="logo.svg" alt="Godot Engine logo" width="1024" height="414" style="width: auto; height: auto; max-width: min(85%, 50vh); max-height: 250px">
+ <br >
+ @GODOT_VERSION@
+ <br >
+ <a href="releases/">Need an old version?</a>
+ <br >
+ <br >
+ <br >
+ <label for="videoMode" style="margin-right: 1rem">Video driver:</label>
+ <select id="videoMode">
+ <option value="" selected="selected">Auto</option>
+ <option value="opengl3">WebGL 2</option>
+ </select>
+ <br >
+ <br >
+ <label for="zip-file" style="margin-right: 1rem">Preload project ZIP:</label>
+ <input id="zip-file" type="file" name="files" style="margin-bottom: 1rem">
+ <br >
+ <a href="demo.zip">(Try this for example)</a>
+ <br >
+ <br >
+ <button id="startButton" class="btn" style="margin-bottom: 4rem; font-weight: 700">Start Godot editor</button>
+ <br >
+ <button class="btn" onclick="clearPersistence()" style="margin-bottom: 1.5rem">Clear persistent data</button>
+ <br >
+ <a href="https://docs.godotengine.org/en/latest/tutorials/editor/using_the_web_editor.html">Web editor documentation</a>
+ </div>
+ </div>
+ <div id="tab-editor" style="display: none;">
+ <canvas id="editor-canvas" tabindex="1">
+ HTML5 canvas appears to be unsupported in the current browser.<br >
+ Please try updating or use a different browser.
+ </canvas>
+ </div>
+ <div id="tab-game" style="display: none;">
+ <canvas id="game-canvas" tabindex="2">
+ HTML5 canvas appears to be unsupported in the current browser.<br >
+ Please try updating or use a different browser.
+ </canvas>
+ </div>
+ <div id="tab-status" style="display: none;">
+ <div id="status-progress" style="display: none;" oncontextmenu="event.preventDefault();">
+ <div id="status-progress-inner"></div>
+ </div>
+ <div id="status-indeterminate" style="display: none;" oncontextmenu="event.preventDefault();">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ </div>
+ <div id="status-notice" class="godot" style="display: none;"></div>
</div>
- <div id="status-notice" class="godot" style="display: none;"></div>
</div>
- </div>
- <script>//<![CDATA[
- window.addEventListener("load", () => {
- function notifyUpdate(sw) {
- const btn = document.getElementById("btn-tab-update");
- btn.onclick = function () {
- if (!window.confirm("Are you sure you want to update?\nClicking \"OK\" will reload all active instances!")) {
- return;
- }
- sw.postMessage("update");
- btn.innerHTML = "Updating...";
- btn.disabled = true;
- };
- btn.style.display = "";
- }
- if ("serviceWorker" in navigator) {
- navigator.serviceWorker.register("service.worker.js").then(function (reg) {
- if (reg.waiting) {
- notifyUpdate(reg.waiting);
- }
- reg.addEventListener("updatefound", function () {
- const update = reg.installing;
- update.addEventListener("statechange", function () {
- if (update.state === "installed") {
- // It's a new install, claim and perform aggressive caching.
- if (!reg.active) {
- update.postMessage("claim");
- } else {
- notifyUpdate(update);
- }
- }
- });
- });
- });
- }
-
- const missing = Engine.getMissingFeatures();
- if (missing.length) {
- // Display error dialog as threading support is required for the editor.
- setButtonEnabled('startButton', false);
- document.getElementById("welcome-modal-description").style.display = "none";
- document.getElementById("welcome-modal-missing-description").style.display = "block";
- document.getElementById("welcome-modal-dismiss").style.display = "none";
- const list = document.getElementById("welcome-modal-missing-list");
- for (let i = 0; i < missing.length; i++) {
- const node = document.createElement("li");
- node.innerText = missing[i];
- list.appendChild(node);
- }
- }
-
- if (missing.length || localStorage.getItem("welcomeModalDismissed") !== 'true') {
- document.getElementById("welcome-modal").style.display = "block";
- document.getElementById("welcome-modal-dismiss").focus();
+ <script>
+window.addEventListener('load', () => {
+ function notifyUpdate(sw) {
+ const btn = document.getElementById('btn-tab-update');
+ btn.onclick = function () {
+ if (!window.confirm('Are you sure you want to update?\nClicking "OK" will reload all active instances!')) {
+ return;
}
- });
-
- function closeWelcomeModal(dontShowAgain) {
- document.getElementById("welcome-modal").style.display = "none";
- if (dontShowAgain) {
- localStorage.setItem("welcomeModalDismissed", 'true');
+ sw.postMessage('update');
+ btn.innerHTML = 'Updating...';
+ btn.disabled = true;
+ };
+ btn.style.display = '';
+ }
+ if ('serviceWorker' in navigator) {
+ navigator.serviceWorker.register('service.worker.js').then(function (reg) {
+ if (reg.waiting) {
+ notifyUpdate(reg.waiting);
}
- }
- //]]></script>
- <script src="godot.editor.js"></script>
- <script>//<![CDATA[
-
- var editor = null;
- var game = null;
- var setStatusMode;
- var setStatusNotice;
- var video_driver = "";
-
- function clearPersistence() {
- function deleteDB(path) {
- return new Promise(function(resolve, reject) {
- var req = indexedDB.deleteDatabase(path);
- req.onsuccess = function() {
- resolve();
- };
- req.onerror = function(err) {
- reject(err);
- };
- req.onblocked = function(err) {
- reject(err);
+ reg.addEventListener('updatefound', function () {
+ const update = reg.installing;
+ update.addEventListener('statechange', function () {
+ if (update.state === 'installed') {
+ // It's a new install, claim and perform aggressive caching.
+ if (!reg.active) {
+ update.postMessage('claim');
+ } else {
+ notifyUpdate(update);
+ }
}
-
});
- }
- if (!window.confirm("Are you sure you want to delete all the locally stored files?\nClicking \"OK\" will permanently remove your projects and editor settings!")) {
- return;
- }
- Promise.all([
- deleteDB("/home/web_user"),
- ]).then(function(results) {
- alert("Done.");
- }).catch(function (err) {
- alert("Error deleting local files. Please retry after reloading the page.");
});
- }
-
- function selectVideoMode() {
- var select = document.getElementById('videoMode');
- video_driver = select.selectedOptions[0].value;
- }
-
- var tabs = [
- document.getElementById('tab-loader'),
- document.getElementById('tab-editor'),
- document.getElementById('tab-game')
- ]
- function showTab(name) {
- tabs.forEach(function (elem) {
- if (elem.id == 'tab-' + name) {
- elem.style.display = 'block';
- if (name == 'editor' || name == 'game') {
- const canvas = document.getElementById(name + '-canvas');
- canvas.focus();
- }
- } else {
- elem.style.display = 'none';
- }
- });
- }
-
- function setButtonEnabled(id, enabled) {
- if (enabled) {
- document.getElementById(id).disabled = "";
- } else {
- document.getElementById(id).disabled = "disabled";
+ });
+ }
+
+ const missing = Engine.getMissingFeatures();
+ if (missing.length) {
+ // Display error dialog as threading support is required for the editor.
+ document.getElementById('startButton').disabled = 'disabled';
+ document.getElementById('welcome-modal-description').style.display = 'none';
+ document.getElementById('welcome-modal-missing-description').style.display = 'block';
+ document.getElementById('welcome-modal-dismiss').style.display = 'none';
+ const list = document.getElementById('welcome-modal-missing-list');
+ for (let i = 0; i < missing.length; i++) {
+ const node = document.createElement('li');
+ node.innerText = missing[i];
+ list.appendChild(node);
+ }
+ }
+
+ if (missing.length || localStorage.getItem('welcomeModalDismissed') !== 'true') {
+ document.getElementById('welcome-modal').style.display = 'block';
+ document.getElementById('welcome-modal-dismiss').focus();
+ }
+});
+
+function closeWelcomeModal(dontShowAgain) { // eslint-disable-line no-unused-vars
+ document.getElementById('welcome-modal').style.display = 'none';
+ if (dontShowAgain) {
+ localStorage.setItem('welcomeModalDismissed', 'true');
+ }
+}
+ </script>
+ <script src="godot.editor.js"></script>
+ <script>
+let editor = null;
+let game = null;
+let setStatusMode;
+let setStatusNotice;
+let video_driver = '';
+
+function clearPersistence() { // eslint-disable-line no-unused-vars
+ function deleteDB(path) {
+ return new Promise(function (resolve, reject) {
+ const req = indexedDB.deleteDatabase(path);
+ req.onsuccess = function () {
+ resolve();
+ };
+ req.onerror = function (err) {
+ reject(err);
+ };
+ req.onblocked = function (err) {
+ reject(err);
+ };
+ });
+ }
+ if (!window.confirm('Are you sure you want to delete all the locally stored files?\nClicking "OK" will permanently remove your projects and editor settings!')) {
+ return;
+ }
+ Promise.all([
+ deleteDB('/home/web_user'),
+ ]).then(function (results) {
+ alert('Done.');
+ }).catch(function (err) {
+ alert('Error deleting local files. Please retry after reloading the page.');
+ });
+}
+
+function selectVideoMode() {
+ const select = document.getElementById('videoMode');
+ video_driver = select.selectedOptions[0].value;
+}
+
+const tabs = [
+ document.getElementById('tab-loader'),
+ document.getElementById('tab-editor'),
+ document.getElementById('tab-game'),
+];
+function showTab(name) {
+ tabs.forEach(function (elem) {
+ if (elem.id === `tab-${name}`) {
+ elem.style.display = 'block';
+ if (name === 'editor' || name === 'game') {
+ const canvas = document.getElementById(`${name}-canvas`);
+ canvas.focus();
}
+ } else {
+ elem.style.display = 'none';
+ }
+ });
+}
+
+function setButtonEnabled(id, enabled) {
+ if (enabled) {
+ document.getElementById(id).disabled = '';
+ } else {
+ document.getElementById(id).disabled = 'disabled';
+ }
+}
+
+function setLoaderEnabled(enabled) {
+ setButtonEnabled('btn-tab-loader', enabled);
+ setButtonEnabled('btn-tab-editor', !enabled);
+ setButtonEnabled('btn-close-editor', !enabled);
+}
+
+function setGameTabEnabled(enabled) {
+ setButtonEnabled('btn-tab-game', enabled);
+ setButtonEnabled('btn-close-game', enabled);
+}
+
+function closeGame() {
+ if (game) {
+ game.requestQuit();
+ }
+}
+
+function closeEditor() { // eslint-disable-line no-unused-vars
+ closeGame();
+ if (editor) {
+ editor.requestQuit();
+ }
+}
+
+function startEditor(zip) {
+ const INDETERMINATE_STATUS_STEP_MS = 100;
+ const persistentPaths = ['/home/web_user'];
+
+ let editorCanvas = document.getElementById('editor-canvas');
+ let gameCanvas = document.getElementById('game-canvas');
+ const statusProgress = document.getElementById('status-progress');
+ const statusProgressInner = document.getElementById('status-progress-inner');
+ const statusIndeterminate = document.getElementById('status-indeterminate');
+ const statusNotice = document.getElementById('status-notice');
+ const headerDiv = document.getElementById('tabs-buttons');
+
+ let initializing = true;
+ let statusMode = 'hidden';
+
+ showTab('status');
+
+ let animationCallbacks = [];
+ function animate(time) {
+ animationCallbacks.forEach((callback) => callback(time));
+ requestAnimationFrame(animate);
+ }
+ requestAnimationFrame(animate);
+
+ let lastScale = 0;
+ let lastWidth = 0;
+ let lastHeight = 0;
+ function adjustCanvasDimensions() {
+ const scale = window.devicePixelRatio || 1;
+ const headerHeight = headerDiv.offsetHeight + 1;
+ const width = window.innerWidth;
+ const height = window.innerHeight - headerHeight;
+ if (lastScale !== scale || lastWidth !== width || lastHeight !== height) {
+ editorCanvas.width = width * scale;
+ editorCanvas.height = height * scale;
+ editorCanvas.style.width = `${width}px`;
+ editorCanvas.style.height = `${height}px`;
+ lastScale = scale;
+ lastWidth = width;
+ lastHeight = height;
+ }
+ }
+ animationCallbacks.push(adjustCanvasDimensions);
+ adjustCanvasDimensions();
+
+ function replaceCanvas(from) {
+ const out = document.createElement('canvas');
+ out.id = from.id;
+ out.tabIndex = from.tabIndex;
+ from.parentNode.replaceChild(out, from);
+ lastScale = 0;
+ return out;
+ }
+
+ function animateStatusIndeterminate(ms) {
+ const i = Math.floor((ms / INDETERMINATE_STATUS_STEP_MS) % 8);
+ if (statusIndeterminate.children[i].style.borderTopColor === '') {
+ Array.prototype.slice.call(statusIndeterminate.children).forEach((child) => {
+ child.style.borderTopColor = '';
+ });
+ statusIndeterminate.children[i].style.borderTopColor = '#dfdfdf';
}
+ }
- function setLoaderEnabled(enabled) {
- setButtonEnabled('btn-tab-loader', enabled);
- setButtonEnabled('btn-tab-editor', !enabled);
- setButtonEnabled('btn-close-editor', !enabled);
- }
-
- function setGameTabEnabled(enabled) {
- setButtonEnabled('btn-tab-game', enabled);
- setButtonEnabled('btn-close-game', enabled);
+ setStatusMode = function (mode) {
+ if (statusMode === mode || !initializing) {
+ return;
}
-
- function closeGame() {
+ [statusProgress, statusIndeterminate, statusNotice].forEach((elem) => {
+ elem.style.display = 'none';
+ });
+ animationCallbacks = animationCallbacks.filter(function (value) {
+ return (value !== animateStatusIndeterminate);
+ });
+ switch (mode) {
+ case 'progress':
+ statusProgress.style.display = 'block';
+ break;
+ case 'indeterminate':
+ statusIndeterminate.style.display = 'block';
+ animationCallbacks.push(animateStatusIndeterminate);
+ break;
+ case 'notice':
+ statusNotice.style.display = 'block';
+ break;
+ case 'hidden':
+ break;
+ default:
+ throw new Error('Invalid status mode');
+ }
+ statusMode = mode;
+ };
+
+ setStatusNotice = function (text) {
+ while (statusNotice.lastChild) {
+ statusNotice.removeChild(statusNotice.lastChild);
+ }
+ const lines = text.split('\n');
+ lines.forEach((line) => {
+ statusNotice.appendChild(document.createTextNode(line));
+ statusNotice.appendChild(document.createElement('br'));
+ });
+ };
+
+ const gameConfig = {
+ 'persistentPaths': persistentPaths,
+ 'unloadAfterInit': false,
+ 'canvas': gameCanvas,
+ 'canvasResizePolicy': 1,
+ 'onExit': function () {
+ gameCanvas = replaceCanvas(gameCanvas);
+ setGameTabEnabled(false);
+ showTab('editor');
+ game = null;
+ },
+ };
+
+ let OnEditorExit = function () {
+ showTab('loader');
+ setLoaderEnabled(true);
+ };
+ function Execute(args) {
+ const is_editor = args.filter(function (v) {
+ return v === '--editor' || v === '-e';
+ }).length !== 0;
+ const is_project_manager = args.filter(function (v) {
+ return v === '--project-manager';
+ }).length !== 0;
+ const is_game = !is_editor && !is_project_manager;
+ if (video_driver) {
+ args.push('--rendering-driver', video_driver);
+ }
+
+ if (is_game) {
if (game) {
- game.requestQuit();
- }
- }
-
- function closeEditor() {
- closeGame();
- if (editor) {
- editor.requestQuit();
- }
- }
-
- function startEditor(zip) {
- const INDETERMINATE_STATUS_STEP_MS = 100;
- const persistentPaths = ['/home/web_user'];
-
- var editorCanvas = document.getElementById('editor-canvas');
- var gameCanvas = document.getElementById('game-canvas');
- var statusProgress = document.getElementById('status-progress');
- var statusProgressInner = document.getElementById('status-progress-inner');
- var statusIndeterminate = document.getElementById('status-indeterminate');
- var statusNotice = document.getElementById('status-notice');
- var headerDiv = document.getElementById('tabs-buttons');
-
- var initializing = true;
- var statusMode = 'hidden';
-
- showTab('status');
-
- var animationCallbacks = [];
- function animate(time) {
- animationCallbacks.forEach(callback => callback(time));
- requestAnimationFrame(animate);
- }
- requestAnimationFrame(animate);
-
- var lastScale = 0;
- var lastWidth = 0;
- var lastHeight = 0;
- function adjustCanvasDimensions() {
- var scale = window.devicePixelRatio || 1;
- var headerHeight = headerDiv.offsetHeight + 1;
- var width = window.innerWidth;
- var height = window.innerHeight - headerHeight;
- if (lastScale !== scale || lastWidth !== width || lastHeight !== height) {
- editorCanvas.width = width * scale;
- editorCanvas.height = height * scale;
- editorCanvas.style.width = width + "px";
- editorCanvas.style.height = height + "px";
- lastScale = scale;
- lastWidth = width;
- lastHeight = height;
- }
- }
- animationCallbacks.push(adjustCanvasDimensions);
- adjustCanvasDimensions();
-
- function replaceCanvas(from) {
- const out = document.createElement("canvas");
- out.id = from.id;
- out.tabIndex = from.tabIndex;
- from.parentNode.replaceChild(out, from);
- lastScale = 0;
- return out;
+ console.error('A game is already running. Close it first');
+ return;
}
-
- setStatusMode = function setStatusMode(mode) {
- if (statusMode === mode || !initializing)
- return;
- [statusProgress, statusIndeterminate, statusNotice].forEach(elem => {
- elem.style.display = 'none';
- });
- animationCallbacks = animationCallbacks.filter(function(value) {
- return (value != animateStatusIndeterminate);
- });
- switch (mode) {
- case 'progress':
- statusProgress.style.display = 'block';
- break;
- case 'indeterminate':
- statusIndeterminate.style.display = 'block';
- animationCallbacks.push(animateStatusIndeterminate);
- break;
- case 'notice':
- statusNotice.style.display = 'block';
- break;
- case 'hidden':
- break;
- default:
- throw new Error('Invalid status mode');
- }
- statusMode = mode;
- };
-
- function animateStatusIndeterminate(ms) {
- var i = Math.floor(ms / INDETERMINATE_STATUS_STEP_MS % 8);
- if (statusIndeterminate.children[i].style.borderTopColor == '') {
- Array.prototype.slice.call(statusIndeterminate.children).forEach(child => {
- child.style.borderTopColor = '';
+ setGameTabEnabled(true);
+ game = new Engine(gameConfig);
+ showTab('game');
+ game.init().then(function () {
+ requestAnimationFrame(function () {
+ game.start({ 'args': args, 'canvas': gameCanvas }).then(function () {
+ gameCanvas.focus();
});
- statusIndeterminate.children[i].style.borderTopColor = '#dfdfdf';
- }
- }
-
- setStatusNotice = function setStatusNotice(text) {
- while (statusNotice.lastChild) {
- statusNotice.removeChild(statusNotice.lastChild);
- }
- var lines = text.split('\n');
- lines.forEach((line) => {
- statusNotice.appendChild(document.createTextNode(line));
- statusNotice.appendChild(document.createElement('br'));
});
- };
-
- const gameConfig = {
- 'persistentPaths': persistentPaths,
- 'unloadAfterInit': false,
- 'canvas': gameCanvas,
- 'canvasResizePolicy': 1,
- 'onExit': function () {
- gameCanvas = replaceCanvas(gameCanvas);
- setGameTabEnabled(false);
- showTab('editor');
- game = null;
- },
- };
-
- var OnEditorExit = function () {
- showTab('loader');
+ });
+ } else { // New editor instances will be run in the same canvas. We want to wait for it to exit.
+ OnEditorExit = function (code) {
setLoaderEnabled(true);
- };
- function Execute(args) {
- const is_editor = args.filter(function(v) { return v == '--editor' || v == '-e' }).length != 0;
- const is_project_manager = args.filter(function(v) { return v == '--project-manager' }).length != 0;
- const is_game = !is_editor && !is_project_manager;
- if (video_driver) {
- args.push('--rendering-driver', video_driver);
- }
-
- if (is_game) {
- if (game) {
- console.error("A game is already running. Close it first");
- return;
- }
- setGameTabEnabled(true);
- game = new Engine(gameConfig);
- showTab('game');
- game.init().then(function() {
- requestAnimationFrame(function() {
- game.start({'args': args, 'canvas': gameCanvas}).then(function() {
- gameCanvas.focus();
- });
- });
+ setTimeout(function () {
+ editor.init().then(function () {
+ setLoaderEnabled(false);
+ OnEditorExit = function () {
+ showTab('loader');
+ setLoaderEnabled(true);
+ };
+ editor.start({ 'args': args, 'persistentDrops': is_project_manager, 'canvas': editorCanvas });
});
- } else { // New editor instances will be run in the same canvas. We want to wait for it to exit.
- OnEditorExit = function(code) {
- setLoaderEnabled(true);
- setTimeout(function() {
- editor.init().then(function() {
- setLoaderEnabled(false);
- OnEditorExit = function() {
- showTab('loader');
- setLoaderEnabled(true);
- };
- editor.start({'args': args, 'persistentDrops': is_project_manager, 'canvas': editorCanvas});
- });
- }, 0);
- OnEditorExit = null;
- };
- }
- }
-
- const editorConfig = {
- 'unloadAfterInit': false,
- 'onProgress': function progressFunction (current, total) {
- if (total > 0) {
- statusProgressInner.style.width = current/total * 100 + '%';
- setStatusMode('progress');
- if (current === total) {
- // wait for progress bar animation
- setTimeout(() => {
- setStatusMode('indeterminate');
- }, 100);
- }
- } else {
- setStatusMode('indeterminate');
- }
- },
- 'canvas': editorCanvas,
- 'canvasResizePolicy': 0,
- 'onExit': function() {
- editorCanvas = replaceCanvas(editorCanvas);
- if (OnEditorExit) {
- OnEditorExit();
- }
- },
- 'onExecute': Execute,
- 'persistentPaths': persistentPaths,
+ }, 0);
+ OnEditorExit = null;
};
- editor = new Engine(editorConfig);
-
- function displayFailureNotice(err) {
- var msg = err.message || err;
- console.error(msg);
- setStatusNotice(msg);
- setStatusMode('notice');
- initializing = false;
- };
-
- if (!Engine.isWebGLAvailable()) {
- displayFailureNotice('WebGL not available');
+ }
+ }
+
+ const editorConfig = {
+ 'unloadAfterInit': false,
+ 'onProgress': function progressFunction(current, total) {
+ if (total > 0) {
+ statusProgressInner.style.width = `${(current / total) * 100}%`;
+ setStatusMode('progress');
+ if (current === total) {
+ // wait for progress bar animation
+ setTimeout(() => {
+ setStatusMode('indeterminate');
+ }, 100);
+ }
} else {
setStatusMode('indeterminate');
- editor.init('godot.editor').then(function() {
- if (zip) {
- editor.copyToFS("/tmp/preload.zip", zip);
- }
- try {
- // Avoid user creating project in the persistent root folder.
- editor.copyToFS("/home/web_user/keep", new Uint8Array());
- } catch(e) {
- // File exists
- }
- selectVideoMode();
- showTab('editor');
- setLoaderEnabled(false);
- const args = ['--project-manager', '--single-window'];
- if (video_driver) {
- args.push('--rendering-driver', video_driver);
- }
- editor.start({'args': args, 'persistentDrops': true}).then(function() {
- setStatusMode('hidden');
- initializing = false;
- });
- }).catch(displayFailureNotice);
}
- };
- document.getElementById("startButton").onclick = function() {
- preloadZip(document.getElementById('zip-file')).then(function(zip) {
- startEditor(zip);
+ },
+ 'canvas': editorCanvas,
+ 'canvasResizePolicy': 0,
+ 'onExit': function () {
+ editorCanvas = replaceCanvas(editorCanvas);
+ if (OnEditorExit) {
+ OnEditorExit();
+ }
+ },
+ 'onExecute': Execute,
+ 'persistentPaths': persistentPaths,
+ };
+ editor = new Engine(editorConfig);
+
+ function displayFailureNotice(err) {
+ const msg = err.message || err;
+ console.error(msg);
+ setStatusNotice(msg);
+ setStatusMode('notice');
+ initializing = false;
+ }
+
+ if (!Engine.isWebGLAvailable()) {
+ displayFailureNotice('WebGL not available');
+ } else {
+ setStatusMode('indeterminate');
+ editor.init('godot.editor').then(function () {
+ if (zip) {
+ editor.copyToFS('/tmp/preload.zip', zip);
+ }
+ try {
+ // Avoid user creating project in the persistent root folder.
+ editor.copyToFS('/home/web_user/keep', new Uint8Array());
+ } catch (e) {
+ // File exists
+ }
+ selectVideoMode();
+ showTab('editor');
+ setLoaderEnabled(false);
+ const args = ['--project-manager', '--single-window'];
+ if (video_driver) {
+ args.push('--rendering-driver', video_driver);
+ }
+ editor.start({ 'args': args, 'persistentDrops': true }).then(function () {
+ setStatusMode('hidden');
+ initializing = false;
});
- }
-
- function preloadZip(target) {
- return new Promise(function(resolve, reject) {
- if (target.files.length > 0) {
- target.files[0].arrayBuffer().then(function(data) {
- resolve(data);
- });
- } else {
- resolve();
- }
+ }).catch(displayFailureNotice);
+ }
+}
+
+function preloadZip(target) {
+ return new Promise(function (resolve, reject) {
+ if (target.files.length > 0) {
+ target.files[0].arrayBuffer().then(function (data) {
+ resolve(data);
});
- }
- //]]></script>
-</body>
+ } else {
+ resolve();
+ }
+ });
+}
+
+document.getElementById('startButton').onclick = function () {
+ preloadZip(document.getElementById('zip-file')).then(function (zip) {
+ startEditor(zip);
+ });
+};
+ </script>
+ </body>
</html>
diff --git a/misc/dist/html/full-size.html b/misc/dist/html/full-size.html
index d5b0050cfd..6ae3e5cc73 100644
--- a/misc/dist/html/full-size.html
+++ b/misc/dist/html/full-size.html
@@ -1,247 +1,245 @@
<!DOCTYPE html>
-<html xmlns='https://www.w3.org/1999/xhtml' lang='' xml:lang=''>
-<head>
- <meta charset='utf-8' />
- <meta name='viewport' content='width=device-width, user-scalable=no' />
- <title>$GODOT_PROJECT_NAME</title>
- <style type='text/css'>
-
- body {
- touch-action: none;
- margin: 0;
- border: 0 none;
- padding: 0;
- text-align: center;
- background-color: black;
- }
-
- #canvas {
- display: block;
- margin: 0;
- color: white;
- }
-
- #canvas:focus {
- outline: none;
- }
-
- .godot {
- font-family: 'Noto Sans', 'Droid Sans', Arial, sans-serif;
- color: #e0e0e0;
- background-color: #3b3943;
- background-image: linear-gradient(to bottom, #403e48, #35333c);
- border: 1px solid #45434e;
- box-shadow: 0 0 1px 1px #2f2d35;
- }
-
-
- /* Status display
- * ============== */
-
- #status {
- position: absolute;
- left: 0;
- top: 0;
- right: 0;
- bottom: 0;
- display: flex;
- justify-content: center;
- align-items: center;
- /* don't consume click events - make children visible explicitly */
- visibility: hidden;
- }
-
- #status-progress {
- width: 366px;
- height: 7px;
- background-color: #38363A;
- border: 1px solid #444246;
- padding: 1px;
- box-shadow: 0 0 2px 1px #1B1C22;
- border-radius: 2px;
- visibility: visible;
- }
-
- @media only screen and (orientation:portrait) {
- #status-progress {
- width: 61.8%;
- }
- }
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, user-scalable=no">
+ <title>$GODOT_PROJECT_NAME</title>
+ <style>
+body {
+ touch-action: none;
+ margin: 0;
+ border: 0 none;
+ padding: 0;
+ text-align: center;
+ background-color: black;
+}
+
+#canvas {
+ display: block;
+ margin: 0;
+ color: white;
+}
+
+#canvas:focus {
+ outline: none;
+}
+
+.godot {
+ font-family: 'Noto Sans', 'Droid Sans', Arial, sans-serif;
+ color: #e0e0e0;
+ background-color: #3b3943;
+ background-image: linear-gradient(to bottom, #403e48, #35333c);
+ border: 1px solid #45434e;
+ box-shadow: 0 0 1px 1px #2f2d35;
+}
+
+/* Status display */
+
+#status {
+ position: absolute;
+ left: 0;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ /* don't consume click events - make children visible explicitly */
+ visibility: hidden;
+}
+
+#status-progress {
+ width: 366px;
+ height: 7px;
+ background-color: #38363A;
+ border: 1px solid #444246;
+ padding: 1px;
+ box-shadow: 0 0 2px 1px #1B1C22;
+ border-radius: 2px;
+ visibility: visible;
+}
+
+@media only screen and (orientation:portrait) {
+ #status-progress {
+ width: 61.8%;
+ }
+}
+
+#status-progress-inner {
+ height: 100%;
+ width: 0;
+ box-sizing: border-box;
+ transition: width 0.5s linear;
+ background-color: #202020;
+ border: 1px solid #222223;
+ box-shadow: 0 0 1px 1px #27282E;
+ border-radius: 3px;
+}
+
+#status-indeterminate {
+ height: 42px;
+ visibility: visible;
+ position: relative;
+}
+
+#status-indeterminate > div {
+ width: 4.5px;
+ height: 0;
+ border-style: solid;
+ border-width: 9px 3px 0 3px;
+ border-color: #2b2b2b transparent transparent transparent;
+ transform-origin: center 21px;
+ position: absolute;
+}
+
+#status-indeterminate > div:nth-child(1) { transform: rotate( 22.5deg); }
+#status-indeterminate > div:nth-child(2) { transform: rotate( 67.5deg); }
+#status-indeterminate > div:nth-child(3) { transform: rotate(112.5deg); }
+#status-indeterminate > div:nth-child(4) { transform: rotate(157.5deg); }
+#status-indeterminate > div:nth-child(5) { transform: rotate(202.5deg); }
+#status-indeterminate > div:nth-child(6) { transform: rotate(247.5deg); }
+#status-indeterminate > div:nth-child(7) { transform: rotate(292.5deg); }
+#status-indeterminate > div:nth-child(8) { transform: rotate(337.5deg); }
+
+#status-notice {
+ margin: 0 100px;
+ line-height: 1.3;
+ visibility: visible;
+ padding: 4px 6px;
+ visibility: visible;
+}
+ </style>
+ $GODOT_HEAD_INCLUDE
+ </head>
+ <body>
+ <canvas id="canvas">
+ HTML5 canvas appears to be unsupported in the current browser.<br >
+ Please try updating or use a different browser.
+ </canvas>
+ <div id="status">
+ <div id="status-progress" style="display: none;" oncontextmenu="event.preventDefault();">
+ <div id ="status-progress-inner"></div>
+ </div>
+ <div id="status-indeterminate" style="display: none;" oncontextmenu="event.preventDefault();">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ </div>
+ <div id="status-notice" class="godot" style="display: none;"></div>
+ </div>
- #status-progress-inner {
- height: 100%;
- width: 0;
- box-sizing: border-box;
- transition: width 0.5s linear;
- background-color: #202020;
- border: 1px solid #222223;
- box-shadow: 0 0 1px 1px #27282E;
- border-radius: 3px;
+ <script src="$GODOT_URL"></script>
+ <script>
+const GODOT_CONFIG = $GODOT_CONFIG;
+const engine = new Engine(GODOT_CONFIG);
+
+(function () {
+ const INDETERMINATE_STATUS_STEP_MS = 100;
+ const statusProgress = document.getElementById('status-progress');
+ const statusProgressInner = document.getElementById('status-progress-inner');
+ const statusIndeterminate = document.getElementById('status-indeterminate');
+ const statusNotice = document.getElementById('status-notice');
+
+ let initializing = true;
+ let statusMode = 'hidden';
+
+ let animationCallbacks = [];
+ function animate(time) {
+ animationCallbacks.forEach((callback) => callback(time));
+ requestAnimationFrame(animate);
+ }
+ requestAnimationFrame(animate);
+
+ function animateStatusIndeterminate(ms) {
+ const i = Math.floor((ms / INDETERMINATE_STATUS_STEP_MS) % 8);
+ if (statusIndeterminate.children[i].style.borderTopColor === '') {
+ Array.prototype.slice.call(statusIndeterminate.children).forEach((child) => {
+ child.style.borderTopColor = '';
+ });
+ statusIndeterminate.children[i].style.borderTopColor = '#dfdfdf';
}
+ }
- #status-indeterminate {
- height: 42px;
- visibility: visible;
- position: relative;
+ function setStatusMode(mode) {
+ if (statusMode === mode || !initializing) {
+ return;
}
-
- #status-indeterminate > div {
- width: 4.5px;
- height: 0;
- border-style: solid;
- border-width: 9px 3px 0 3px;
- border-color: #2b2b2b transparent transparent transparent;
- transform-origin: center 21px;
- position: absolute;
+ [statusProgress, statusIndeterminate, statusNotice].forEach((elem) => {
+ elem.style.display = 'none';
+ });
+ animationCallbacks = animationCallbacks.filter(function (value) {
+ return (value !== animateStatusIndeterminate);
+ });
+ switch (mode) {
+ case 'progress':
+ statusProgress.style.display = 'block';
+ break;
+ case 'indeterminate':
+ statusIndeterminate.style.display = 'block';
+ animationCallbacks.push(animateStatusIndeterminate);
+ break;
+ case 'notice':
+ statusNotice.style.display = 'block';
+ break;
+ case 'hidden':
+ break;
+ default:
+ throw new Error('Invalid status mode');
}
+ statusMode = mode;
+ }
- #status-indeterminate > div:nth-child(1) { transform: rotate( 22.5deg); }
- #status-indeterminate > div:nth-child(2) { transform: rotate( 67.5deg); }
- #status-indeterminate > div:nth-child(3) { transform: rotate(112.5deg); }
- #status-indeterminate > div:nth-child(4) { transform: rotate(157.5deg); }
- #status-indeterminate > div:nth-child(5) { transform: rotate(202.5deg); }
- #status-indeterminate > div:nth-child(6) { transform: rotate(247.5deg); }
- #status-indeterminate > div:nth-child(7) { transform: rotate(292.5deg); }
- #status-indeterminate > div:nth-child(8) { transform: rotate(337.5deg); }
-
- #status-notice {
- margin: 0 100px;
- line-height: 1.3;
- visibility: visible;
- padding: 4px 6px;
- visibility: visible;
+ function setStatusNotice(text) {
+ while (statusNotice.lastChild) {
+ statusNotice.removeChild(statusNotice.lastChild);
}
- </style>
-$GODOT_HEAD_INCLUDE
-</head>
-<body>
- <canvas id='canvas'>
- HTML5 canvas appears to be unsupported in the current browser.<br />
- Please try updating or use a different browser.
- </canvas>
- <div id='status'>
- <div id='status-progress' style='display: none;' oncontextmenu='event.preventDefault();'><div id ='status-progress-inner'></div></div>
- <div id='status-indeterminate' style='display: none;' oncontextmenu='event.preventDefault();'>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- <div></div>
- </div>
- <div id='status-notice' class='godot' style='display: none;'></div>
- </div>
-
- <script type='text/javascript' src='$GODOT_URL'></script>
- <script type='text/javascript'>//<![CDATA[
-
- const GODOT_CONFIG = $GODOT_CONFIG;
- var engine = new Engine(GODOT_CONFIG);
-
- (function() {
- const INDETERMINATE_STATUS_STEP_MS = 100;
- var statusProgress = document.getElementById('status-progress');
- var statusProgressInner = document.getElementById('status-progress-inner');
- var statusIndeterminate = document.getElementById('status-indeterminate');
- var statusNotice = document.getElementById('status-notice');
-
- var initializing = true;
- var statusMode = 'hidden';
-
- var animationCallbacks = [];
- function animate(time) {
- animationCallbacks.forEach(callback => callback(time));
- requestAnimationFrame(animate);
- }
- requestAnimationFrame(animate);
-
- function setStatusMode(mode) {
-
- if (statusMode === mode || !initializing)
- return;
- [statusProgress, statusIndeterminate, statusNotice].forEach(elem => {
- elem.style.display = 'none';
- });
- animationCallbacks = animationCallbacks.filter(function(value) {
- return (value != animateStatusIndeterminate);
- });
- switch (mode) {
- case 'progress':
- statusProgress.style.display = 'block';
- break;
- case 'indeterminate':
- statusIndeterminate.style.display = 'block';
- animationCallbacks.push(animateStatusIndeterminate);
- break;
- case 'notice':
- statusNotice.style.display = 'block';
- break;
- case 'hidden':
- break;
- default:
- throw new Error('Invalid status mode');
- }
- statusMode = mode;
- }
-
- function animateStatusIndeterminate(ms) {
- var i = Math.floor(ms / INDETERMINATE_STATUS_STEP_MS % 8);
- if (statusIndeterminate.children[i].style.borderTopColor == '') {
- Array.prototype.slice.call(statusIndeterminate.children).forEach(child => {
- child.style.borderTopColor = '';
- });
- statusIndeterminate.children[i].style.borderTopColor = '#dfdfdf';
- }
- }
-
- function setStatusNotice(text) {
- while (statusNotice.lastChild) {
- statusNotice.removeChild(statusNotice.lastChild);
- }
- var lines = text.split('\n');
- lines.forEach((line) => {
- statusNotice.appendChild(document.createTextNode(line));
- statusNotice.appendChild(document.createElement('br'));
- });
- };
-
- function displayFailureNotice(err) {
- var msg = err.message || err;
- console.error(msg);
- setStatusNotice(msg);
- setStatusMode('notice');
- initializing = false;
- };
-
- const missing = Engine.getMissingFeatures();
- if (missing.length !== 0) {
- const missingMsg = 'Warning!\nThe following features required to run Godot projects on the Web are missing:\n';
- displayFailureNotice(missingMsg + missing.join("\n"));
- } else {
- setStatusMode('indeterminate');
- engine.startGame({
- 'onProgress': function (current, total) {
- if (total > 0) {
- statusProgressInner.style.width = current/total * 100 + '%';
- setStatusMode('progress');
- if (current === total) {
- // wait for progress bar animation
- setTimeout(() => {
- setStatusMode('indeterminate');
- }, 500);
- }
- } else {
+ const lines = text.split('\n');
+ lines.forEach((line) => {
+ statusNotice.appendChild(document.createTextNode(line));
+ statusNotice.appendChild(document.createElement('br'));
+ });
+ }
+
+ function displayFailureNotice(err) {
+ const msg = err.message || err;
+ console.error(msg);
+ setStatusNotice(msg);
+ setStatusMode('notice');
+ initializing = false;
+ }
+
+ const missing = Engine.getMissingFeatures();
+ if (missing.length !== 0) {
+ const missingMsg = 'Warning!\nThe following features required to run Godot projects on the Web are missing:\n';
+ displayFailureNotice(missingMsg + missing.join('\n'));
+ } else {
+ setStatusMode('indeterminate');
+ engine.startGame({
+ 'onProgress': function (current, total) {
+ if (total > 0) {
+ statusProgressInner.style.width = `${(current / total) * 100}%`;
+ setStatusMode('progress');
+ if (current === total) {
+ // wait for progress bar animation
+ setTimeout(() => {
setStatusMode('indeterminate');
- }
- },
- }).then(() => {
- setStatusMode('hidden');
- initializing = false;
- }, displayFailureNotice);
- }
- })();
- //]]></script>
-</body>
+ }, 500);
+ }
+ } else {
+ setStatusMode('indeterminate');
+ }
+ },
+ }).then(() => {
+ setStatusMode('hidden');
+ initializing = false;
+ }, displayFailureNotice);
+ }
+}());
+ </script>
+ </body>
</html>
diff --git a/misc/dist/html/offline-export.html b/misc/dist/html/offline-export.html
index 41ab42b04b..ae5298ae46 100644
--- a/misc/dist/html/offline-export.html
+++ b/misc/dist/html/offline-export.html
@@ -1,42 +1,41 @@
<!DOCTYPE html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>You are offline</title>
- <style>
- html {
- background-color: #000000;
- color: #ffffff;
- }
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>You are offline</title>
+ <style>
+html {
+ background-color: #000000;
+ color: #ffffff;
+}
- body {
- font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
- margin: 2rem;
- }
+body {
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
+ margin: 2rem;
+}
- p {
- margin-block: 1rem;
- }
+p {
+ margin-block: 1rem;
+}
- button {
- display: block;
- padding: 1rem 2rem;
- margin: 3rem auto 0;
- }
- </style>
-</head>
-<body>
- <h1>You are offline</h1>
- <p>This application requires an Internet connection to run for the first time.</p>
- <p>Press the button below to try reloading:</p>
- <button type="button">Reload</button>
-
- <script>
- document.querySelector("button").addEventListener("click", () => {
- window.location.reload();
- });
- </script>
-</body>
+button {
+ display: block;
+ padding: 1rem 2rem;
+ margin: 3rem auto 0;
+}
+ </style>
+ </head>
+ <body>
+ <h1>You are offline</h1>
+ <p>This application requires an Internet connection to run for the first time.</p>
+ <p>Press the button below to try reloading:</p>
+ <button type="button">Reload</button>
+ <script>
+document.querySelector('button').addEventListener('click', () => {
+ window.location.reload();
+});
+ </script>
+ </body>
</html>
diff --git a/misc/dist/html/offline.html b/misc/dist/html/offline.html
index 5cfc3362d9..123181e3e0 100644
--- a/misc/dist/html/offline.html
+++ b/misc/dist/html/offline.html
@@ -1,44 +1,44 @@
<!DOCTYPE html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#202531" />
- <meta name="msapplication-navbutton-color" content="#202531" />
- <title>You are offline</title>
- <style>
- html {
- background-color: #333b4f;
- color: #e0e0e0;
- }
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#202531">
+ <meta name="msapplication-navbutton-color" content="#202531">
+ <title>You are offline</title>
+ <style>
+html {
+ background-color: #333b4f;
+ color: #e0e0e0;
+}
- body {
- font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
- margin: 2rem;
- }
+body {
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
+ margin: 2rem;
+}
- p {
- margin-block: 1rem;
- }
+p {
+ margin-block: 1rem;
+}
- button {
- display: block;
- padding: 1rem 2rem;
- margin: 3rem auto 0;
- }
- </style>
-</head>
-<body>
- <h1>You are offline</h1>
- <p>This application requires an Internet connection to run for the first time.</p>
- <p>Press the button below to try reloading:</p>
- <button type="button">Reload</button>
+button {
+ display: block;
+ padding: 1rem 2rem;
+ margin: 3rem auto 0;
+}
+ </style>
+ </head>
+ <body>
+ <h1>You are offline</h1>
+ <p>This application requires an Internet connection to run for the first time.</p>
+ <p>Press the button below to try reloading:</p>
+ <button type="button">Reload</button>
- <script>
- document.querySelector("button").addEventListener("click", () => {
- window.location.reload();
- });
- </script>
-</body>
+ <script>
+document.querySelector('button').addEventListener('click', () => {
+ window.location.reload();
+});
+ </script>
+ </body>
</html>
diff --git a/misc/scripts/dotnet_format.sh b/misc/scripts/dotnet_format.sh
index 645737f419..cc34137a37 100755
--- a/misc/scripts/dotnet_format.sh
+++ b/misc/scripts/dotnet_format.sh
@@ -5,6 +5,13 @@
set -uo pipefail
+# Create dummy generated files.
+echo "<Project />" > modules/mono/SdkPackageVersions.props
+mkdir -p modules/mono/glue/GodotSharp/GodotSharp/Generated
+echo "<Project />" > modules/mono/glue/GodotSharp/GodotSharp/Generated/GeneratedIncludes.props
+mkdir -p modules/mono/glue/GodotSharp/GodotSharpEditor/Generated
+echo "<Project />" > modules/mono/glue/GodotSharp/GodotSharpEditor/Generated/GeneratedIncludes.props
+
# Loops through all C# projects tracked by Git.
git ls-files -- '*.csproj' \
':!:.git/*' ':!:thirdparty/*' ':!:platform/android/java/lib/src/com/google/*' ':!:*-so_wrap.*' |
diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp
index e80d453df7..155f7809b0 100644
--- a/modules/basis_universal/register_types.cpp
+++ b/modules/basis_universal/register_types.cpp
@@ -253,7 +253,7 @@ static Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size
};
image.instantiate();
- image->create(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata);
+ image->set_data(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata);
return image;
}
diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp
index cc21ed28e8..681b3e74bc 100644
--- a/modules/bmp/image_loader_bmp.cpp
+++ b/modules/bmp/image_loader_bmp.cpp
@@ -156,7 +156,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
if (p_color_buffer == nullptr || color_table_size == 0) { // regular pixels
- p_image->create(width, height, false, Image::FORMAT_RGBA8, data);
+ p_image->set_data(width, height, false, Image::FORMAT_RGBA8, data);
} else { // data is in indexed format, extend it
@@ -194,7 +194,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
dest += 4;
}
- p_image->create(width, height, false, Image::FORMAT_RGBA8, extended_data);
+ p_image->set_data(width, height, false, Image::FORMAT_RGBA8, extended_data);
}
}
return err;
diff --git a/modules/camera/camera_macos.mm b/modules/camera/camera_macos.mm
index 0b9696a3e9..0e61dde8e9 100644
--- a/modules/camera/camera_macos.mm
+++ b/modules/camera/camera_macos.mm
@@ -158,7 +158,7 @@
memcpy(w, dataY, new_width * new_height);
img[0].instantiate();
- img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
+ img[0]->set_data(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
}
{
@@ -177,7 +177,7 @@
///TODO OpenGL doesn't support FORMAT_RG8, need to do some form of conversion
img[1].instantiate();
- img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
+ img[1]->set_data(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
}
// set our texture...
diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml
index 7e92d667b3..06f8f5a403 100644
--- a/modules/csg/doc_classes/CSGShape3D.xml
+++ b/modules/csg/doc_classes/CSGShape3D.xml
@@ -64,9 +64,10 @@
A contact is detected if object A is in any of the layers that object B scans, or object B is in any layer scanned by object A. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
<member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1">
- The physics layers this CSG shape scans for collisions. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
+ The physics layers this CSG shape scans for collisions. Only effective if [member use_collision] is [code]true[/code]. See [url=$DOCS_URL/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
<member name="collision_priority" type="float" setter="set_collision_priority" getter="get_collision_priority" default="1.0">
+ The priority used to solve colliding when occurring penetration. Only effective if [member use_collision] is [code]true[/code]. The higher the priority is, the lower the penetration into the object will be. This can for example be used to prevent the player from breaking through the boundaries of a level.
</member>
<member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape3D.Operation" default="0">
The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent.
@@ -75,7 +76,7 @@
Snap makes the mesh snap to a given distance so that the faces of two meshes can be perfectly aligned. A lower value results in greater precision but may be harder to adjust.
</member>
<member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision" default="false">
- Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden.
+ Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden. See also [member collision_mask] and [member collision_priority].
</member>
</members>
<constants>
diff --git a/modules/cvtt/image_compress_cvtt.cpp b/modules/cvtt/image_compress_cvtt.cpp
index 3322ff0a1b..89705e4ee0 100644
--- a/modules/cvtt/image_compress_cvtt.cpp
+++ b/modules/cvtt/image_compress_cvtt.cpp
@@ -230,7 +230,7 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChann
h = MAX(h / 2, 1);
}
- p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
+ p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
}
void image_decompress_cvtt(Image *p_image) {
@@ -339,5 +339,5 @@ void image_decompress_cvtt(Image *p_image) {
w >>= 1;
h >>= 1;
}
- p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
+ p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
}
diff --git a/modules/denoise/lightmap_denoiser.cpp b/modules/denoise/lightmap_denoiser.cpp
index a0dbd07b10..2b9221bc43 100644
--- a/modules/denoise/lightmap_denoiser.cpp
+++ b/modules/denoise/lightmap_denoiser.cpp
@@ -51,7 +51,7 @@ Ref<Image> LightmapDenoiserOIDN::denoise_image(const Ref<Image> &p_image) {
return p_image;
}
- img->create(img->get_width(), img->get_height(), false, img->get_format(), data);
+ img->set_data(img->get_width(), img->get_height(), false, img->get_format(), data);
return img;
}
diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml
index 5181ae76ce..f02fc893fd 100644
--- a/modules/enet/doc_classes/ENetMultiplayerPeer.xml
+++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml
@@ -77,8 +77,5 @@
<member name="host" type="ENetConnection" setter="" getter="get_host">
The underlying [ENetConnection] created after [method create_client] and [method create_server].
</member>
- <member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true">
- Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server.
- </member>
</members>
</class>
diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp
index e7728f4aec..c93db3b972 100644
--- a/modules/enet/enet_multiplayer_peer.cpp
+++ b/modules/enet/enet_multiplayer_peer.cpp
@@ -44,6 +44,22 @@ int ENetMultiplayerPeer::get_packet_peer() const {
return incoming_packets.front()->get().from;
}
+MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_packet_mode() const {
+ ERR_FAIL_COND_V_MSG(!_is_active(), TRANSFER_MODE_RELIABLE, "The multiplayer instance isn't currently active.");
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, TRANSFER_MODE_RELIABLE);
+ return incoming_packets.front()->get().transfer_mode;
+}
+
+int ENetMultiplayerPeer::get_packet_channel() const {
+ ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
+ int ch = incoming_packets.front()->get().channel;
+ if (ch >= SYSCH_MAX) { // First 2 channels are reserved.
+ return ch - SYSCH_MAX + 1;
+ }
+ return 0;
+}
+
Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
set_refuse_new_connections(false);
@@ -114,6 +130,22 @@ Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {
return OK;
}
+void ENetMultiplayerPeer::_store_packet(int32_t p_source, ENetConnection::Event &p_event) {
+ Packet packet;
+ packet.packet = p_event.packet;
+ packet.channel = p_event.channel_id;
+ packet.from = p_source;
+ if (p_event.packet->flags & ENET_PACKET_FLAG_RELIABLE) {
+ packet.transfer_mode = TRANSFER_MODE_RELIABLE;
+ } else if (p_event.packet->flags & ENET_PACKET_FLAG_UNSEQUENCED) {
+ packet.transfer_mode = TRANSFER_MODE_UNRELIABLE;
+ } else {
+ packet.transfer_mode = TRANSFER_MODE_UNRELIABLE_ORDERED;
+ }
+ packet.packet->referenceCount++;
+ incoming_packets.push_back(packet);
+}
+
bool ENetMultiplayerPeer::_parse_server_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event) {
switch (p_type) {
case ENetConnection::EVENT_CONNECT: {
@@ -131,9 +163,6 @@ bool ENetMultiplayerPeer::_parse_server_event(ENetConnection::EventType p_type,
peers[id] = p_event.peer;
emit_signal(SNAME("peer_connected"), id);
- if (server_relay) {
- _notify_peers(id, true);
- }
return false;
}
case ENetConnection::EVENT_DISCONNECT: {
@@ -145,50 +174,11 @@ bool ENetMultiplayerPeer::_parse_server_event(ENetConnection::EventType p_type,
emit_signal(SNAME("peer_disconnected"), id);
peers.erase(id);
- if (server_relay) {
- _notify_peers(id, false);
- }
return false;
}
case ENetConnection::EVENT_RECEIVE: {
- if (p_event.channel_id == SYSCH_CONFIG) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V_MSG(false, "Only server can send config messages");
- } else {
- if (p_event.packet->dataLength < 8) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V_MSG(false, "Invalid packet size");
- }
-
- uint32_t source = decode_uint32(&p_event.packet->data[0]);
- int target = decode_uint32(&p_event.packet->data[4]);
-
- uint32_t id = p_event.peer->get_meta(SNAME("_net_id"));
- // Someone is cheating and trying to fake the source!
- if (source != id) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!");
- }
-
- Packet packet;
- packet.packet = p_event.packet;
- packet.channel = p_event.channel_id;
- packet.from = id;
-
- // Even if relaying is disabled, these targets are valid as incoming packets.
- if (target == 1 || target == 0 || target < -1) {
- packet.packet->referenceCount++;
- incoming_packets.push_back(packet);
- }
-
- if (server_relay && target != 1) {
- packet.packet->referenceCount++;
- _relay(source, target, p_event.channel_id, p_event.packet);
- packet.packet->referenceCount--;
- _destroy_unused(p_event.packet);
- }
- // Destroy packet later
- }
+ int32_t source = p_event.peer->get_meta(SNAME("_net_id"));
+ _store_packet(source, p_event);
return false;
}
default:
@@ -215,44 +205,7 @@ bool ENetMultiplayerPeer::_parse_client_event(ENetConnection::EventType p_type,
return true;
}
case ENetConnection::EVENT_RECEIVE: {
- if (p_event.channel_id == SYSCH_CONFIG) {
- // Config message
- if (p_event.packet->dataLength != 8) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V(false);
- }
-
- int msg = decode_uint32(&p_event.packet->data[0]);
- int id = decode_uint32(&p_event.packet->data[4]);
-
- switch (msg) {
- case SYSMSG_ADD_PEER: {
- peers[id] = Ref<ENetPacketPeer>();
- emit_signal(SNAME("peer_connected"), id);
-
- } break;
- case SYSMSG_REMOVE_PEER: {
- peers.erase(id);
- emit_signal(SNAME("peer_disconnected"), id);
- } break;
- }
- _destroy_unused(p_event.packet);
- } else {
- if (p_event.packet->dataLength < 8) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V_MSG(false, "Invalid packet size");
- }
-
- uint32_t source = decode_uint32(&p_event.packet->data[0]);
- Packet packet;
- packet.packet = p_event.packet;
- packet.from = source;
- packet.channel = p_event.channel_id;
-
- packet.packet->referenceCount++;
- incoming_packets.push_back(packet);
- // Destroy packet later
- }
+ _store_packet(1, p_event);
return false;
}
default:
@@ -273,18 +226,7 @@ bool ENetMultiplayerPeer::_parse_mesh_event(ENetConnection::EventType p_type, EN
hosts.erase(p_peer_id);
return true;
case ENetConnection::EVENT_RECEIVE: {
- if (p_event.packet->dataLength < 8) {
- _destroy_unused(p_event.packet);
- ERR_FAIL_V_MSG(false, "Invalid packet size");
- }
-
- Packet packet;
- packet.packet = p_event.packet;
- packet.from = p_peer_id;
- packet.channel = p_event.channel_id;
-
- packet.packet->referenceCount++;
- incoming_packets.push_back(packet);
+ _store_packet(p_peer_id, p_event);
return false;
} break;
default:
@@ -376,6 +318,10 @@ bool ENetMultiplayerPeer::is_server() const {
return active_mode == MODE_SERVER;
}
+bool ENetMultiplayerPeer::is_server_relay_supported() const {
+ return active_mode == MODE_SERVER || active_mode == MODE_CLIENT;
+}
+
void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) {
if (!_is_active()) {
return;
@@ -422,8 +368,8 @@ Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_si
current_packet = incoming_packets.front()->get();
incoming_packets.pop_front();
- *r_buffer = (const uint8_t *)(&current_packet.packet->data[8]);
- r_buffer_size = current_packet.packet->dataLength - 8;
+ *r_buffer = (const uint8_t *)(current_packet.packet->data);
+ r_buffer_size = current_packet.packet->dataLength;
return OK;
}
@@ -457,15 +403,13 @@ Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size
}
#ifdef DEBUG_ENABLED
- if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size + 8 > ENET_HOST_DEFAULT_MTU) {
- WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size + 8, ENET_HOST_DEFAULT_MTU));
+ if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size > ENET_HOST_DEFAULT_MTU) {
+ WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size, ENET_HOST_DEFAULT_MTU));
}
#endif
- ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags);
- encode_uint32(unique_id, &packet->data[0]); // Source ID
- encode_uint32(target_peer, &packet->data[4]); // Dest ID
- memcpy(&packet->data[8], p_buffer, p_buffer_size);
+ ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size, packet_flags);
+ memcpy(&packet->data[0], p_buffer, p_buffer_size);
if (is_server()) {
if (target_peer == 0) {
@@ -548,16 +492,6 @@ void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {
MultiplayerPeer::set_refuse_new_connections(p_enabled);
}
-void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) {
- ERR_FAIL_COND_MSG(_is_active(), "Server relaying can't be toggled while the multiplayer instance is active.");
-
- server_relay = p_enabled;
-}
-
-bool ENetMultiplayerPeer::is_server_relay_enabled() const {
- return server_relay;
-}
-
Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {
ERR_FAIL_COND_V(!_is_active(), nullptr);
ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);
@@ -577,70 +511,6 @@ void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {
}
}
-void ENetMultiplayerPeer::_relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet) {
- if (p_to == 0) {
- // Re-send to everyone but sender :|
- for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
- if (E.key == p_from) {
- continue;
- }
-
- E.value->send(p_channel, p_packet);
- }
- } else if (p_to < 0) {
- // Re-send to everyone but excluded and sender.
- for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
- if (E.key == p_from || E.key == -p_to) { // Do not resend to self, also do not send to excluded
- continue;
- }
-
- E.value->send(p_channel, p_packet);
- }
- } else {
- // To someone else, specifically
- ERR_FAIL_COND(!peers.has(p_to));
- ENetPacket *packet = enet_packet_create(p_packet->data, p_packet->dataLength, p_packet->flags);
- peers[p_to]->send(p_channel, packet);
- }
-}
-
-void ENetMultiplayerPeer::_notify_peers(int p_id, bool p_connected) {
- if (p_connected) {
- ERR_FAIL_COND(!peers.has(p_id));
- // Someone connected, notify all the peers available.
- Ref<ENetPacketPeer> peer = peers[p_id];
- ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
- encode_uint32(p_id, &packet->data[4]);
- for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
- if (E.key == p_id) {
- continue;
- }
- // Send new peer to existing peer.
- E.value->send(SYSCH_CONFIG, packet);
- // Send existing peer to new peer.
- // This packet will be automatically destroyed by ENet after send.
- ENetPacket *packet2 = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_ADD_PEER, &packet2->data[0]);
- encode_uint32(E.key, &packet2->data[4]);
- peer->send(SYSCH_CONFIG, packet2);
- }
- _destroy_unused(packet);
- } else {
- // Server just received a client disconnect and is in relay mode, notify everyone else.
- ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
- encode_uint32(p_id, &packet->data[4]);
- for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
- if (E.key == p_id) {
- continue;
- }
- E.value->send(SYSCH_CONFIG, packet);
- }
- _destroy_unused(packet);
- }
-}
-
void ENetMultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0));
@@ -649,12 +519,9 @@ void ENetMultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &ENetMultiplayerPeer::close_connection, DEFVAL(100));
ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);
- ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &ENetMultiplayerPeer::set_server_relay_enabled);
- ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &ENetMultiplayerPeer::is_server_relay_enabled);
ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);
ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");
}
diff --git a/modules/enet/enet_multiplayer_peer.h b/modules/enet/enet_multiplayer_peer.h
index 3152068d46..85692e8eee 100644
--- a/modules/enet/enet_multiplayer_peer.h
+++ b/modules/enet/enet_multiplayer_peer.h
@@ -47,10 +47,9 @@ private:
};
enum {
- SYSCH_CONFIG = 0,
- SYSCH_RELIABLE = 1,
- SYSCH_UNRELIABLE = 2,
- SYSCH_MAX = 3
+ SYSCH_RELIABLE = 0,
+ SYSCH_UNRELIABLE = 1,
+ SYSCH_MAX = 2
};
enum Mode {
@@ -66,8 +65,6 @@ private:
int target_peer = 0;
- bool server_relay = true;
-
ConnectionStatus connection_status = CONNECTION_DISCONNECTED;
HashMap<int, Ref<ENetConnection>> hosts;
@@ -77,18 +74,18 @@ private:
ENetPacket *packet = nullptr;
int from = 0;
int channel = 0;
+ TransferMode transfer_mode = TRANSFER_MODE_RELIABLE;
};
List<Packet> incoming_packets;
Packet current_packet;
+ void _store_packet(int32_t p_source, ENetConnection::Event &p_event);
void _pop_current_packet();
bool _parse_server_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event);
bool _parse_client_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event);
bool _parse_mesh_event(ENetConnection::EventType p_event_type, ENetConnection::Event &p_event, int p_peer_id);
- void _relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet);
- void _notify_peers(int p_id, bool p_connected);
void _destroy_unused(ENetPacket *p_packet);
_FORCE_INLINE_ bool _is_active() const { return active_mode != MODE_NONE; }
@@ -99,10 +96,15 @@ protected:
public:
virtual void set_target_peer(int p_peer) override;
+
virtual int get_packet_peer() const override;
+ virtual TransferMode get_packet_mode() const override;
+ virtual int get_packet_channel() const override;
virtual void poll() override;
virtual bool is_server() const override;
+ virtual bool is_server_relay_supported() const override;
+
// Overridden so we can instrument the DTLSServer when needed.
virtual void set_refuse_new_connections(bool p_enabled) override;
@@ -125,8 +127,6 @@ public:
void disconnect_peer(int p_peer, bool now = false);
void set_bind_ip(const IPAddress &p_ip);
- void set_server_relay_enabled(bool p_enabled);
- bool is_server_relay_enabled() const;
Ref<ENetConnection> get_host() const;
Ref<ENetPacketPeer> get_peer(int p_id) const;
diff --git a/modules/etcpak/image_compress_etcpak.cpp b/modules/etcpak/image_compress_etcpak.cpp
index 7d5557d197..3d66b27556 100644
--- a/modules/etcpak/image_compress_etcpak.cpp
+++ b/modules/etcpak/image_compress_etcpak.cpp
@@ -233,7 +233,7 @@ void _compress_etcpak(EtcpakType p_compresstype, Image *r_img, float p_lossy_qua
}
// Replace original image with compressed one.
- r_img->create(width, height, mipmaps, target_format, dest_data);
+ r_img->set_data(width, height, mipmaps, target_format, dest_data);
print_verbose(vformat("ETCPAK encode took %s ms.", rtos(OS::get_singleton()->get_ticks_msec() - start_time)));
}
diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml
index bc44479f93..c8eda53a2d 100644
--- a/modules/gdscript/doc_classes/@GDScript.xml
+++ b/modules/gdscript/doc_classes/@GDScript.xml
@@ -18,13 +18,11 @@
<param index="2" name="b8" type="int" />
<param index="3" name="a8" type="int" default="255" />
<description>
- Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255.
- [code]r8[/code] red channel
- [code]g8[/code] green channel
- [code]b8[/code] blue channel
- [code]a8[/code] alpha channel
+ Returns a [Color] constructed from red ([param r8]), green ([param g8]), blue ([param b8]), and optionally alpha ([param a8]) integer channels, each divided by [code]255.0[/code] for their final value.
[codeblock]
- red = Color8(255, 0, 0)
+ var red = Color8(255, 0, 0) # Same as Color(1, 0, 0)
+ var dark_blue = Color8(0, 0, 51) # Same as Color(0, 0, 0.2).
+ var my_color = Color8(306, 255, 0, 102) # Same as Color(1.2, 1, 0, 0.4).
[/codeblock]
</description>
</method>
@@ -33,9 +31,9 @@
<param index="0" name="condition" type="bool" />
<param index="1" name="message" type="String" default="&quot;&quot;" />
<description>
- Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users.
- [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode.
- The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. It must be a static string, so format strings can't be used. You can use this to provide additional details about why the assertion failed.
+ Asserts that the [param condition] is [code]true[/code]. If the [param condition] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users.
+ An optional [param message] can be shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed.
+ [b]Warning:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode.
[codeblock]
# Imagine we always want speed to be between 0 and 20.
var speed = -10
@@ -50,7 +48,7 @@
<return type="String" />
<param index="0" name="char" type="int" />
<description>
- Returns a character as a String of the given Unicode code point (which is compatible with ASCII code).
+ Returns a single character (as a [String]) of the given Unicode code point (which is compatible with ASCII code).
[codeblock]
a = char(65) # a is "A"
a = char(65 + 32) # a is "a"
@@ -63,14 +61,14 @@
<param index="0" name="what" type="Variant" />
<param index="1" name="type" type="int" />
<description>
- Converts from a type to another in the best way possible. The [code]type[/code] parameter uses the [enum Variant.Type] values.
+ Converts [param what] to [param type] in the best way possible. The [param type] uses the [enum Variant.Type] values.
[codeblock]
- a = Vector2(1, 0)
- # Prints 1
- print(a.length())
- a = convert(a, TYPE_STRING)
- # Prints 6 as "(1, 0)" is 6 characters
- print(a.length())
+ var a = [4, 2.5, 1.2]
+ print(a is Array) # Prints true
+
+ var b = convert(a, TYPE_PACKED_BYTE_ARRAY)
+ print(b) # Prints [4, 2, 1]
+ print(b is Array) # Prints false
[/codeblock]
</description>
</method>
@@ -78,7 +76,7 @@
<return type="Object" />
<param index="0" name="dictionary" type="Dictionary" />
<description>
- Converts a [param dictionary] (previously created with [method inst_to_dict]) back to an Object instance. Useful for deserializing.
+ Converts a [param dictionary] (created with [method inst_to_dict]) back to an Object instance. Can be useful for deserializing.
</description>
</method>
<method name="get_stack">
@@ -95,19 +93,19 @@
func bar():
print(get_stack())
[/codeblock]
- would print
+ Starting from [code]_ready()[/code], [code]bar()[/code] would print:
[codeblock]
[{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}]
[/codeblock]
- [b]Note:[/b] [method get_stack] only works if the running instance is connected to a debugging server (i.e. an editor instance). [method get_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.
- [b]Note:[/b] Not supported for calling from threads. Instead, this will return an empty array.
+ [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method get_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.
+ [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will return an empty array.
</description>
</method>
<method name="inst_to_dict">
<return type="Dictionary" />
<param index="0" name="instance" type="Object" />
<description>
- Returns the passed [param instance] converted to a Dictionary (useful for serializing).
+ Returns the passed [param instance] converted to a Dictionary. Can be useful for serializing.
[codeblock]
var foo = "bar"
func _ready():
@@ -126,11 +124,13 @@
<return type="int" />
<param index="0" name="var" type="Variant" />
<description>
- Returns length of Variant [code]var[/code]. Length is the character count of String, element count of Array, size of Dictionary, etc.
- [b]Note:[/b] Generates a fatal error if Variant can not provide a length.
+ Returns the length of the given Variant [param var]. The length can be the character count of a [String], the element count of any array type or the size of a [Dictionary]. For every other Variant type, a run-time error is generated and execution is stopped.
[codeblock]
a = [1, 2, 3, 4]
len(a) # Returns 4
+
+ b = "Hello!"
+ len(b) # Returns 6
[/codeblock]
</description>
</method>
@@ -138,25 +138,25 @@
<return type="Resource" />
<param index="0" name="path" type="String" />
<description>
- Loads a resource from the filesystem located at [code]path[/code]. The resource is loaded on the method call (unless it's referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload].
+ Returns a [Resource] from the filesystem located at the absolute [param path]. Unless it's already referenced elsewhere (such as in another script or in the scene), the resource is loaded from disk on function call, which might cause a slight delay, especially when loading large scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload].
[b]Note:[/b] Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script.
[codeblock]
- # Load a scene called main located in the root of the project directory and cache it in a variable.
+ # Load a scene called "main" located in the root of the project directory and cache it in a variable.
var main = load("res://main.tscn") # main will contain a PackedScene resource.
[/codeblock]
- [b]Important:[/b] The path must be absolute, a local path will just return [code]null[/code].
- This method is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios.
- [b]Note:[/b] You have to import the files into the engine first to load them using [method load]. If you want to load [Image]s at run-time, you may use [method Image.load]. If you want to import audio files, you can use the snippet described in [member AudioStreamMP3.data].
+ [b]Important:[/b] The path must be absolute. A relative path will always return [code]null[/code].
+ This function is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios.
+ [b]Note:[/b] Files have to be imported into the engine first to load them using this function. If you want to load [Image]s at run-time, you may use [method Image.load]. If you want to import audio files, you can use the snippet described in [member AudioStreamMP3.data].
</description>
</method>
<method name="preload">
<return type="Resource" />
<param index="0" name="path" type="String" />
<description>
- Returns a [Resource] from the filesystem located at [code]path[/code]. The resource is loaded during script parsing, i.e. is loaded with the script and [method preload] effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use [method load].
+ Returns a [Resource] from the filesystem located at [param path]. During run-time, the resource is loaded when the script is being parsed. This function effectively acts as a reference to that resource. Note that this function requires [param path] to be a constant [String]. If you want to load a resource from a dynamic/variable path, use [method load].
[b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script.
[codeblock]
- # Instance a scene.
+ # Create instance of a scene.
var diamond = preload("res://diamond.tscn").instantiate()
[/codeblock]
</description>
@@ -165,24 +165,24 @@
<return type="void" />
<description>
Like [method @GlobalScope.print], but includes the current stack frame when running with the debugger turned on.
- Output in the console would look something like this:
+ The output in the console may look like the following:
[codeblock]
Test print
- At: res://test.gd:15:_process()
+ At: res://test.gd:15:_process()
[/codeblock]
- [b]Note:[/b] Not supported for calling from threads. Instead of the stack frame, this will print the thread ID.
+ [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID.
</description>
</method>
<method name="print_stack">
<return type="void" />
<description>
Prints a stack trace at the current code location. See also [method get_stack].
- Output in the console would look something like this:
+ The output in the console may look like the following:
[codeblock]
Frame 0 - res://test.gd:16 in function '_process'
[/codeblock]
- [b]Note:[/b] [method print_stack] only works if the running instance is connected to a debugging server (i.e. an editor instance). [method print_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.
- [b]Note:[/b] Not supported for calling from threads. Instead of the stack trace, this will print the thread ID.
+ [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method print_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.
+ [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID.
</description>
</method>
<method name="range" qualifiers="vararg">
@@ -229,7 +229,7 @@
<method name="str" qualifiers="vararg">
<return type="String" />
<description>
- Converts one or more arguments to string in the best way possible.
+ Converts one or more arguments to a [String] in the best way possible.
[codeblock]
var a = [10, 20, 30]
var b = str(a);
@@ -242,7 +242,7 @@
<return type="bool" />
<param index="0" name="type" type="StringName" />
<description>
- Returns whether the given [Object]-derived class exists in [ClassDB]. Note that [Variant] data types are not registered in [ClassDB].
+ Returns [code]true[/code] if the given [Object]-derived class exists in [ClassDB]. Note that [Variant] data types are not registered in [ClassDB].
[codeblock]
type_exists("Sprite2D") # Returns true
type_exists("NonExistentClass") # Returns false
@@ -259,11 +259,11 @@
</constant>
<constant name="INF" value="inf">
Positive floating-point infinity. This is the result of floating-point division when the divisor is [code]0.0[/code]. For negative infinity, use [code]-INF[/code]. Dividing by [code]-0.0[/code] will result in negative infinity if the numerator is positive, so dividing by [code]0.0[/code] is not the same as dividing by [code]-0.0[/code] (despite [code]0.0 == -0.0[/code] returning [code]true[/code]).
- [b]Note:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead.
+ [b]Warning:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead.
</constant>
<constant name="NAN" value="nan">
"Not a Number", an invalid floating-point value. [constant NAN] has special properties, including that it is not equal to itself ([code]NAN == NAN[/code] returns [code]false[/code]). It is output by some invalid operations, such as dividing floating-point [code]0.0[/code] by [code]0.0[/code].
- [b]Note:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead.
+ [b]Warning:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead.
</constant>
</constants>
<annotations>
@@ -294,7 +294,7 @@
<annotation name="@export_color_no_alpha">
<return type="void" />
<description>
- Export a [Color] property without an alpha (fixed as [code]1.0[/code]).
+ Export a [Color] property without transparency (its alpha fixed as [code]1.0[/code]).
See also [constant PROPERTY_HINT_COLOR_NO_ALPHA].
[codeblock]
@export_color_no_alpha var modulate_color: Color
@@ -320,7 +320,7 @@
[codeblock]
@export_enum("Rebecca", "Mary", "Leah") var character_name: String
@export_enum("Warrior", "Magician", "Thief") var character_class: int
- @export_enum("Walking:30", "Running:60", "Riding:200") var character_speed: int
+ @export_enum("Slow:30", "Average:60", "Very Fast:200") var character_speed: int
[/codeblock]
</description>
</annotation>
@@ -451,7 +451,7 @@
<description>
Define a new group for the following exported properties. This helps to organize properties in the Inspector dock. Groups can be added with an optional [param prefix], which would make group to only consider properties that have this prefix. The grouping will break on the first property that doesn't have a prefix. The prefix is also removed from the property's name in the Inspector dock.
If no [param prefix] is provided, the every following property is added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for parameters, [code]@export_group("", "")[/code].
- Groups cannot be nested, use [annotation @export_subgroup] to add subgroups to your groups.
+ Groups cannot be nested, use [annotation @export_subgroup] to add subgroups within groups.
See also [constant PROPERTY_USAGE_GROUP].
[codeblock]
@export_group("My Properties")
@@ -473,7 +473,7 @@
Export a [String] property with a large [TextEdit] widget instead of a [LineEdit]. This adds support for multiline content and makes it easier to edit large amount of text stored in the property.
See also [constant PROPERTY_HINT_MULTILINE_TEXT].
[codeblock]
- @export_multiline var character_bio
+ @export_multiline var character_biography
[/codeblock]
</description>
</annotation>
@@ -547,11 +547,11 @@
<return type="void" />
<param index="0" name="icon_path" type="String" />
<description>
- Add a custom icon to the current script. The icon is displayed in the Scene dock for every node that the script is attached to. For named classes the icon is also displayed in various editor dialogs.
+ Add a custom icon to the current script. After loading an icon at [param icon_path], the icon is displayed in the Scene dock for every node that the script is attached to. For named classes, the icon is also displayed in various editor dialogs.
[codeblock]
@icon("res://path/to/class/icon.svg")
[/codeblock]
- [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported yet.
+ [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported.
</description>
</annotation>
<annotation name="@onready">
@@ -590,7 +590,7 @@
<return type="void" />
<param index="0" name="warning" type="String" />
<description>
- Mark the following statement to ignore the specified warning. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url].
+ Mark the following statement to ignore the specified [param warning]. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url].
[codeblock]
func test():
print("hello")
diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml
index 578e7a34f3..8246c96c15 100644
--- a/modules/gdscript/doc_classes/GDScript.xml
+++ b/modules/gdscript/doc_classes/GDScript.xml
@@ -4,7 +4,7 @@
A script implemented in the GDScript programming language.
</brief_description>
<description>
- A script implemented in the GDScript programming language. The script extends the functionality of all objects that instance it.
+ A script implemented in the GDScript programming language. The script extends the functionality of all objects that instantiate it.
[method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes.
</description>
<tutorials>
diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp
index 8645aa6f15..996d323a7f 100644
--- a/modules/gdscript/editor/gdscript_highlighter.cpp
+++ b/modules/gdscript/editor/gdscript_highlighter.cpp
@@ -256,7 +256,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
}
String word = str.substr(from + 1, to - from);
// Keywords need to be exceptions, except for keywords that represent a value.
- if (word == "true" || word == "false" || word == "null" || word == "PI" || word == "TAU" || word == "INF" || word == "NAN" || word == "self" || word == "super" || !keywords.has(word)) {
+ if (word == "true" || word == "false" || word == "null" || word == "PI" || word == "TAU" || word == "INF" || word == "NAN" || word == "self" || word == "super" || !reserved_keywords.has(word)) {
if (!is_symbol(str[to]) || str[to] == '"' || str[to] == '\'' || str[to] == ')' || str[to] == ']' || str[to] == '}') {
is_binary_op = true;
}
@@ -338,8 +338,10 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l
col = global_function_color;
}
}
- } else if (keywords.has(word)) {
- col = keywords[word];
+ } else if (class_names.has(word)) {
+ col = class_names[word];
+ } else if (reserved_keywords.has(word)) {
+ col = reserved_keywords[word];
} else if (member_keywords.has(word)) {
col = member_keywords[word];
}
@@ -563,7 +565,8 @@ PackedStringArray GDScriptSyntaxHighlighter::_get_supported_languages() const {
}
void GDScriptSyntaxHighlighter::_update_cache() {
- keywords.clear();
+ class_names.clear();
+ reserved_keywords.clear();
member_keywords.clear();
global_functions.clear();
color_regions.clear();
@@ -580,7 +583,7 @@ void GDScriptSyntaxHighlighter::_update_cache() {
List<StringName> types;
ClassDB::get_class_list(&types);
for (const StringName &E : types) {
- keywords[E] = types_color;
+ class_names[E] = types_color;
}
/* User types. */
@@ -588,14 +591,14 @@ void GDScriptSyntaxHighlighter::_update_cache() {
List<StringName> global_classes;
ScriptServer::get_global_class_list(&global_classes);
for (const StringName &E : global_classes) {
- keywords[E] = usertype_color;
+ class_names[E] = usertype_color;
}
/* Autoloads. */
for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) {
const ProjectSettings::AutoloadInfo &info = E.value;
if (info.is_singleton) {
- keywords[info.name] = usertype_color;
+ class_names[info.name] = usertype_color;
}
}
@@ -606,7 +609,7 @@ void GDScriptSyntaxHighlighter::_update_cache() {
List<String> core_types;
gdscript->get_core_type_words(&core_types);
for (const String &E : core_types) {
- keywords[StringName(E)] = basetype_color;
+ class_names[StringName(E)] = basetype_color;
}
/* Reserved words. */
@@ -616,9 +619,9 @@ void GDScriptSyntaxHighlighter::_update_cache() {
gdscript->get_reserved_words(&keyword_list);
for (const String &E : keyword_list) {
if (gdscript->is_control_flow_keyword(E)) {
- keywords[StringName(E)] = control_flow_keyword_color;
+ reserved_keywords[StringName(E)] = control_flow_keyword_color;
} else {
- keywords[StringName(E)] = keyword_color;
+ reserved_keywords[StringName(E)] = keyword_color;
}
}
diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h
index 60b5b092d4..7c22eb30b1 100644
--- a/modules/gdscript/editor/gdscript_highlighter.h
+++ b/modules/gdscript/editor/gdscript_highlighter.h
@@ -47,7 +47,8 @@ private:
Vector<ColorRegion> color_regions;
HashMap<int, int> color_region_cache;
- HashMap<StringName, Color> keywords;
+ HashMap<StringName, Color> class_names;
+ HashMap<StringName, Color> reserved_keywords;
HashMap<StringName, Color> member_keywords;
HashSet<StringName> global_functions;
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 0a9dad04c7..b4da9c1224 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -1050,6 +1050,11 @@ Error GDScript::load_byte_code(const String &p_path) {
return ERR_COMPILATION_FAILED;
}
+void GDScript::set_path(const String &p_path, bool p_take_over) {
+ Script::set_path(p_path, p_take_over);
+ this->path = p_path;
+}
+
Error GDScript::load_source_code(const String &p_path) {
Vector<uint8_t> sourcef;
Error err;
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index 0a010e5ad0..72ad890fbc 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -222,6 +222,7 @@ public:
virtual Error reload(bool p_keep_state = false) override;
+ virtual void set_path(const String &p_path, bool p_take_over = false) override;
void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too...
Error load_source_code(const String &p_path);
Error load_byte_code(const String &p_path);
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index e1beb2f374..898e4eb1a6 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -1041,7 +1041,7 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) {
}
}
-void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
+void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {
ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
switch (p_node->type) {
@@ -1114,7 +1114,7 @@ void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
case GDScriptParser::Node::SUBSCRIPT:
case GDScriptParser::Node::TERNARY_OPERATOR:
case GDScriptParser::Node::UNARY_OPERATOR:
- reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), true);
+ reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);
break;
case GDScriptParser::Node::BREAK:
case GDScriptParser::Node::BREAKPOINT:
@@ -1411,7 +1411,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
variable_type.builtin_type = Variant::INT; // Can this ever be a float or something else?
p_for->variable->set_datatype(variable_type);
} else if (p_for->list) {
- resolve_node(p_for->list);
+ resolve_node(p_for->list, false);
if (p_for->list->datatype.has_container_element_type()) {
variable_type = p_for->list->datatype.get_container_element_type();
variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
@@ -1439,7 +1439,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
}
void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
- resolve_node(p_while->condition);
+ resolve_node(p_while->condition, false);
resolve_suite(p_while->loop);
p_while->set_datatype(p_while->loop->get_datatype());
@@ -1824,7 +1824,7 @@ void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expre
reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
break;
case GDScriptParser::Node::CALL:
- reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), p_is_root);
+ reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);
break;
case GDScriptParser::Node::CAST:
reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
@@ -2548,6 +2548,16 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a
mark_lambda_use_self();
}
+#ifdef DEBUG_ENABLED
+ if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL) {
+ parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);
+ }
+
+ if (is_static && !base_type.is_meta_type && !(callee_type != GDScriptParser::Node::SUBSCRIPT && parser->current_function != nullptr && parser->current_function->is_static)) {
+ parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, base_type.to_string());
+ }
+#endif // DEBUG_ENABLED
+
call_type = return_type;
} else {
bool found = false;
@@ -3216,7 +3226,13 @@ void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
}
p_preload->resolved_path = p_preload->resolved_path.simplify_path();
if (!ResourceLoader::exists(p_preload->resolved_path)) {
- push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
+ Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
+
+ if (file_check->file_exists(p_preload->resolved_path)) {
+ push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);
+ } else {
+ push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
+ }
} else {
// TODO: Don't load if validating: use completion cache.
p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h
index 3966b81b6e..217a856ce0 100644
--- a/modules/gdscript/gdscript_analyzer.h
+++ b/modules/gdscript/gdscript_analyzer.h
@@ -63,7 +63,7 @@ class GDScriptAnalyzer {
void resolve_class_body(GDScriptParser::ClassNode *p_class);
void resolve_function_signature(GDScriptParser::FunctionNode *p_function);
void resolve_function_body(GDScriptParser::FunctionNode *p_function);
- void resolve_node(GDScriptParser::Node *p_node);
+ void resolve_node(GDScriptParser::Node *p_node, bool p_is_root = true);
void resolve_suite(GDScriptParser::SuiteNode *p_suite);
void resolve_if(GDScriptParser::IfNode *p_if);
void resolve_for(GDScriptParser::ForNode *p_for);
diff --git a/modules/gdscript/gdscript_warning.cpp b/modules/gdscript/gdscript_warning.cpp
index 1cae7bdfac..a0c107aa53 100644
--- a/modules/gdscript/gdscript_warning.cpp
+++ b/modules/gdscript/gdscript_warning.cpp
@@ -155,6 +155,10 @@ String GDScriptWarning::get_message() const {
case INT_ASSIGNED_TO_ENUM: {
return "Integer used when an enum value is expected. If this is intended cast the integer to the enum type.";
}
+ case STATIC_CALLED_ON_INSTANCE: {
+ CHECK_SYMBOLS(2);
+ return vformat(R"(The function '%s()' is a static function but was called from an instance. Instead, it should be directly called from the type: '%s.%s()'.)", symbols[0], symbols[1], symbols[0]);
+ }
case WARNING_MAX:
break; // Can't happen, but silences warning
}
@@ -215,6 +219,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) {
"EMPTY_FILE",
"SHADOWED_GLOBAL_IDENTIFIER",
"INT_ASSIGNED_TO_ENUM",
+ "STATIC_CALLED_ON_INSTANCE",
};
static_assert((sizeof(names) / sizeof(*names)) == WARNING_MAX, "Amount of warning types don't match the amount of warning names.");
diff --git a/modules/gdscript/gdscript_warning.h b/modules/gdscript/gdscript_warning.h
index a639e7b44e..7e4e975510 100644
--- a/modules/gdscript/gdscript_warning.h
+++ b/modules/gdscript/gdscript_warning.h
@@ -78,6 +78,7 @@ public:
EMPTY_FILE, // A script file is empty.
SHADOWED_GLOBAL_IDENTIFIER, // A global class or function has the same name as variable.
INT_ASSIGNED_TO_ENUM, // An integer value was assigned to an enum-typed variable without casting.
+ STATIC_CALLED_ON_INSTANCE, // A static method was called on an instance of a class instead of on the class itself.
WARNING_MAX,
};
diff --git a/modules/gdscript/tests/scripts/parser/features/class.gd b/modules/gdscript/tests/scripts/parser/features/class.gd
index 6652f85ad9..af24b32322 100644
--- a/modules/gdscript/tests/scripts/parser/features/class.gd
+++ b/modules/gdscript/tests/scripts/parser/features/class.gd
@@ -21,5 +21,5 @@ func test():
assert(test_sub.number == 25) # From Test.
assert(test_sub.other_string == "bye") # From TestSub.
- TestConstructor.new()
- TestConstructor.new(500)
+ var _test_constructor = TestConstructor.new()
+ _test_constructor = TestConstructor.new(500)
diff --git a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out
index d73c5eb7cd..13f759dd46 100644
--- a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out
+++ b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out
@@ -1 +1,5 @@
GDTEST_OK
+>> WARNING
+>> Line: 6
+>> RETURN_VALUE_DISCARDED
+>> The function 'i_return_int()' returns a value, but this value is never used.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd
new file mode 100644
index 0000000000..29d8501b78
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd
@@ -0,0 +1,11 @@
+class Player:
+ var x = 3
+
+func test():
+ # These should not emit a warning.
+ var _player = Player.new()
+ print(String.num_uint64(8589934592)) # 2 ^ 33
+
+ # This should emit a warning.
+ var some_string = String()
+ print(some_string.num_uint64(8589934592)) # 2 ^ 33
diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out
new file mode 100644
index 0000000000..3933a35178
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out
@@ -0,0 +1,7 @@
+GDTEST_OK
+>> WARNING
+>> Line: 11
+>> STATIC_CALLED_ON_INSTANCE
+>> The function 'num_uint64()' is a static function but was called from an instance. Instead, it should be directly called from the type: 'String.num_uint64()'.
+8589934592
+8589934592
diff --git a/modules/glslang/register_types.cpp b/modules/glslang/register_types.cpp
index b1c2140039..53ec0fde34 100644
--- a/modules/glslang/register_types.cpp
+++ b/modules/glslang/register_types.cpp
@@ -53,7 +53,6 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage
};
int ClientInputSemanticsVersion = 100; // maps to, say, #define VULKAN 100
- bool check_subgroup_support = true; // assume we support subgroups
glslang::EShTargetClientVersion ClientVersion = glslang::EShTargetVulkan_1_2;
glslang::EShTargetLanguageVersion TargetVersion = glslang::EShTargetSpv_1_5;
@@ -63,7 +62,6 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage
if (capabilities->version_major == 1 && capabilities->version_minor == 0) {
ClientVersion = glslang::EShTargetVulkan_1_0;
TargetVersion = glslang::EShTargetSpv_1_0;
- check_subgroup_support = false; // subgroups are not supported in Vulkan 1.0
} else if (capabilities->version_major == 1 && capabilities->version_minor == 1) {
ClientVersion = glslang::EShTargetVulkan_1_1;
TargetVersion = glslang::EShTargetSpv_1_3;
@@ -88,7 +86,7 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage
shader.setEnvClient(glslang::EShClientVulkan, ClientVersion);
shader.setEnvTarget(glslang::EShTargetSpv, TargetVersion);
- if (check_subgroup_support) {
+ {
uint32_t stage_bit = 1 << p_stage;
uint32_t subgroup_in_shaders = uint32_t(p_render_device->limit_get(RD::LIMIT_SUBGROUP_IN_SHADERS));
diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml
index 4d1aa89ac9..8e48066623 100644
--- a/modules/gltf/doc_classes/GLTFNode.xml
+++ b/modules/gltf/doc_classes/GLTFNode.xml
@@ -9,6 +9,25 @@
<tutorials>
<link title="GLTF scene and node spec">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_004_ScenesNodes.md"</link>
</tutorials>
+ <methods>
+ <method name="get_additional_data">
+ <return type="Variant" />
+ <param index="0" name="extension_name" type="StringName" />
+ <description>
+ Gets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless.
+ The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null.
+ </description>
+ </method>
+ <method name="set_additional_data">
+ <return type="void" />
+ <param index="0" name="extension_name" type="StringName" />
+ <param index="1" name="additional_data" type="Variant" />
+ <description>
+ Sets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless.
+ The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want.
+ </description>
+ </method>
+ </methods>
<members>
<member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1">
</member>
diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml
index 56f3a70631..d0740cf7ca 100644
--- a/modules/gltf/doc_classes/GLTFState.xml
+++ b/modules/gltf/doc_classes/GLTFState.xml
@@ -20,6 +20,14 @@
<description>
</description>
</method>
+ <method name="get_additional_data">
+ <return type="Variant" />
+ <param index="0" name="extension_name" type="StringName" />
+ <description>
+ Gets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless.
+ The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null.
+ </description>
+ </method>
<method name="get_animation_player">
<return type="AnimationPlayer" />
<param index="0" name="idx" type="int" />
@@ -120,6 +128,15 @@
<description>
</description>
</method>
+ <method name="set_additional_data">
+ <return type="void" />
+ <param index="0" name="extension_name" type="StringName" />
+ <param index="1" name="additional_data" type="Variant" />
+ <description>
+ Sets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless.
+ The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want.
+ </description>
+ </method>
<method name="set_animations">
<return type="void" />
<param index="0" name="animations" type="GLTFAnimation[]" />
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index 8272db9018..cb148463a7 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -2590,10 +2590,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
Mesh::PRIMITIVE_TRIANGLES, // 4 TRIANGLES
Mesh::PRIMITIVE_TRIANGLE_STRIP, // 5 TRIANGLE_STRIP
Mesh::PRIMITIVE_TRIANGLES, // 6 TRIANGLE_FAN fan not supported, should be converted
-#ifndef _MSC_VER
-#warning line loop and triangle fan are not supported and need to be converted to lines and triangles
-#endif
-
+ // TODO: Line loop and triangle fan are not supported and need to be converted to lines and triangles.
};
primitive = primitives2[mode];
@@ -3487,7 +3484,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) {
height = albedo_texture->get_height();
width = albedo_texture->get_width();
}
- orm_image->create(width, height, false, Image::FORMAT_RGBA8);
+ orm_image->initialize_data(width, height, false, Image::FORMAT_RGBA8);
if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) {
ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
}
@@ -3863,13 +3860,11 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re
if (r_spec_gloss->diffuse_img.is_null()) {
return;
}
- Ref<Image> rm_img;
- rm_img.instantiate();
bool has_roughness = false;
bool has_metal = false;
p_material->set_roughness(1.0f);
p_material->set_metallic(1.0f);
- rm_img->create(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
+ Ref<Image> rm_img = Image::create_empty(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
r_spec_gloss->spec_gloss_img->decompress();
if (r_spec_gloss->diffuse_img.is_valid()) {
r_spec_gloss->diffuse_img->decompress();
diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp
index 60192c67e6..ac5665e396 100644
--- a/modules/gltf/gltf_state.cpp
+++ b/modules/gltf/gltf_state.cpp
@@ -87,6 +87,8 @@ void GLTFState::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_animations"), &GLTFState::get_animations);
ClassDB::bind_method(D_METHOD("set_animations", "animations"), &GLTFState::set_animations);
ClassDB::bind_method(D_METHOD("get_scene_node", "idx"), &GLTFState::get_scene_node);
+ ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFState::get_additional_data);
+ ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFState::set_additional_data);
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "json"), "set_json", "get_json"); // Dictionary
ADD_PROPERTY(PropertyInfo(Variant::INT, "major_version"), "set_major_version", "get_major_version"); // int
@@ -358,3 +360,11 @@ String GLTFState::get_base_path() {
void GLTFState::set_base_path(String p_base_path) {
base_path = p_base_path;
}
+
+Variant GLTFState::get_additional_data(const StringName &p_extension_name) {
+ return additional_data[p_extension_name];
+}
+
+void GLTFState::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) {
+ additional_data[p_extension_name] = p_additional_data;
+}
diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h
index afe7e82010..e24017b0fd 100644
--- a/modules/gltf/gltf_state.h
+++ b/modules/gltf/gltf_state.h
@@ -97,6 +97,7 @@ class GLTFState : public Resource {
HashMap<ObjectID, GLTFSkeletonIndex> skeleton3d_to_gltf_skeleton;
HashMap<ObjectID, HashMap<ObjectID, GLTFSkinIndex>> skin_and_skeleton3d_to_gltf_skin;
+ Dictionary additional_data;
protected:
static void _bind_methods();
@@ -191,6 +192,9 @@ public:
AnimationPlayer *get_animation_player(int idx);
+ Variant get_additional_data(const StringName &p_extension_name);
+ void set_additional_data(const StringName &p_extension_name, Variant p_additional_data);
+
//void set_scene_nodes(RBMap<GLTFNodeIndex, Node *> p_scene_nodes) {
// this->scene_nodes = p_scene_nodes;
//}
diff --git a/modules/gltf/structures/gltf_node.cpp b/modules/gltf/structures/gltf_node.cpp
index 86280603fa..6fd36f93b7 100644
--- a/modules/gltf/structures/gltf_node.cpp
+++ b/modules/gltf/structures/gltf_node.cpp
@@ -57,6 +57,8 @@ void GLTFNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_children", "children"), &GLTFNode::set_children);
ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light);
ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light);
+ ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFNode::get_additional_data);
+ ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFNode::set_additional_data);
ADD_PROPERTY(PropertyInfo(Variant::INT, "parent"), "set_parent", "get_parent"); // GLTFNodeIndex
ADD_PROPERTY(PropertyInfo(Variant::INT, "height"), "set_height", "get_height"); // int
@@ -176,3 +178,11 @@ GLTFLightIndex GLTFNode::get_light() {
void GLTFNode::set_light(GLTFLightIndex p_light) {
light = p_light;
}
+
+Variant GLTFNode::get_additional_data(const StringName &p_extension_name) {
+ return additional_data[p_extension_name];
+}
+
+void GLTFNode::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) {
+ additional_data[p_extension_name] = p_additional_data;
+}
diff --git a/modules/gltf/structures/gltf_node.h b/modules/gltf/structures/gltf_node.h
index 1a57ea32e2..90a4fa99ed 100644
--- a/modules/gltf/structures/gltf_node.h
+++ b/modules/gltf/structures/gltf_node.h
@@ -53,6 +53,7 @@ private:
Vector3 scale = Vector3(1, 1, 1);
Vector<int> children;
GLTFLightIndex light = -1;
+ Dictionary additional_data;
protected:
static void _bind_methods();
@@ -96,6 +97,9 @@ public:
GLTFLightIndex get_light();
void set_light(GLTFLightIndex p_light);
+
+ Variant get_additional_data(const StringName &p_extension_name);
+ void set_additional_data(const StringName &p_extension_name, Variant p_additional_data);
};
#endif // GLTF_NODE_H
diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp
index 6f0bc16a26..457b263e16 100644
--- a/modules/hdr/image_loader_hdr.cpp
+++ b/modules/hdr/image_loader_hdr.cpp
@@ -140,7 +140,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField
}
}
- p_image->create(width, height, false, Image::FORMAT_RGBE9995, imgdata);
+ p_image->set_data(width, height, false, Image::FORMAT_RGBE9995, imgdata);
return OK;
}
diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp
index ce20ac9060..d465467cf9 100644
--- a/modules/jpg/image_loader_jpegd.cpp
+++ b/modules/jpg/image_loader_jpegd.cpp
@@ -99,7 +99,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
fmt = Image::FORMAT_RGB8;
}
- p_image->create(image_width, image_height, false, fmt, data);
+ p_image->set_data(image_width, image_height, false, fmt, data);
return OK;
}
diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp
index 8785f327db..9111827c1b 100644
--- a/modules/lightmapper_rd/lightmapper_rd.cpp
+++ b/modules/lightmapper_rd/lightmapper_rd.cpp
@@ -251,15 +251,11 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_
}
for (int i = 0; i < atlas_slices; i++) {
- Ref<Image> albedo;
- albedo.instantiate();
- albedo->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
+ Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
albedo->set_as_black();
albedo_images.write[i] = albedo;
- Ref<Image> emission;
- emission.instantiate();
- emission->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
+ Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
emission->set_as_black();
emission_images.write[i] = emission;
}
@@ -478,9 +474,7 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i
grid_usage.write[j] = count > 0 ? 255 : 0;
}
- Ref<Image> img;
- img.instantiate();
- img->create(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
+ Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
}
#endif
@@ -660,9 +654,7 @@ LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShade
#ifdef DEBUG_TEXTURES
for (int i = 0; i < atlas_slices; i++) {
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->convert(Image::FORMAT_RGBA8);
img->save_png("res://5_dilated_" + itos(i) + ".png");
}
@@ -778,7 +770,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
panorama_tex->convert(Image::FORMAT_RGBAF);
} else {
panorama_tex.instantiate();
- panorama_tex->create(8, 8, false, Image::FORMAT_RGBAF);
+ panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
panorama_tex->fill(Color(0, 0, 0, 1));
}
@@ -953,13 +945,11 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
for (int i = 0; i < atlas_slices; i++) {
Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
img->save_exr("res://1_position_" + itos(i) + ".exr", false);
s = rd->texture_get_data(normal_tex, i);
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
}
#endif
@@ -1182,9 +1172,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
for (int i = 0; i < atlas_slices; i++) {
Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
}
#endif
@@ -1415,14 +1403,10 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
#if 0
for (int i = 0; i < probe_positions.size(); i++) {
- Ref<Image> img;
- img.instantiate();
- img->create(6, 4, false, Image::FORMAT_RGB8);
+ Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
for (int j = 0; j < 6; j++) {
Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
- Ref<Image> img2;
- img2.instantiate();
- img2->create(2, 2, false, Image::FORMAT_RGBAF, s);
+ Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
img2->convert(Image::FORMAT_RGB8);
img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
}
@@ -1449,9 +1433,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
if (denoiser.is_valid()) {
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
Ref<Image> denoised = denoiser->denoise_image(img);
if (denoised != img) {
@@ -1484,9 +1466,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
}
#endif
@@ -1640,9 +1620,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
}
#endif
@@ -1652,9 +1630,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
- Ref<Image> img;
- img.instantiate();
- img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
img->convert(Image::FORMAT_RGBH); //remove alpha
bake_textures.push_back(img);
}
@@ -1667,9 +1643,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
#ifdef DEBUG_TEXTURES
{
- Ref<Image> img2;
- img2.instantiate();
- img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
+ Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
img2->save_exr("res://6_lightprobes.exr", false);
}
#endif
diff --git a/modules/mono/Directory.Build.targets b/modules/mono/Directory.Build.targets
index 98410b93ae..e666b3ac9d 100644
--- a/modules/mono/Directory.Build.targets
+++ b/modules/mono/Directory.Build.targets
@@ -2,6 +2,8 @@
<PropertyGroup>
<_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' And '$(PackageId)' != '' And '$(GeneratePackageOnBuild.ToLower())' == 'true' ">true</_HasNuGetPackage>
<_HasNuGetPackage Condition=" '$(_HasNuGetPackage)' == '' ">false</_HasNuGetPackage>
+ <_HasSymbolsNuGetPackage Condition=" '$(_HasSymbolsNuGetPackage)' == '' And '$(PackageId)' != '' And '$(IncludeSymbols.ToLower())' == 'true' And '$(SymbolPackageFormat)' == 'snupkg' ">true</_HasSymbolsNuGetPackage>
+ <_HasSymbolsNuGetPackage Condition=" '$(_HasSymbolsNuGetPackage)' == '' ">false</_HasSymbolsNuGetPackage>
</PropertyGroup>
<Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack"
Condition=" '$(_HasNuGetPackage)' == 'true' ">
@@ -10,13 +12,15 @@
<GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir>
</PropertyGroup>
<Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
+ <Copy Condition=" '$(_HasSymbolsNuGetPackage)' == 'true' " SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).snupkg" DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
</Target>
<Target Name="PushNuGetPackagesToLocalSource" BeforeTargets="Pack"
Condition=" '$(_HasNuGetPackage)' == 'true' And '$(PushNuGetToLocalSource)' != '' ">
<Copy SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(PushNuGetToLocalSource)\" />
+ <Copy Condition=" '$(_HasSymbolsNuGetPackage)' == 'true' " SourceFiles="$(PackageOutputPath)$(PackageId).$(PackageVersion).snupkg" DestinationFolder="$(PushNuGetToLocalSource)\" />
</Target>
<Target Name="ClearNuGetLocalPackageCache" BeforeTargets="Pack"
Condition=" '$(_HasNuGetPackage)' == 'true' And '$(ClearNuGetLocalCache.ToLower())' == 'true' ">
- <RemoveDir Directories="$(NugetPackageRoot)/$(PackageId.ToLower())/$(PackageVersion)"/>
+ <RemoveDir Directories="$(NugetPackageRoot)/$(PackageId.ToLower())/$(PackageVersion)" />
</Target>
</Project>
diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp
index c4547b4323..1f4b085bfb 100644
--- a/modules/mono/class_db_api_json.cpp
+++ b/modules/mono/class_db_api_json.cpp
@@ -227,8 +227,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
Ref<FileAccess> f = FileAccess::open(p_output_file, FileAccess::WRITE);
ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file '" + p_output_file + "'.");
- JSON json;
- f->store_string(json.stringify(classes_dict, "\t"));
+ f->store_string(JSON::stringify(classes_dict, "\t"));
print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file));
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs
index 7ec3f88e5d..19fdd51dab 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/GodotPluginsInitializerGenerator.cs
@@ -56,7 +56,7 @@ namespace GodotPlugins.Game
}
";
- context.AddSource("GodotPlugins.Game_Generated",
+ context.AddSource("GodotPlugins.Game.generated",
SourceText.From(source, Encoding.UTF8));
}
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs
index 1ee31eb1a9..d915eeac0b 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptMethodsGenerator.cs
@@ -87,7 +87,7 @@ namespace Godot.SourceGenerators
bool isInnerClass = symbol.ContainingType != null;
string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptMethods_Generated";
+ + "_ScriptMethods.generated";
var source = new StringBuilder();
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
index e8a9e28d0c..ccfb405d26 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPathAttributeGenerator.cs
@@ -96,8 +96,8 @@ namespace Godot.SourceGenerators
string.Empty;
bool hasNamespace = classNs.Length != 0;
- var uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptPath_Generated";
+ string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
+ + "_ScriptPath.generated";
var source = new StringBuilder();
@@ -126,7 +126,7 @@ namespace Godot.SourceGenerators
source.Append("\n}\n");
}
- context.AddSource(uniqueHint.ToString(), SourceText.From(source.ToString(), Encoding.UTF8));
+ context.AddSource(uniqueHint, SourceText.From(source.ToString(), Encoding.UTF8));
}
private static void AddScriptTypesAssemblyAttr(GeneratorExecutionContext context,
@@ -157,7 +157,7 @@ namespace Godot.SourceGenerators
sourceBuilder.Append("})]\n");
- context.AddSource("AssemblyScriptTypes_Generated",
+ context.AddSource("AssemblyScriptTypes.generated",
SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs
index b331e2e794..1198c633d9 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertiesGenerator.cs
@@ -73,7 +73,7 @@ namespace Godot.SourceGenerators
bool isInnerClass = symbol.ContainingType != null;
string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptProperties_Generated";
+ + "_ScriptProperties.generated";
var source = new StringBuilder();
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs
index 65dadcb801..98b9745c16 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptPropertyDefValGenerator.cs
@@ -73,7 +73,7 @@ namespace Godot.SourceGenerators
bool isInnerClass = symbol.ContainingType != null;
string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptPropertyDefVal_Generated";
+ + "_ScriptPropertyDefVal.generated";
var source = new StringBuilder();
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs
index a40220565f..11e0a6fa21 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSerializationGenerator.cs
@@ -73,7 +73,7 @@ namespace Godot.SourceGenerators
bool isInnerClass = symbol.ContainingType != null;
string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptSerialization_Generated";
+ + "_ScriptSerialization.generated";
var source = new StringBuilder();
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs
index ea7cc3fe38..4e443ce26e 100644
--- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs
@@ -82,7 +82,7 @@ namespace Godot.SourceGenerators
bool isInnerClass = symbol.ContainingType != null;
string uniqueHint = symbol.FullQualifiedName().SanitizeQualifiedNameForUniqueHint()
- + "_ScriptSignals_Generated";
+ + "_ScriptSignals.generated";
var source = new StringBuilder();
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
index 0d2bea2363..745a8b73f8 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
@@ -17,6 +17,8 @@ namespace GodotTools.Export
{
public partial class ExportPlugin : EditorExportPlugin
{
+ private List<string> _tempFolders = new List<string>();
+
public void RegisterExportSettings()
{
// TODO: These would be better as export preset options, but that doesn't seem to be supported yet
@@ -111,62 +113,78 @@ namespace GodotTools.Export
string buildConfig = isDebug ? "ExportDebug" : "ExportRelease";
- // TODO: This works for now, as we only implemented support for x86 family desktop so far, but it needs to be fixed
- string arch = features.Contains("x86_64") ? "x86_64" : "x86";
-
- string ridOS = DetermineRuntimeIdentifierOS(platform);
- string ridArch = DetermineRuntimeIdentifierArch(arch);
- string runtimeIdentifier = $"{ridOS}-{ridArch}";
-
- // Create temporary publish output directory
-
- string publishOutputTempDir = Path.Combine(Path.GetTempPath(), "godot-publish-dotnet",
- $"{Process.GetCurrentProcess().Id}-{buildConfig}-{runtimeIdentifier}");
-
- if (!Directory.Exists(publishOutputTempDir))
- Directory.CreateDirectory(publishOutputTempDir);
-
- // Execute dotnet publish
-
- if (!BuildManager.PublishProjectBlocking(buildConfig, platform,
- runtimeIdentifier, publishOutputTempDir))
+ var archs = new List<string>();
+ if (features.Contains("x86_64"))
{
- throw new InvalidOperationException("Failed to build project.");
+ archs.Add("x86_64");
}
-
- string soExt = ridOS switch
+ else if (features.Contains("x86_32"))
{
- OS.DotNetOS.Win or OS.DotNetOS.Win10 => "dll",
- OS.DotNetOS.OSX or OS.DotNetOS.iOS => "dylib",
- _ => "so"
- };
-
- if (!File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.dll"))
- // NativeAOT shared library output
- && !File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.{soExt}")))
+ archs.Add("x86_32");
+ }
+ else if (features.Contains("arm64"))
{
- throw new NotSupportedException(
- "Publish succeeded but project assembly not found in the output directory");
+ archs.Add("arm64");
}
-
- // Copy all files from the dotnet publish output directory to
- // a data directory next to the Godot output executable.
-
- string outputDataDir = Path.Combine(outputDir, DetermineDataDirNameForProject());
-
- if (Directory.Exists(outputDataDir))
- Directory.Delete(outputDataDir, recursive: true); // Clean first
-
- Directory.CreateDirectory(outputDataDir);
-
- foreach (string dir in Directory.GetDirectories(publishOutputTempDir, "*", SearchOption.AllDirectories))
+ else if (features.Contains("universal"))
{
- Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(publishOutputTempDir.Length + 1)));
+ if (platform == OS.Platforms.MacOS)
+ {
+ archs.Add("x86_64");
+ archs.Add("arm64");
+ }
}
- foreach (string file in Directory.GetFiles(publishOutputTempDir, "*", SearchOption.AllDirectories))
+ foreach (var arch in archs)
{
- File.Copy(file, Path.Combine(outputDataDir, file.Substring(publishOutputTempDir.Length + 1)));
+ string ridOS = DetermineRuntimeIdentifierOS(platform);
+ string ridArch = DetermineRuntimeIdentifierArch(arch);
+ string runtimeIdentifier = $"{ridOS}-{ridArch}";
+ string projectDataDirName = $"{DetermineDataDirNameForProject()}_{arch}";
+ if (platform == OS.Platforms.MacOS)
+ {
+ projectDataDirName = Path.Combine("Contents", "Resources", projectDataDirName);
+ }
+
+ // Create temporary publish output directory
+
+ string publishOutputTempDir = Path.Combine(Path.GetTempPath(), "godot-publish-dotnet",
+ $"{Process.GetCurrentProcess().Id}-{buildConfig}-{runtimeIdentifier}");
+
+ _tempFolders.Add(publishOutputTempDir);
+
+ if (!Directory.Exists(publishOutputTempDir))
+ Directory.CreateDirectory(publishOutputTempDir);
+
+ // Execute dotnet publish
+
+ if (!BuildManager.PublishProjectBlocking(buildConfig, platform,
+ runtimeIdentifier, publishOutputTempDir))
+ {
+ throw new InvalidOperationException("Failed to build project.");
+ }
+
+ string soExt = ridOS switch
+ {
+ OS.DotNetOS.Win or OS.DotNetOS.Win10 => "dll",
+ OS.DotNetOS.OSX or OS.DotNetOS.iOS => "dylib",
+ _ => "so"
+ };
+
+ if (!File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.dll"))
+ // NativeAOT shared library output
+ && !File.Exists(Path.Combine(publishOutputTempDir, $"{GodotSharpDirs.ProjectAssemblyName}.{soExt}")))
+ {
+ throw new NotSupportedException(
+ "Publish succeeded but project assembly not found in the output directory");
+ }
+
+ // Add to the exported project shared object list.
+
+ foreach (string file in Directory.GetFiles(publishOutputTempDir, "*", SearchOption.AllDirectories))
+ {
+ AddSharedObject(file, tags: null, projectDataDirName);
+ }
}
}
@@ -198,6 +216,12 @@ namespace GodotTools.Export
if (Directory.Exists(aotTempDir))
Directory.Delete(aotTempDir, recursive: true);
+ foreach (string folder in _tempFolders)
+ {
+ Directory.Delete(folder, recursive: true);
+ }
+ _tempFolders.Clear();
+
// TODO: The following is just a workaround until the export plugins can be made to abort with errors
// We check for empty as well, because it's set to empty after hot-reloading
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index d29e0d69ab..3be8dd87c0 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -3119,9 +3119,10 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
for (const KeyValue<StringName, ClassDB::ClassInfo::EnumInfo> &E : enum_map) {
StringName enum_proxy_cname = E.key;
String enum_proxy_name = enum_proxy_cname.operator String();
- if (itype.find_property_by_proxy_name(enum_proxy_cname)) {
- // We have several conflicts between enums and PascalCase properties,
- // so we append 'Enum' to the enum name in those cases.
+ if (itype.find_property_by_proxy_name(enum_proxy_name) || itype.find_method_by_proxy_name(enum_proxy_name) || itype.find_signal_by_proxy_name(enum_proxy_name)) {
+ // In case the enum name conflicts with other PascalCase members,
+ // we append 'Enum' to the enum name in those cases.
+ // We have several conflicts between enums and PascalCase properties.
enum_proxy_name += "Enum";
enum_proxy_cname = StringName(enum_proxy_name);
}
@@ -3170,7 +3171,15 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
int64_t *value = class_info->constant_map.getptr(StringName(constant_name));
ERR_FAIL_NULL_V(value, false);
- ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
+ String constant_proxy_name = snake_to_pascal_case(constant_name, true);
+
+ if (itype.find_property_by_proxy_name(constant_proxy_name) || itype.find_method_by_proxy_name(constant_proxy_name) || itype.find_signal_by_proxy_name(constant_proxy_name)) {
+ // In case the constant name conflicts with other PascalCase members,
+ // we append 'Constant' to the constant name in those cases.
+ constant_proxy_name += "Constant";
+ }
+
+ ConstantInterface iconstant(constant_name, constant_proxy_name, *value);
iconstant.const_doc = nullptr;
for (int i = 0; i < itype.class_doc->constants.size(); i++) {
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
index 3c75d18943..9b3969d453 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs
@@ -76,6 +76,11 @@ namespace Godot
internal static bool TrySerializeDelegate(Delegate @delegate, Collections.Array serializedData)
{
+ if (@delegate is null)
+ {
+ return false;
+ }
+
if (@delegate is MulticastDelegate multicastDelegate)
{
bool someDelegatesSerialized = false;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
index 13070c8033..664b2e0f34 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
@@ -292,6 +292,18 @@ namespace Godot
}
/// <summary>
+ /// Constructs a <see cref="Plane"/> from a <paramref name="normal"/> vector and
+ /// a <paramref name="point"/> on the plane.
+ /// </summary>
+ /// <param name="normal">The normal of the plane, must be normalized.</param>
+ /// <param name="point">The point on the plane.</param>
+ public Plane(Vector3 normal, Vector3 point)
+ {
+ _normal = normal;
+ D = _normal.Dot(point);
+ }
+
+ /// <summary>
/// Constructs a <see cref="Plane"/> from the three points, given in clockwise order.
/// </summary>
/// <param name="v1">The first point.</param>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
index 5827d3e591..a63b668387 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
@@ -27,6 +27,8 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<!-- SdkPackageVersions.props for easy access -->
diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
index 5d69ad8ec6..8f623625fc 100644
--- a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
@@ -22,6 +22,8 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+ <IncludeSymbols>true</IncludeSymbols>
+ <SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<PropertyGroup>
<DefineConstants>$(DefineConstants);GODOT</DefineConstants>
diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp
index c7e47d2718..185a7e60cf 100644
--- a/modules/mono/godotsharp_dirs.cpp
+++ b/modules/mono/godotsharp_dirs.cpp
@@ -94,138 +94,63 @@ String _get_mono_user_dir() {
class _GodotSharpDirs {
public:
- String res_data_dir;
String res_metadata_dir;
- String res_config_dir;
- String res_temp_dir;
- String res_temp_assemblies_base_dir;
String res_temp_assemblies_dir;
String mono_user_dir;
- String mono_logs_dir;
-
- String api_assemblies_base_dir;
String api_assemblies_dir;
#ifdef TOOLS_ENABLED
- String mono_solutions_dir;
String build_logs_dir;
-
String data_editor_tools_dir;
-#else
- // Equivalent of res_assemblies_dir, but in the data directory rather than in 'res://'.
- // Only defined on export templates. Used when exporting assemblies outside of PCKs.
- String data_game_assemblies_dir;
-#endif
-
- String data_mono_etc_dir;
- String data_mono_lib_dir;
-
-#ifdef WINDOWS_ENABLED
- String data_mono_bin_dir;
#endif
private:
_GodotSharpDirs() {
- res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().path_join("mono");
+ String res_data_dir = ProjectSettings::get_singleton()->get_project_data_path().path_join("mono");
res_metadata_dir = res_data_dir.path_join("metadata");
- res_config_dir = res_data_dir.path_join("etc").path_join("mono");
// TODO use paths from csproj
- res_temp_dir = res_data_dir.path_join("temp");
- res_temp_assemblies_base_dir = res_temp_dir.path_join("bin");
- res_temp_assemblies_dir = res_temp_assemblies_base_dir.path_join(_get_expected_build_config());
-
- api_assemblies_base_dir = res_data_dir.path_join("assemblies");
+ res_temp_assemblies_dir = res_data_dir.path_join("temp").path_join("bin").path_join(_get_expected_build_config());
#ifdef WEB_ENABLED
mono_user_dir = "user://";
#else
mono_user_dir = _get_mono_user_dir();
#endif
- mono_logs_dir = mono_user_dir.path_join("mono_logs");
-
-#ifdef TOOLS_ENABLED
- mono_solutions_dir = mono_user_dir.path_join("solutions");
- build_logs_dir = mono_user_dir.path_join("build_logs");
-
- String base_path = ProjectSettings::get_singleton()->globalize_path("res://");
-#endif
String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir();
+ String res_dir = OS::get_singleton()->get_bundle_resource_dir();
#ifdef TOOLS_ENABLED
-
String data_dir_root = exe_dir.path_join("GodotSharp");
data_editor_tools_dir = data_dir_root.path_join("Tools");
- api_assemblies_base_dir = data_dir_root.path_join("Api");
-
- String data_mono_root_dir = data_dir_root.path_join("Mono");
- data_mono_etc_dir = data_mono_root_dir.path_join("etc");
-
-#ifdef ANDROID_ENABLED
- data_mono_lib_dir = gdmono::android::support::get_app_native_lib_dir();
-#else
- data_mono_lib_dir = data_mono_root_dir.path_join("lib");
-#endif
-
-#ifdef WINDOWS_ENABLED
- data_mono_bin_dir = data_mono_root_dir.path_join("bin");
-#endif
-
+ String api_assemblies_base_dir = data_dir_root.path_join("Api");
+ build_logs_dir = mono_user_dir.path_join("build_logs");
#ifdef MACOS_ENABLED
if (!DirAccess::exists(data_editor_tools_dir)) {
- data_editor_tools_dir = exe_dir.path_join("../Resources/GodotSharp/Tools");
+ data_editor_tools_dir = res_dir.path_join("GodotSharp").path_join("Tools");
}
-
if (!DirAccess::exists(api_assemblies_base_dir)) {
- api_assemblies_base_dir = exe_dir.path_join("../Resources/GodotSharp/Api");
- }
-
- if (!DirAccess::exists(data_mono_root_dir)) {
- data_mono_etc_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/etc");
- data_mono_lib_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/lib");
+ api_assemblies_base_dir = res_dir.path_join("GodotSharp").path_join("Api");
}
#endif
-
-#else
-
+ api_assemblies_dir = api_assemblies_base_dir.path_join(GDMono::get_expected_api_build_config());
+#else // TOOLS_ENABLED
+ String arch = Engine::get_singleton()->get_architecture_name();
String appname = ProjectSettings::get_singleton()->get("application/config/name");
String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- String data_dir_root = exe_dir.path_join("data_" + appname_safe);
+ String data_dir_root = exe_dir.path_join("data_" + appname_safe + "_" + arch);
if (!DirAccess::exists(data_dir_root)) {
- data_dir_root = exe_dir.path_join("data_Godot");
+ data_dir_root = exe_dir.path_join("data_Godot_" + arch);
}
-
- String data_mono_root_dir = data_dir_root.path_join("Mono");
- data_mono_etc_dir = data_mono_root_dir.path_join("etc");
-
-#ifdef ANDROID_ENABLED
- data_mono_lib_dir = gdmono::android::support::get_app_native_lib_dir();
-#else
- data_mono_lib_dir = data_mono_root_dir.path_join("lib");
- data_game_assemblies_dir = data_dir_root.path_join("Assemblies");
-#endif
-
-#ifdef WINDOWS_ENABLED
- data_mono_bin_dir = data_mono_root_dir.path_join("bin");
-#endif
-
#ifdef MACOS_ENABLED
- if (!DirAccess::exists(data_mono_root_dir)) {
- data_mono_etc_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/etc");
- data_mono_lib_dir = exe_dir.path_join("../Resources/GodotSharp/Mono/lib");
+ if (!DirAccess::exists(data_dir_root)) {
+ data_dir_root = res_dir.path_join("data_" + appname_safe + "_" + arch);
}
-
- if (!DirAccess::exists(data_game_assemblies_dir)) {
- data_game_assemblies_dir = exe_dir.path_join("../Resources/GodotSharp/Assemblies");
+ if (!DirAccess::exists(data_dir_root)) {
+ data_dir_root = res_dir.path_join("data_Godot_" + arch);
}
#endif
-
-#endif
-
-#ifdef TOOLS_ENABLED
- api_assemblies_dir = api_assemblies_base_dir.path_join(GDMono::get_expected_api_build_config());
-#else
api_assemblies_dir = data_dir_root;
#endif
}
@@ -237,26 +162,10 @@ public:
}
};
-String get_res_data_dir() {
- return _GodotSharpDirs::get_singleton().res_data_dir;
-}
-
String get_res_metadata_dir() {
return _GodotSharpDirs::get_singleton().res_metadata_dir;
}
-String get_res_config_dir() {
- return _GodotSharpDirs::get_singleton().res_config_dir;
-}
-
-String get_res_temp_dir() {
- return _GodotSharpDirs::get_singleton().res_temp_dir;
-}
-
-String get_res_temp_assemblies_base_dir() {
- return _GodotSharpDirs::get_singleton().res_temp_assemblies_base_dir;
-}
-
String get_res_temp_assemblies_dir() {
return _GodotSharpDirs::get_singleton().res_temp_assemblies_dir;
}
@@ -265,23 +174,11 @@ String get_api_assemblies_dir() {
return _GodotSharpDirs::get_singleton().api_assemblies_dir;
}
-String get_api_assemblies_base_dir() {
- return _GodotSharpDirs::get_singleton().api_assemblies_base_dir;
-}
-
String get_mono_user_dir() {
return _GodotSharpDirs::get_singleton().mono_user_dir;
}
-String get_mono_logs_dir() {
- return _GodotSharpDirs::get_singleton().mono_logs_dir;
-}
-
#ifdef TOOLS_ENABLED
-String get_mono_solutions_dir() {
- return _GodotSharpDirs::get_singleton().mono_solutions_dir;
-}
-
String get_build_logs_dir() {
return _GodotSharpDirs::get_singleton().build_logs_dir;
}
@@ -289,23 +186,6 @@ String get_build_logs_dir() {
String get_data_editor_tools_dir() {
return _GodotSharpDirs::get_singleton().data_editor_tools_dir;
}
-#else
-String get_data_game_assemblies_dir() {
- return _GodotSharpDirs::get_singleton().data_game_assemblies_dir;
-}
#endif
-String get_data_mono_etc_dir() {
- return _GodotSharpDirs::get_singleton().data_mono_etc_dir;
-}
-
-String get_data_mono_lib_dir() {
- return _GodotSharpDirs::get_singleton().data_mono_lib_dir;
-}
-
-#ifdef WINDOWS_ENABLED
-String get_data_mono_bin_dir() {
- return _GodotSharpDirs::get_singleton().data_mono_bin_dir;
-}
-#endif
} // namespace GodotSharpDirs
diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h
index 03e62ffd82..cdfb8e4787 100644
--- a/modules/mono/godotsharp_dirs.h
+++ b/modules/mono/godotsharp_dirs.h
@@ -35,34 +35,18 @@
namespace GodotSharpDirs {
-String get_res_data_dir();
String get_res_metadata_dir();
-String get_res_config_dir();
-String get_res_temp_dir();
-String get_res_temp_assemblies_base_dir();
String get_res_temp_assemblies_dir();
String get_api_assemblies_dir();
-String get_api_assemblies_base_dir();
String get_mono_user_dir();
-String get_mono_logs_dir();
#ifdef TOOLS_ENABLED
-String get_mono_solutions_dir();
String get_build_logs_dir();
-
String get_data_editor_tools_dir();
-#else
-String get_data_game_assemblies_dir();
#endif
-String get_data_mono_etc_dir();
-String get_data_mono_lib_dir();
-
-#ifdef WINDOWS_ENABLED
-String get_data_mono_bin_dir();
-#endif
} // namespace GodotSharpDirs
#endif // GODOTSHARP_DIRS_H
diff --git a/modules/multiplayer/doc_classes/SceneMultiplayer.xml b/modules/multiplayer/doc_classes/SceneMultiplayer.xml
index 62bb396d15..a7b89f58ac 100644
--- a/modules/multiplayer/doc_classes/SceneMultiplayer.xml
+++ b/modules/multiplayer/doc_classes/SceneMultiplayer.xml
@@ -42,6 +42,10 @@
The root path to use for RPCs and replication. Instead of an absolute path, a relative path will be used to find the node upon which the RPC should be executed.
This effectively allows to have different branches of the scene tree to be managed by different MultiplayerAPI, allowing for example to run both client and server in the same scene.
</member>
+ <member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true">
+ Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server.
+ [b]Note:[/b] Support for this feature may depend on the current [MultiplayerPeer] configuration. See [method MultiplayerPeer.is_server_relay_supported].
+ </member>
</members>
<signals>
<signal name="peer_packet">
diff --git a/modules/multiplayer/multiplayer_synchronizer.cpp b/modules/multiplayer/multiplayer_synchronizer.cpp
index 9755f426d5..95857392c7 100644
--- a/modules/multiplayer/multiplayer_synchronizer.cpp
+++ b/modules/multiplayer/multiplayer_synchronizer.cpp
@@ -118,6 +118,10 @@ void MultiplayerSynchronizer::set_net_id(uint32_t p_net_id) {
}
bool MultiplayerSynchronizer::update_outbound_sync_time(uint64_t p_msec) {
+ if (last_sync_msec == p_msec) {
+ // last_sync_msec has been updated on this frame.
+ return true;
+ }
if (p_msec >= last_sync_msec + interval_msec) {
last_sync_msec = p_msec;
return true;
diff --git a/modules/multiplayer/scene_cache_interface.cpp b/modules/multiplayer/scene_cache_interface.cpp
index b3b642f815..7df9b95b30 100644
--- a/modules/multiplayer/scene_cache_interface.cpp
+++ b/modules/multiplayer/scene_cache_interface.cpp
@@ -105,8 +105,7 @@ void SceneCacheInterface::process_simplify_path(int p_from, const uint8_t *p_pac
multiplayer_peer->set_transfer_channel(0);
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
- multiplayer_peer->set_target_peer(p_from);
- multiplayer_peer->put_packet(packet.ptr(), packet.size());
+ multiplayer->send_command(p_from, packet.ptr(), packet.size());
}
void SceneCacheInterface::process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
@@ -162,10 +161,9 @@ Error SceneCacheInterface::_send_confirm_path(Node *p_node, NodePath p_path, Pat
Error err = OK;
for (int peer_id : p_peers) {
- multiplayer_peer->set_target_peer(peer_id);
multiplayer_peer->set_transfer_channel(0);
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
- err = multiplayer_peer->put_packet(packet.ptr(), packet.size());
+ err = multiplayer->send_command(peer_id, packet.ptr(), packet.size());
ERR_FAIL_COND_V(err != OK, err);
// Insert into confirmed, but as false since it was not confirmed.
psc->confirmed_peers.insert(peer_id, false);
diff --git a/modules/multiplayer/scene_multiplayer.cpp b/modules/multiplayer/scene_multiplayer.cpp
index 3fc1eef366..f94f8ef658 100644
--- a/modules/multiplayer/scene_multiplayer.cpp
+++ b/modules/multiplayer/scene_multiplayer.cpp
@@ -67,12 +67,20 @@ Error SceneMultiplayer::poll() {
const uint8_t *packet;
int len;
+ int channel = multiplayer_peer->get_packet_channel();
+ MultiplayerPeer::TransferMode mode = multiplayer_peer->get_packet_mode();
+
Error err = multiplayer_peer->get_packet(&packet, len);
ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err));
- remote_sender_id = sender;
- _process_packet(sender, packet, len);
- remote_sender_id = 0;
+ if (len && (packet[0] & CMD_MASK) == NETWORK_COMMAND_SYS) {
+ // Sys messages are processed separately since they might call _process_packet themselves.
+ _process_sys(sender, packet, len, mode, channel);
+ } else {
+ remote_sender_id = sender;
+ _process_packet(sender, packet, len);
+ remote_sender_id = 0;
+ }
if (!multiplayer_peer.is_valid()) {
return OK; // It's also possible that a packet or RPC caused a disconnection, so also check here.
@@ -86,6 +94,7 @@ void SceneMultiplayer::clear() {
connected_peers.clear();
packet_cache.clear();
cache->clear();
+ relay_buffer->clear();
}
void SceneMultiplayer::set_root_path(const NodePath &p_path) {
@@ -166,10 +175,123 @@ void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int
case NETWORK_COMMAND_SYNC: {
replicator->on_sync_receive(p_from, p_packet, p_packet_len);
} break;
+ default: {
+ ERR_FAIL_MSG("Invalid network command from " + itos(p_from));
+ } break;
+ }
+}
+
+Error SceneMultiplayer::send_command(int p_to, const uint8_t *p_packet, int p_packet_len) {
+ if (server_relay && get_unique_id() != 1 && p_to != 1 && multiplayer_peer->is_server_relay_supported()) {
+ // Send relay packet.
+ relay_buffer->seek(0);
+ relay_buffer->put_u8(NETWORK_COMMAND_SYS);
+ relay_buffer->put_u8(SYS_COMMAND_RELAY);
+ relay_buffer->put_32(p_to); // Set the destination.
+ relay_buffer->put_data(p_packet, p_packet_len);
+ multiplayer_peer->set_target_peer(1);
+ const Vector<uint8_t> data = relay_buffer->get_data_array();
+ return multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position());
+ }
+ if (p_to < 0) {
+ for (const int &pid : connected_peers) {
+ if (pid == -p_to) {
+ continue;
+ }
+ multiplayer_peer->set_target_peer(pid);
+ multiplayer_peer->put_packet(p_packet, p_packet_len);
+ }
+ return OK;
+ } else {
+ multiplayer_peer->set_target_peer(p_to);
+ return multiplayer_peer->put_packet(p_packet, p_packet_len);
+ }
+}
+
+void SceneMultiplayer::_process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel) {
+ ERR_FAIL_COND_MSG(p_packet_len < SYS_CMD_SIZE, "Invalid packet received. Size too small.");
+ uint8_t sys_cmd_type = p_packet[1];
+ int32_t peer = int32_t(decode_uint32(&p_packet[2]));
+ switch (sys_cmd_type) {
+ case SYS_COMMAND_ADD_PEER: {
+ ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
+ _add_peer(peer);
+ } break;
+ case SYS_COMMAND_DEL_PEER: {
+ ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
+ _del_peer(peer);
+ } break;
+ case SYS_COMMAND_RELAY: {
+ ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported());
+ ERR_FAIL_COND(p_packet_len < SYS_CMD_SIZE + 1);
+ const uint8_t *packet = p_packet + SYS_CMD_SIZE;
+ int len = p_packet_len - SYS_CMD_SIZE;
+ bool should_process = false;
+ if (get_unique_id() == 1) { // I am the server.
+ // Direct messages to server should not go through relay.
+ ERR_FAIL_COND(peer > 0 && !connected_peers.has(peer));
+ // Send relay packet.
+ relay_buffer->seek(0);
+ relay_buffer->put_u8(NETWORK_COMMAND_SYS);
+ relay_buffer->put_u8(SYS_COMMAND_RELAY);
+ relay_buffer->put_32(p_from); // Set the source.
+ relay_buffer->put_data(packet, len);
+ const Vector<uint8_t> data = relay_buffer->get_data_array();
+ multiplayer_peer->set_transfer_mode(p_mode);
+ multiplayer_peer->set_transfer_channel(p_channel);
+ if (peer > 0) {
+ multiplayer_peer->set_target_peer(peer);
+ multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position());
+ } else {
+ for (const int &P : connected_peers) {
+ // Not to sender, nor excluded.
+ if (P == p_from || (peer < 0 && P != -peer)) {
+ continue;
+ }
+ multiplayer_peer->set_target_peer(P);
+ multiplayer_peer->put_packet(data.ptr(), relay_buffer->get_position());
+ }
+ }
+ if (peer == 0 || peer == -1) {
+ should_process = true;
+ peer = p_from; // Process as the source.
+ }
+ } else {
+ ERR_FAIL_COND(p_from != 1); // Bug.
+ should_process = true;
+ }
+ if (should_process) {
+ remote_sender_id = peer;
+ _process_packet(peer, packet, len);
+ remote_sender_id = 0;
+ }
+ } break;
+ default: {
+ ERR_FAIL();
+ }
}
}
void SceneMultiplayer::_add_peer(int p_id) {
+ if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
+ // Notify others of connection, and send connected peers to newly connected one.
+ uint8_t buf[SYS_CMD_SIZE];
+ buf[0] = NETWORK_COMMAND_SYS;
+ buf[1] = SYS_COMMAND_ADD_PEER;
+ multiplayer_peer->set_transfer_channel(0);
+ multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
+ for (const int &P : connected_peers) {
+ // Send new peer to already connected.
+ encode_uint32(p_id, &buf[2]);
+ multiplayer_peer->set_target_peer(P);
+ multiplayer_peer->put_packet(buf, sizeof(buf));
+ // Send already connected to new peer.
+ encode_uint32(P, &buf[2]);
+ multiplayer_peer->set_target_peer(p_id);
+ multiplayer_peer->put_packet(buf, sizeof(buf));
+ }
+ }
+
connected_peers.insert(p_id);
cache->on_peer_change(p_id, true);
replicator->on_peer_change(p_id, true);
@@ -177,6 +299,23 @@ void SceneMultiplayer::_add_peer(int p_id) {
}
void SceneMultiplayer::_del_peer(int p_id) {
+ if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
+ // Notify others of disconnection.
+ uint8_t buf[SYS_CMD_SIZE];
+ buf[0] = NETWORK_COMMAND_SYS;
+ buf[1] = SYS_COMMAND_DEL_PEER;
+ multiplayer_peer->set_transfer_channel(0);
+ multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
+ encode_uint32(p_id, &buf[2]);
+ for (const int &P : connected_peers) {
+ if (P == p_id) {
+ continue;
+ }
+ multiplayer_peer->set_target_peer(P);
+ multiplayer_peer->put_packet(buf, sizeof(buf));
+ }
+ }
+
replicator->on_peer_change(p_id, false);
cache->on_peer_change(p_id, false);
connected_peers.erase(p_id);
@@ -209,11 +348,9 @@ Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, Multiplayer
packet_cache.write[0] = NETWORK_COMMAND_RAW;
memcpy(&packet_cache.write[1], &r[0], p_data.size());
- multiplayer_peer->set_target_peer(p_to);
multiplayer_peer->set_transfer_channel(p_channel);
multiplayer_peer->set_transfer_mode(p_mode);
-
- return multiplayer_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
+ return send_command(p_to, packet_cache.ptr(), p_data.size() + 1);
}
void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
@@ -303,6 +440,15 @@ Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_con
return ERR_INVALID_PARAMETER;
}
+void SceneMultiplayer::set_server_relay_enabled(bool p_enabled) {
+ ERR_FAIL_COND_MSG(multiplayer_peer.is_valid() && multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_DISCONNECTED, "Cannot change the server relay option while the multiplayer peer is active.");
+ server_relay = p_enabled;
+}
+
+bool SceneMultiplayer::is_server_relay_enabled() const {
+ return server_relay;
+}
+
void SceneMultiplayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path);
ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path);
@@ -311,17 +457,22 @@ void SceneMultiplayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections);
ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding);
ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed);
+ ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &SceneMultiplayer::set_server_relay_enabled);
+ ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &SceneMultiplayer::is_server_relay_enabled);
ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
+
ADD_PROPERTY_DEFAULT("refuse_new_connections", false);
ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
}
SceneMultiplayer::SceneMultiplayer() {
+ relay_buffer.instantiate();
replicator = Ref<SceneReplicationInterface>(memnew(SceneReplicationInterface(this)));
rpc = Ref<SceneRPCInterface>(memnew(SceneRPCInterface(this)));
cache = Ref<SceneCacheInterface>(memnew(SceneCacheInterface(this)));
diff --git a/modules/multiplayer/scene_multiplayer.h b/modules/multiplayer/scene_multiplayer.h
index a99cca7b21..06d7b2c7a7 100644
--- a/modules/multiplayer/scene_multiplayer.h
+++ b/modules/multiplayer/scene_multiplayer.h
@@ -49,6 +49,17 @@ public:
NETWORK_COMMAND_SPAWN,
NETWORK_COMMAND_DESPAWN,
NETWORK_COMMAND_SYNC,
+ NETWORK_COMMAND_SYS,
+ };
+
+ enum SysCommands {
+ SYS_COMMAND_ADD_PEER,
+ SYS_COMMAND_DEL_PEER,
+ SYS_COMMAND_RELAY,
+ };
+
+ enum {
+ SYS_CMD_SIZE = 6, // Command + sys command + peer_id (+ optional payload).
};
// For each command, the 4 MSB can contain custom flags, as defined by subsystems.
@@ -74,6 +85,8 @@ private:
NodePath root_path;
bool allow_object_decoding = false;
+ bool server_relay = true;
+ Ref<StreamPeerBuffer> relay_buffer;
Ref<SceneCacheInterface> cache;
Ref<SceneReplicationInterface> replicator;
@@ -84,6 +97,7 @@ protected:
void _process_packet(int p_from, const uint8_t *p_packet, int p_packet_len);
void _process_raw(int p_from, const uint8_t *p_packet, int p_packet_len);
+ void _process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel);
void _add_peer(int p_id);
void _del_peer(int p_id);
@@ -111,6 +125,7 @@ public:
void set_root_path(const NodePath &p_path);
NodePath get_root_path() const;
+ Error send_command(int p_to, const uint8_t *p_packet, int p_packet_len); // Used internally to relay packets when needed.
Error send_bytes(Vector<uint8_t> p_data, int p_to = MultiplayerPeer::TARGET_PEER_BROADCAST, MultiplayerPeer::TransferMode p_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE, int p_channel = 0);
String get_rpc_md5(const Object *p_obj);
@@ -123,6 +138,9 @@ public:
void set_allow_object_decoding(bool p_enable);
bool is_object_decoding_allowed() const;
+ void set_server_relay_enabled(bool p_enabled);
+ bool is_server_relay_enabled() const;
+
Ref<SceneCacheInterface> get_path_cache() { return cache; }
#ifdef DEBUG_ENABLED
diff --git a/modules/multiplayer/scene_replication_interface.cpp b/modules/multiplayer/scene_replication_interface.cpp
index df9985916b..da425076a4 100644
--- a/modules/multiplayer/scene_replication_interface.cpp
+++ b/modules/multiplayer/scene_replication_interface.cpp
@@ -261,11 +261,11 @@ Error SceneReplicationInterface::_update_sync_visibility(int p_peer, Multiplayer
if (p_peer == 0) {
for (KeyValue<int, PeerInfo> &E : peers_info) {
// Might be visible to this specific peer.
- is_visible = is_visible || p_sync->is_visible_to(E.key);
- if (is_visible == E.value.sync_nodes.has(sid)) {
+ bool is_visible_to_peer = is_visible || p_sync->is_visible_to(E.key);
+ if (is_visible_to_peer == E.value.sync_nodes.has(sid)) {
continue;
}
- if (is_visible) {
+ if (is_visible_to_peer) {
E.value.sync_nodes.insert(sid);
} else {
E.value.sync_nodes.erase(sid);
@@ -370,10 +370,9 @@ Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size,
#endif
Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
- peer->set_target_peer(p_peer);
peer->set_transfer_channel(0);
peer->set_transfer_mode(p_reliable ? MultiplayerPeer::TRANSFER_MODE_RELIABLE : MultiplayerPeer::TRANSFER_MODE_UNRELIABLE);
- return peer->put_packet(p_buffer, p_size);
+ return multiplayer->send_command(p_peer, p_buffer, p_size);
}
Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len) {
diff --git a/modules/multiplayer/scene_rpc_interface.cpp b/modules/multiplayer/scene_rpc_interface.cpp
index 65090b9316..acc113c901 100644
--- a/modules/multiplayer/scene_rpc_interface.cpp
+++ b/modules/multiplayer/scene_rpc_interface.cpp
@@ -412,8 +412,7 @@ void SceneRPCInterface::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, con
if (has_all_peers) {
// They all have verified paths, so send fast.
- peer->set_target_peer(p_to); // To all of you.
- peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
+ multiplayer->send_command(p_to, packet_cache.ptr(), ofs);
} else {
// Unreachable because the node ID is never compressed if the peers doesn't know it.
CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
@@ -438,16 +437,14 @@ void SceneRPCInterface::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, con
bool confirmed = multiplayer->get_path_cache()->is_cache_confirmed(from_path, P);
- peer->set_target_peer(P); // To this one specifically.
-
if (confirmed) {
// This one confirmed path, so use id.
encode_uint32(psc_id, &(packet_cache.write[1]));
- peer->put_packet(packet_cache.ptr(), ofs);
+ multiplayer->send_command(P, packet_cache.ptr(), ofs);
} else {
// This one did not confirm path yet, so use entire path (sorry!).
encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
- peer->put_packet(packet_cache.ptr(), ofs + path_len);
+ multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);
}
}
}
diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp
index f989fc45a5..f0d3e329ce 100644
--- a/modules/navigation/navigation_mesh_generator.cpp
+++ b/modules/navigation/navigation_mesh_generator.cpp
@@ -266,10 +266,10 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans
if (err == OK) {
PackedVector3Array faces;
- for (int j = 0; j < md.faces.size(); ++j) {
- Geometry3D::MeshData::Face face = md.faces[j];
+ for (uint32_t j = 0; j < md.faces.size(); ++j) {
+ const Geometry3D::MeshData::Face &face = md.faces[j];
- for (int k = 2; k < face.indices.size(); ++k) {
+ for (uint32_t k = 2; k < face.indices.size(); ++k) {
faces.push_back(md.vertices[face.indices[0]]);
faces.push_back(md.vertices[face.indices[k - 1]]);
faces.push_back(md.vertices[face.indices[k]]);
@@ -392,10 +392,10 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans
if (err == OK) {
PackedVector3Array faces;
- for (int j = 0; j < md.faces.size(); ++j) {
- Geometry3D::MeshData::Face face = md.faces[j];
+ for (uint32_t j = 0; j < md.faces.size(); ++j) {
+ const Geometry3D::MeshData::Face &face = md.faces[j];
- for (int k = 2; k < face.indices.size(); ++k) {
+ for (uint32_t k = 2; k < face.indices.size(); ++k) {
faces.push_back(md.vertices[face.indices[0]]);
faces.push_back(md.vertices[face.indices[k - 1]]);
faces.push_back(md.vertices[face.indices[k]]);
diff --git a/modules/noise/noise_texture_2d.cpp b/modules/noise/noise_texture_2d.cpp
index 23d60c4866..8c785d7591 100644
--- a/modules/noise/noise_texture_2d.cpp
+++ b/modules/noise/noise_texture_2d.cpp
@@ -176,9 +176,7 @@ Ref<Image> NoiseTexture2D::_modulate_with_gradient(Ref<Image> p_image, Ref<Gradi
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);
+ Ref<Image> new_image = Image::create_empty(width, height, false, Image::FORMAT_RGBA8);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
diff --git a/modules/openxr/SCsub b/modules/openxr/SCsub
index 5ac167ad98..b5978ab134 100644
--- a/modules/openxr/SCsub
+++ b/modules/openxr/SCsub
@@ -96,6 +96,7 @@ env_openxr.add_source_files(module_obj, "extensions/openxr_composition_layer_dep
env_openxr.add_source_files(module_obj, "extensions/openxr_htc_vive_tracker_extension.cpp")
env_openxr.add_source_files(module_obj, "extensions/openxr_hand_tracking_extension.cpp")
env_openxr.add_source_files(module_obj, "extensions/openxr_fb_passthrough_extension_wrapper.cpp")
+env_openxr.add_source_files(module_obj, "extensions/openxr_fb_display_refresh_rate_extension.cpp")
env.modules_sources += module_obj
diff --git a/modules/openxr/action_map/openxr_action_map.cpp b/modules/openxr/action_map/openxr_action_map.cpp
index 185e44c29d..123f860ce9 100644
--- a/modules/openxr/action_map/openxr_action_map.cpp
+++ b/modules/openxr/action_map/openxr_action_map.cpp
@@ -224,7 +224,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our interaction profiles
Ref<OpenXRInteractionProfile> profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/khr/simple_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -236,7 +236,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Vive controller profile
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -257,7 +257,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our WMR controller profile
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/microsoft/motion_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -280,7 +280,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Meta touch controller profile
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/oculus/touch_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -305,7 +305,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Valve index controller profile
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/valve/index_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -333,7 +333,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our HP MR controller profile
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/hp/mixed_reality_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -356,7 +356,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Samsung Odyssey controller profile,
// Note that this controller is only identified specifically on WMR, on SteamVR this is identified as a normal WMR controller.
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/samsung/odyssey_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -379,7 +379,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Vive Cosmos controller
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_cosmos_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -403,7 +403,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Note, Vive Focus 3 currently is not yet supported as a stand alone device
// however HTC currently has a beta OpenXR runtime in testing we may support in the near future
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_focus3_controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
@@ -427,7 +427,7 @@ void OpenXRActionMap::create_default_action_sets() {
// Create our Huawei controller
profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/huawei/controller");
- profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
+ profile->add_new_binding(default_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose");
profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose");
profile->add_new_binding(palm_pose, "/user/hand/left/input/palm_ext/pose,/user/hand/right/input/palm_ext/pose");
diff --git a/modules/openxr/doc_classes/OpenXRInterface.xml b/modules/openxr/doc_classes/OpenXRInterface.xml
index 25bf496de9..f089fd066e 100644
--- a/modules/openxr/doc_classes/OpenXRInterface.xml
+++ b/modules/openxr/doc_classes/OpenXRInterface.xml
@@ -10,6 +10,19 @@
<tutorials>
<link title="Setting up XR">$DOCS_URL/tutorials/xr/setting_up_xr.html</link>
</tutorials>
+ <methods>
+ <method name="get_available_display_refresh_rates" qualifiers="const">
+ <return type="Array" />
+ <description>
+ Returns display refresh rates supported by the current HMD. Only returned if this feature is supported by the OpenXR runtime and after the interface has been initialized.
+ </description>
+ </method>
+ </methods>
+ <members>
+ <member name="display_refresh_rate" type="float" setter="set_display_refresh_rate" getter="get_display_refresh_rate" default="0.0">
+ The display refresh rate for the current HMD. Only functional if this feature is supported by the OpenXR runtime and after the interface has been initialized.
+ </member>
+ </members>
<signals>
<signal name="pose_recentered">
<description>
diff --git a/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp
new file mode 100644
index 0000000000..c0bbaea5b4
--- /dev/null
+++ b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.cpp
@@ -0,0 +1,123 @@
+/*************************************************************************/
+/* openxr_fb_display_refresh_rate_extension.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 "openxr_fb_display_refresh_rate_extension.h"
+
+OpenXRDisplayRefreshRateExtension *OpenXRDisplayRefreshRateExtension::singleton = nullptr;
+
+OpenXRDisplayRefreshRateExtension *OpenXRDisplayRefreshRateExtension::get_singleton() {
+ return singleton;
+}
+
+OpenXRDisplayRefreshRateExtension::OpenXRDisplayRefreshRateExtension(OpenXRAPI *p_openxr_api) :
+ OpenXRExtensionWrapper(p_openxr_api) {
+ singleton = this;
+
+ // Extensions we use for our hand tracking.
+ request_extensions[XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME] = &display_refresh_rate_ext;
+}
+
+OpenXRDisplayRefreshRateExtension::~OpenXRDisplayRefreshRateExtension() {
+ display_refresh_rate_ext = false;
+}
+
+void OpenXRDisplayRefreshRateExtension::on_instance_created(const XrInstance p_instance) {
+ if (display_refresh_rate_ext) {
+ EXT_INIT_XR_FUNC(xrEnumerateDisplayRefreshRatesFB);
+ EXT_INIT_XR_FUNC(xrGetDisplayRefreshRateFB);
+ EXT_INIT_XR_FUNC(xrRequestDisplayRefreshRateFB);
+ }
+}
+
+void OpenXRDisplayRefreshRateExtension::on_instance_destroyed() {
+ display_refresh_rate_ext = false;
+}
+
+float OpenXRDisplayRefreshRateExtension::get_refresh_rate() const {
+ float refresh_rate = 0.0;
+
+ if (display_refresh_rate_ext) {
+ float rate;
+ XrResult result = xrGetDisplayRefreshRateFB(openxr_api->get_session(), &rate);
+ if (XR_FAILED(result)) {
+ print_line("OpenXR: Failed to obtain refresh rate [", openxr_api->get_error_string(result), "]");
+ } else {
+ refresh_rate = rate;
+ }
+ }
+
+ return refresh_rate;
+}
+
+void OpenXRDisplayRefreshRateExtension::set_refresh_rate(float p_refresh_rate) {
+ if (display_refresh_rate_ext) {
+ XrResult result = xrRequestDisplayRefreshRateFB(openxr_api->get_session(), p_refresh_rate);
+ if (XR_FAILED(result)) {
+ print_line("OpenXR: Failed to set refresh rate [", openxr_api->get_error_string(result), "]");
+ }
+ }
+}
+
+Array OpenXRDisplayRefreshRateExtension::get_available_refresh_rates() const {
+ Array arr;
+ XrResult result;
+
+ if (display_refresh_rate_ext) {
+ uint32_t display_refresh_rate_count = 0;
+ result = xrEnumerateDisplayRefreshRatesFB(openxr_api->get_session(), 0, &display_refresh_rate_count, nullptr);
+ if (XR_FAILED(result)) {
+ print_line("OpenXR: Failed to obtain refresh rates count [", openxr_api->get_error_string(result), "]");
+ }
+
+ if (display_refresh_rate_count > 0) {
+ float *display_refresh_rates = (float *)memalloc(sizeof(float) * display_refresh_rate_count);
+ if (display_refresh_rates == nullptr) {
+ print_line("OpenXR: Failed to obtain refresh rates memory buffer [", openxr_api->get_error_string(result), "]");
+ return arr;
+ }
+
+ result = xrEnumerateDisplayRefreshRatesFB(openxr_api->get_session(), display_refresh_rate_count, &display_refresh_rate_count, display_refresh_rates);
+ if (XR_FAILED(result)) {
+ print_line("OpenXR: Failed to obtain refresh rates count [", openxr_api->get_error_string(result), "]");
+ memfree(display_refresh_rates);
+ return arr;
+ }
+
+ for (uint32_t i = 0; i < display_refresh_rate_count; i++) {
+ float refresh_rate = display_refresh_rates[i];
+ arr.push_back(Variant(refresh_rate));
+ }
+
+ memfree(display_refresh_rates);
+ }
+ }
+
+ return arr;
+}
diff --git a/modules/websocket/websocket_client.h b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h
index e747aee4e4..dcd52fe4d1 100644
--- a/modules/websocket/websocket_client.h
+++ b/modules/openxr/extensions/openxr_fb_display_refresh_rate_extension.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* websocket_client.h */
+/* openxr_fb_display_refresh_rate_extension.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,48 +28,43 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef WEBSOCKET_CLIENT_H
-#define WEBSOCKET_CLIENT_H
+#ifndef OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H
+#define OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H
-#include "core/crypto/crypto.h"
-#include "core/error/error_list.h"
-#include "websocket_multiplayer_peer.h"
-#include "websocket_peer.h"
+// This extension gives us access to the possible display refresh rates
+// supported by the HMD.
+// While this is an FB extension it has been adopted by most runtimes and
+// will likely become core in the near future.
-class WebSocketClient : public WebSocketMultiplayerPeer {
- GDCLASS(WebSocketClient, WebSocketMultiplayerPeer);
- GDCICLASS(WebSocketClient);
+#include "../openxr_api.h"
+#include "../util.h"
-protected:
- Ref<WebSocketPeer> _peer;
- bool verify_tls = true;
- Ref<X509Certificate> tls_cert;
-
- static void _bind_methods();
+#include "openxr_extension_wrapper.h"
+class OpenXRDisplayRefreshRateExtension : public OpenXRExtensionWrapper {
public:
- Error connect_to_url(String p_url, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false, const Vector<String> p_custom_headers = Vector<String>());
+ static OpenXRDisplayRefreshRateExtension *get_singleton();
+
+ OpenXRDisplayRefreshRateExtension(OpenXRAPI *p_openxr_api);
+ virtual ~OpenXRDisplayRefreshRateExtension() override;
+
+ virtual void on_instance_created(const XrInstance p_instance) override;
+ virtual void on_instance_destroyed() override;
- void set_verify_tls_enabled(bool p_verify_tls);
- bool is_verify_tls_enabled() const;
- Ref<X509Certificate> get_trusted_tls_certificate() const;
- void set_trusted_tls_certificate(Ref<X509Certificate> p_cert);
+ float get_refresh_rate() const;
+ void set_refresh_rate(float p_refresh_rate);
- virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0;
- virtual void disconnect_from_host(int p_code = 1000, String p_reason = "") = 0;
- virtual IPAddress get_connected_host() const = 0;
- virtual uint16_t get_connected_port() const = 0;
+ Array get_available_refresh_rates() const;
- virtual bool is_server() const override;
+private:
+ static OpenXRDisplayRefreshRateExtension *singleton;
- void _on_peer_packet();
- void _on_connect(String p_protocol);
- void _on_close_request(int p_code, String p_reason);
- void _on_disconnect(bool p_was_clean);
- void _on_error();
+ bool display_refresh_rate_ext = false;
- WebSocketClient();
- ~WebSocketClient();
+ // OpenXR API call wrappers
+ EXT_PROTO_XRRESULT_FUNC4(xrEnumerateDisplayRefreshRatesFB, (XrSession), session, (uint32_t), displayRefreshRateCapacityInput, (uint32_t *), displayRefreshRateCountOutput, (float *), displayRefreshRates);
+ EXT_PROTO_XRRESULT_FUNC2(xrGetDisplayRefreshRateFB, (XrSession), session, (float *), display_refresh_rate);
+ EXT_PROTO_XRRESULT_FUNC2(xrRequestDisplayRefreshRateFB, (XrSession), session, (float), display_refresh_rate);
};
-#endif // WEBSOCKET_CLIENT_H
+#endif // OPENXR_FB_DISPLAY_REFRESH_RATE_EXTENSION_H
diff --git a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp
index 88cc7c061c..4d996e6283 100644
--- a/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp
+++ b/modules/openxr/extensions/openxr_htc_vive_tracker_extension.cpp
@@ -69,6 +69,34 @@ bool OpenXRHTCViveTrackerExtension::on_event_polled(const XrEventDataBuffer &eve
bool OpenXRHTCViveTrackerExtension::is_path_supported(const String &p_path) {
if (p_path == "/interaction_profiles/htc/vive_tracker_htcx") {
return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/handheld_object") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/left_foot") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/right_foot") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/left_shoulder") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/right_shoulder") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/left_elbow") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/right_elbow") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/left_knee") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/right_knee") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/waist") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/chest") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/chest") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/camera") {
+ return available;
+ } else if (p_path == "/user/vive_tracker_htcx/role/keyboard") {
+ return available;
}
// Not a path under this extensions control, so we return true;
diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp
index 01107ebcc9..1ff1dac512 100644
--- a/modules/openxr/openxr_api.cpp
+++ b/modules/openxr/openxr_api.cpp
@@ -50,6 +50,7 @@
#endif
#include "extensions/openxr_composition_layer_depth_extension.h"
+#include "extensions/openxr_fb_display_refresh_rate_extension.h"
#include "extensions/openxr_fb_passthrough_extension_wrapper.h"
#include "extensions/openxr_hand_tracking_extension.h"
#include "extensions/openxr_htc_vive_tracker_extension.h"
@@ -131,11 +132,9 @@ bool OpenXRAPI::load_layer_properties() {
result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
-#ifdef DEBUG
for (uint32_t i = 0; i < num_layer_properties; i++) {
- print_line("OpenXR: Found OpenXR layer ", layer_properties[i].layerName);
+ print_verbose(String("OpenXR: Found OpenXR layer ") + layer_properties[i].layerName);
}
-#endif
return true;
}
@@ -163,11 +162,9 @@ bool OpenXRAPI::load_supported_extensions() {
result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
-#ifdef DEBUG
for (uint32_t i = 0; i < num_supported_extensions; i++) {
- print_line("OpenXR: Found OpenXR extension ", supported_extensions[i].extensionName);
+ print_verbose(String("OpenXR: Found OpenXR extension ") + supported_extensions[i].extensionName);
}
-#endif
return true;
}
@@ -175,17 +172,10 @@ bool OpenXRAPI::load_supported_extensions() {
bool OpenXRAPI::is_extension_supported(const String &p_extension) const {
for (uint32_t i = 0; i < num_supported_extensions; i++) {
if (supported_extensions[i].extensionName == p_extension) {
-#ifdef DEBUG
- print_line("OpenXR: requested extension", p_extension, "is supported");
-#endif
return true;
}
}
-#ifdef DEBUG
- print_line("OpenXR: requested extension", p_extension, "is not supported");
-#endif
-
return false;
}
@@ -401,11 +391,9 @@ bool OpenXRAPI::load_supported_view_configuration_types() {
result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations");
-#ifdef DEBUG
for (uint32_t i = 0; i < num_view_configuration_types; i++) {
- print_line("OpenXR: Found supported view configuration ", OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i]));
+ print_verbose(String("OpenXR: Found supported view configuration ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i]));
}
-#endif
return true;
}
@@ -454,17 +442,15 @@ bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType
result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations");
-#ifdef DEBUG
for (uint32_t i = 0; i < view_count; i++) {
- print_line("OpenXR: Found supported view configuration view");
- print_line(" - width: ", view_configuration_views[i].maxImageRectWidth);
- print_line(" - height: ", view_configuration_views[i].maxImageRectHeight);
- print_line(" - sample count: ", view_configuration_views[i].maxSwapchainSampleCount);
- print_line(" - recommended render width: ", view_configuration_views[i].recommendedImageRectWidth);
- print_line(" - recommended render height: ", view_configuration_views[i].recommendedImageRectHeight);
- print_line(" - recommended render sample count: ", view_configuration_views[i].recommendedSwapchainSampleCount);
+ print_verbose("OpenXR: Found supported view configuration view");
+ print_verbose(String(" - width: ") + itos(view_configuration_views[i].maxImageRectWidth));
+ print_verbose(String(" - height: ") + itos(view_configuration_views[i].maxImageRectHeight));
+ print_verbose(String(" - sample count: ") + itos(view_configuration_views[i].maxSwapchainSampleCount));
+ print_verbose(String(" - recommended render width: ") + itos(view_configuration_views[i].recommendedImageRectWidth));
+ print_verbose(String(" - recommended render height: ") + itos(view_configuration_views[i].recommendedImageRectHeight));
+ print_verbose(String(" - recommended render sample count: ") + itos(view_configuration_views[i].recommendedSwapchainSampleCount));
}
-#endif
return true;
}
@@ -546,11 +532,9 @@ bool OpenXRAPI::load_supported_reference_spaces() {
result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces");
- // #ifdef DEBUG
for (uint32_t i = 0; i < num_reference_spaces; i++) {
- print_line("OpenXR: Found supported reference space ", OpenXRUtil::get_reference_space_name(supported_reference_spaces[i]));
+ print_verbose(String("OpenXR: Found supported reference space ") + OpenXRUtil::get_reference_space_name(supported_reference_spaces[i]));
}
- // #endif
return true;
}
@@ -643,11 +627,9 @@ bool OpenXRAPI::load_supported_swapchain_formats() {
result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats);
ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats");
- // #ifdef DEBUG
for (uint32_t i = 0; i < num_swapchain_formats; i++) {
- print_line("OpenXR: Found supported swapchain format ", get_swapchain_format_name(supported_swapchain_formats[i]));
+ print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(supported_swapchain_formats[i]));
}
- // #endif
return true;
}
@@ -706,7 +688,7 @@ bool OpenXRAPI::create_swapchains() {
swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
print_line("Couldn't find usable color swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
} else {
- print_line("Using color swap chain format:", get_swapchain_format_name(swapchain_format_to_use));
+ print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
}
if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain, &swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data)) {
@@ -741,7 +723,7 @@ bool OpenXRAPI::create_swapchains() {
swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
print_line("Couldn't find usable depth swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
} else {
- print_line("Using depth swap chain format:", get_swapchain_format_name(swapchain_format_to_use));
+ print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
}
if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain, &swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data)) {
@@ -900,9 +882,7 @@ bool OpenXRAPI::create_swapchain(XrSwapchainUsageFlags p_usage_flags, int64_t p_
}
bool OpenXRAPI::on_state_idle() {
-#ifdef DEBUG
- print_line("On state idle");
-#endif
+ print_verbose("On state idle");
for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
wrapper->on_state_idle();
@@ -912,9 +892,7 @@ bool OpenXRAPI::on_state_idle() {
}
bool OpenXRAPI::on_state_ready() {
-#ifdef DEBUG
- print_line("On state ready");
-#endif
+ print_verbose("On state ready");
// begin session
XrSessionBeginInfo session_begin_info = {
@@ -957,9 +935,7 @@ bool OpenXRAPI::on_state_ready() {
}
bool OpenXRAPI::on_state_synchronized() {
-#ifdef DEBUG
- print_line("On state synchronized");
-#endif
+ print_verbose("On state synchronized");
// Just in case, see if we already have active trackers...
List<RID> trackers;
@@ -976,9 +952,7 @@ bool OpenXRAPI::on_state_synchronized() {
}
bool OpenXRAPI::on_state_visible() {
-#ifdef DEBUG
- print_line("On state visible");
-#endif
+ print_verbose("On state visible");
for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
wrapper->on_state_visible();
@@ -992,9 +966,7 @@ bool OpenXRAPI::on_state_visible() {
}
bool OpenXRAPI::on_state_focused() {
-#ifdef DEBUG
- print_line("On state focused");
-#endif
+ print_verbose("On state focused");
for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
wrapper->on_state_focused();
@@ -1008,9 +980,7 @@ bool OpenXRAPI::on_state_focused() {
}
bool OpenXRAPI::on_state_stopping() {
-#ifdef DEBUG
- print_line("On state stopping");
-#endif
+ print_verbose("On state stopping");
if (xr_interface) {
xr_interface->on_state_stopping();
@@ -1036,9 +1006,7 @@ bool OpenXRAPI::on_state_stopping() {
}
bool OpenXRAPI::on_state_loss_pending() {
-#ifdef DEBUG
- print_line("On state loss pending");
-#endif
+ print_verbose("On state loss pending");
for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
wrapper->on_state_loss_pending();
@@ -1050,9 +1018,7 @@ bool OpenXRAPI::on_state_loss_pending() {
}
bool OpenXRAPI::on_state_exiting() {
-#ifdef DEBUG
- print_line("On state existing");
-#endif
+ print_verbose("On state existing");
for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
wrapper->on_state_exiting();
@@ -1324,12 +1290,10 @@ XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform,
head_pose_confidence = confidence;
if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
print_line("OpenXR head space location not valid (check tracking?)");
-#ifdef DEBUG
} else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
- print_line("OpenVR Head pose now tracking with low confidence");
+ print_verbose("OpenVR Head pose now tracking with low confidence");
} else {
- print_line("OpenVR Head pose now tracking with high confidence");
-#endif
+ print_verbose("OpenVR Head pose now tracking with high confidence");
}
}
@@ -1417,7 +1381,7 @@ bool OpenXRAPI::poll_events() {
// TODO We get this event if we're about to loose our OpenXR instance.
// We should queue exiting Godot at this point.
- print_verbose("OpenXR EVENT: instance loss pending at " + itos(event->lossTime));
+ print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
return false;
} break;
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
@@ -1425,9 +1389,9 @@ bool OpenXRAPI::poll_events() {
session_state = event->state;
if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
- print_verbose("OpenXR EVENT: session state changed to UNKNOWN - " + itos(session_state));
+ print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
} else {
- print_verbose("OpenXR EVENT: session state changed to " + OpenXRUtil::get_session_state_name(session_state));
+ print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
switch (session_state) {
case XR_SESSION_STATE_IDLE:
@@ -1462,7 +1426,7 @@ bool OpenXRAPI::poll_events() {
case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
- print_verbose("OpenXR EVENT: reference space type " + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
+ print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
if (event->poseValid && xr_interface) {
xr_interface->on_pose_recentered();
}
@@ -1481,7 +1445,7 @@ bool OpenXRAPI::poll_events() {
} break;
default:
if (!handled) {
- print_verbose("OpenXR Unhandled event type " + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
+ print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
}
break;
}
@@ -1589,7 +1553,7 @@ void OpenXRAPI::pre_render() {
if (frame_state.predictedDisplayPeriod > 500000000) {
// display period more then 0.5 seconds? must be wrong data
- print_verbose("OpenXR resetting invalid display period " + rtos(frame_state.predictedDisplayPeriod));
+ print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
frame_state.predictedDisplayPeriod = 0;
}
@@ -1636,13 +1600,11 @@ void OpenXRAPI::pre_render() {
}
if (view_pose_valid != pose_valid) {
view_pose_valid = pose_valid;
-#ifdef DEBUG
if (!view_pose_valid) {
- print_line("OpenXR View pose became invalid");
+ print_verbose("OpenXR View pose became invalid");
} else {
- print_line("OpenXR View pose became valid");
+ print_verbose("OpenXR View pose became valid");
}
-#endif
}
// let's start our frame..
@@ -1787,6 +1749,31 @@ void OpenXRAPI::end_frame() {
}
}
+float OpenXRAPI::get_display_refresh_rate() const {
+ OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
+ if (drrext) {
+ return drrext->get_refresh_rate();
+ }
+
+ return 0.0;
+}
+
+void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
+ OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
+ if (drrext != nullptr) {
+ drrext->set_refresh_rate(p_refresh_rate);
+ }
+}
+
+Array OpenXRAPI::get_available_display_refresh_rates() const {
+ OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
+ if (drrext != nullptr) {
+ return drrext->get_available_refresh_rates();
+ }
+
+ return Array();
+}
+
OpenXRAPI::OpenXRAPI() {
// OpenXRAPI is only constructed if OpenXR is enabled.
singleton = this;
@@ -1856,6 +1843,7 @@ OpenXRAPI::OpenXRAPI() {
register_extension_wrapper(memnew(OpenXRHTCViveTrackerExtension(this)));
register_extension_wrapper(memnew(OpenXRHandTrackingExtension(this)));
register_extension_wrapper(memnew(OpenXRFbPassthroughExtensionWrapper(this)));
+ register_extension_wrapper(memnew(OpenXRDisplayRefreshRateExtension(this)));
}
OpenXRAPI::~OpenXRAPI() {
@@ -2081,8 +2069,6 @@ RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_n
copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
- // print_line("Creating action set ", action_set_info.actionSetName, " - ", action_set_info.localizedActionSetName, " (", itos(action_set_info.priority), ")");
-
XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
if (XR_FAILED(result)) {
print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
@@ -2236,8 +2222,6 @@ RID OpenXRAPI::action_create(RID p_action_set, const String p_name, const String
copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
- // print_line("Creating action ", action_info.actionName, action_info.localizedActionName, action_info.countSubactionPaths);
-
XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
if (XR_FAILED(result)) {
print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.h
index bd69432dcb..5dce749351 100644
--- a/modules/openxr/openxr_api.h
+++ b/modules/openxr/openxr_api.h
@@ -84,8 +84,6 @@ private:
bool ext_vive_focus3_available = false;
bool ext_huawei_controller_available = false;
- bool is_path_supported(const String &p_path);
-
// composition layer providers
Vector<OpenXRCompositionLayerProvider *> composition_layer_providers;
@@ -302,6 +300,7 @@ public:
void parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
bool xr_result(XrResult result, const char *format, Array args = Array()) const;
+ bool is_path_supported(const String &p_path);
static bool openxr_is_enabled(bool p_check_run_in_editor = true);
static OpenXRAPI *get_singleton();
@@ -336,6 +335,11 @@ public:
void post_draw_viewport(RID p_render_target);
void end_frame();
+ // Display refresh rate
+ float get_display_refresh_rate() const;
+ void set_display_refresh_rate(float p_refresh_rate);
+ Array get_available_display_refresh_rates() const;
+
// action map
String get_default_action_map_resource_name();
diff --git a/modules/openxr/openxr_interface.cpp b/modules/openxr/openxr_interface.cpp
index 68414ae84e..bdf437b0b7 100644
--- a/modules/openxr/openxr_interface.cpp
+++ b/modules/openxr/openxr_interface.cpp
@@ -41,6 +41,13 @@ void OpenXRInterface::_bind_methods() {
ADD_SIGNAL(MethodInfo("session_focussed"));
ADD_SIGNAL(MethodInfo("session_visible"));
ADD_SIGNAL(MethodInfo("pose_recentered"));
+
+ // Display refresh rate
+ ClassDB::bind_method(D_METHOD("get_display_refresh_rate"), &OpenXRInterface::get_display_refresh_rate);
+ ClassDB::bind_method(D_METHOD("set_display_refresh_rate", "refresh_rate"), &OpenXRInterface::set_display_refresh_rate);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "display_refresh_rate"), "set_display_refresh_rate", "get_display_refresh_rate");
+
+ ClassDB::bind_method(D_METHOD("get_available_display_refresh_rates"), &OpenXRInterface::get_available_display_refresh_rates);
}
StringName OpenXRInterface::get_name() const {
@@ -147,24 +154,25 @@ void OpenXRInterface::_load_action_map() {
Ref<OpenXRAction> xr_action = actions[j];
PackedStringArray toplevel_paths = xr_action->get_toplevel_paths();
- Vector<Tracker *> trackers_new;
+ Vector<Tracker *> trackers_for_action;
for (int k = 0; k < toplevel_paths.size(); k++) {
- Tracker *tracker = find_tracker(toplevel_paths[k], true);
- if (tracker) {
- trackers_new.push_back(tracker);
+ // Only check for our tracker if our path is supported.
+ if (openxr_api->is_path_supported(toplevel_paths[k])) {
+ Tracker *tracker = find_tracker(toplevel_paths[k], true);
+ if (tracker) {
+ trackers_for_action.push_back(tracker);
+ }
}
}
- Action *action = create_action(action_set, xr_action->get_name(), xr_action->get_localized_name(), xr_action->get_action_type(), trackers);
- if (action) {
- // we link our actions back to our trackers so we know which actions to check when we're processing our trackers
- for (int t = 0; t < trackers_new.size(); t++) {
- link_action_to_tracker(trackers_new[t], action);
+ // Only add our action if we have atleast one valid toplevel path
+ if (trackers_for_action.size() > 0) {
+ Action *action = create_action(action_set, xr_action->get_name(), xr_action->get_localized_name(), xr_action->get_action_type(), trackers_for_action);
+ if (action) {
+ // add this to our map for creating our interaction profiles
+ xr_actions[xr_action] = action;
}
-
- // add this to our map for creating our interaction profiles
- xr_actions[xr_action] = action;
}
}
}
@@ -282,6 +290,13 @@ OpenXRInterface::Action *OpenXRInterface::create_action(ActionSet *p_action_set,
action->action_rid = openxr_api->action_create(p_action_set->action_set_rid, p_action_name, p_localized_name, p_action_type, tracker_rids);
p_action_set->actions.push_back(action);
+ // we link our actions back to our trackers so we know which actions to check when we're processing our trackers
+ for (int i = 0; i < p_trackers.size(); i++) {
+ if (p_trackers[i]->actions.find(action) == -1) {
+ p_trackers[i]->actions.push_back(action);
+ }
+ }
+
return action;
}
@@ -330,6 +345,8 @@ OpenXRInterface::Tracker *OpenXRInterface::find_tracker(const String &p_tracker_
return nullptr;
}
+ ERR_FAIL_COND_V(!openxr_api->is_path_supported(p_tracker_name), nullptr);
+
// Create our RID
RID tracker_rid = openxr_api->tracker_create(p_tracker_name);
ERR_FAIL_COND_V(tracker_rid.is_null(), nullptr);
@@ -389,12 +406,6 @@ void OpenXRInterface::tracker_profile_changed(RID p_tracker, RID p_interaction_p
}
}
-void OpenXRInterface::link_action_to_tracker(Tracker *p_tracker, Action *p_action) {
- if (p_tracker->actions.find(p_action) == -1) {
- p_tracker->actions.push_back(p_action);
- }
-}
-
void OpenXRInterface::handle_tracker(Tracker *p_tracker) {
ERR_FAIL_NULL(openxr_api);
ERR_FAIL_COND(p_tracker->positional_tracker.is_null());
@@ -447,9 +458,18 @@ void OpenXRInterface::handle_tracker(Tracker *p_tracker) {
void OpenXRInterface::trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) {
ERR_FAIL_NULL(openxr_api);
+
Action *action = find_action(p_action_name);
ERR_FAIL_NULL(action);
- Tracker *tracker = find_tracker(p_tracker_name);
+
+ // We need to map our tracker name to our OpenXR name for our inbuild names.
+ String tracker_name = p_tracker_name;
+ if (tracker_name == "left_hand") {
+ tracker_name = "/user/hand/left";
+ } else if (tracker_name == "right_hand") {
+ tracker_name = "/user/hand/right";
+ }
+ Tracker *tracker = find_tracker(tracker_name);
ERR_FAIL_NULL(tracker);
// TODO OpenXR does not support delay, so we may need to add support for that somehow...
@@ -571,6 +591,36 @@ bool OpenXRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) {
return false;
}
+float OpenXRInterface::get_display_refresh_rate() const {
+ if (openxr_api == nullptr) {
+ return 0.0;
+ } else if (!openxr_api->is_initialized()) {
+ return 0.0;
+ } else {
+ return openxr_api->get_display_refresh_rate();
+ }
+}
+
+void OpenXRInterface::set_display_refresh_rate(float p_refresh_rate) {
+ if (openxr_api == nullptr) {
+ return;
+ } else if (!openxr_api->is_initialized()) {
+ return;
+ } else {
+ openxr_api->set_display_refresh_rate(p_refresh_rate);
+ }
+}
+
+Array OpenXRInterface::get_available_display_refresh_rates() const {
+ if (openxr_api == nullptr) {
+ return Array();
+ } else if (!openxr_api->is_initialized()) {
+ return Array();
+ } else {
+ return openxr_api->get_available_display_refresh_rates();
+ }
+}
+
Size2 OpenXRInterface::get_render_target_size() {
if (openxr_api == nullptr) {
return Size2();
diff --git a/modules/openxr/openxr_interface.h b/modules/openxr/openxr_interface.h
index 72935b039c..454612346f 100644
--- a/modules/openxr/openxr_interface.h
+++ b/modules/openxr/openxr_interface.h
@@ -91,7 +91,6 @@ private:
void free_actions(ActionSet *p_action_set);
Tracker *find_tracker(const String &p_tracker_name, bool p_create = false);
- void link_action_to_tracker(Tracker *p_tracker, Action *p_action);
void handle_tracker(Tracker *p_tracker);
void free_trackers();
@@ -120,6 +119,10 @@ public:
virtual XRInterface::PlayAreaMode get_play_area_mode() const override;
virtual bool set_play_area_mode(XRInterface::PlayAreaMode p_mode) override;
+ float get_display_refresh_rate() const;
+ void set_display_refresh_rate(float p_refresh_rate);
+ Array get_available_display_refresh_rates() const;
+
virtual Size2 get_render_target_size() override;
virtual uint32_t get_view_count() override;
virtual Transform3D get_camera_transform() override;
diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml
index 56404f796c..2abfc93722 100644
--- a/modules/regex/doc_classes/RegEx.xml
+++ b/modules/regex/doc_classes/RegEx.xml
@@ -4,7 +4,7 @@
Class for searching text for patterns using regular expressions.
</brief_description>
<description>
- A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.
+ A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For example, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.
To begin, the RegEx object needs to be compiled with the search pattern using [method compile] before it can be used.
[codeblock]
var regex = RegEx.new()
diff --git a/modules/squish/image_decompress_squish.cpp b/modules/squish/image_decompress_squish.cpp
index 3a810e5259..2abd9a0c69 100644
--- a/modules/squish/image_decompress_squish.cpp
+++ b/modules/squish/image_decompress_squish.cpp
@@ -70,7 +70,7 @@ void image_decompress_squish(Image *p_image) {
h >>= 1;
}
- p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
+ p_image->set_data(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
if (p_image->get_format() == Image::FORMAT_DXT5_RA_AS_RG) {
p_image->convert_ra_rgba8_to_rg();
diff --git a/modules/svg/SCsub b/modules/svg/SCsub
index 93262f4f87..ae3e1bdedb 100644
--- a/modules/svg/SCsub
+++ b/modules/svg/SCsub
@@ -11,6 +11,16 @@ thirdparty_obj = []
thirdparty_dir = "#thirdparty/thorvg/"
thirdparty_sources = [
+ "src/lib/sw_engine/tvgSwFill.cpp",
+ "src/lib/sw_engine/tvgSwImage.cpp",
+ "src/lib/sw_engine/tvgSwMath.cpp",
+ "src/lib/sw_engine/tvgSwMemPool.cpp",
+ "src/lib/sw_engine/tvgSwRaster.cpp",
+ "src/lib/sw_engine/tvgSwRenderer.cpp",
+ "src/lib/sw_engine/tvgSwRle.cpp",
+ "src/lib/sw_engine/tvgSwShape.cpp",
+ "src/lib/sw_engine/tvgSwStroke.cpp",
+ "src/lib/tvgAccessor.cpp",
"src/lib/tvgBezier.cpp",
"src/lib/tvgCanvas.cpp",
"src/lib/tvgFill.cpp",
@@ -28,27 +38,18 @@ thirdparty_sources = [
"src/lib/tvgShape.cpp",
"src/lib/tvgSwCanvas.cpp",
"src/lib/tvgTaskScheduler.cpp",
+ "src/loaders/external_png/tvgPngLoader.cpp",
+ "src/loaders/jpg/tvgJpgd.cpp",
+ "src/loaders/jpg/tvgJpgLoader.cpp",
"src/loaders/raw/tvgRawLoader.cpp",
- "src/loaders/svg/tvgXmlParser.cpp",
- "src/loaders/svg/tvgSvgUtil.cpp",
- "src/loaders/svg/tvgSvgSceneBuilder.cpp",
- "src/loaders/svg/tvgSvgPath.cpp",
- "src/loaders/svg/tvgSvgLoader.cpp",
"src/loaders/svg/tvgSvgCssStyle.cpp",
+ "src/loaders/svg/tvgSvgLoader.cpp",
+ "src/loaders/svg/tvgSvgPath.cpp",
+ "src/loaders/svg/tvgSvgSceneBuilder.cpp",
+ "src/loaders/svg/tvgSvgUtil.cpp",
+ "src/loaders/svg/tvgXmlParser.cpp",
"src/loaders/tvg/tvgTvgBinInterpreter.cpp",
"src/loaders/tvg/tvgTvgLoader.cpp",
- "src/loaders/jpg/tvgJpgLoader.cpp",
- "src/loaders/jpg/tvgJpgd.cpp",
- "src/loaders/external_png/tvgPngLoader.cpp",
- "src/lib/sw_engine/tvgSwFill.cpp",
- "src/lib/sw_engine/tvgSwImage.cpp",
- "src/lib/sw_engine/tvgSwMath.cpp",
- "src/lib/sw_engine/tvgSwMemPool.cpp",
- "src/lib/sw_engine/tvgSwRaster.cpp",
- "src/lib/sw_engine/tvgSwRenderer.cpp",
- "src/lib/sw_engine/tvgSwRle.cpp",
- "src/lib/sw_engine/tvgSwShape.cpp",
- "src/lib/sw_engine/tvgSwStroke.cpp",
"src/savers/tvg/tvgTvgSaver.cpp",
]
@@ -62,14 +63,18 @@ env_thirdparty.Prepend(
CPPPATH=[
thirdparty_dir + "src/lib",
thirdparty_dir + "src/lib/sw_engine",
+ thirdparty_dir + "src/loaders/external_png",
+ thirdparty_dir + "src/loaders/jpg",
thirdparty_dir + "src/loaders/raw",
thirdparty_dir + "src/loaders/svg",
- thirdparty_dir + "src/loaders/jpg",
- thirdparty_dir + "src/loaders/png",
thirdparty_dir + "src/loaders/tvg",
thirdparty_dir + "src/savers/tvg",
]
)
+# Also requires libpng headers
+if env["builtin_libpng"]:
+ env_thirdparty.Prepend(CPPPATH=["#thirdparty/libpng"])
+
env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
env.modules_sources += thirdparty_obj
diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp
index f43f2784c7..b8c412a201 100644
--- a/modules/svg/image_loader_svg.cpp
+++ b/modules/svg/image_loader_svg.cpp
@@ -135,7 +135,7 @@ void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_strin
res = sw_canvas->clear(true);
memfree(buffer);
- p_image->create(width, height, false, Image::FORMAT_RGBA8, image);
+ p_image->set_data(width, height, false, Image::FORMAT_RGBA8, image);
}
void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp
index c9b0fa7dd5..0929d3a2b0 100644
--- a/modules/text_server_adv/text_server_adv.cpp
+++ b/modules/text_server_adv/text_server_adv.cpp
@@ -810,12 +810,12 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_
ret.y = 0x7fffffff;
ret.x = 0;
+ const int *ct_offsets_ptr = ct.offsets.ptr();
for (int j = 0; j < ct.texture_w - mw; j++) {
int max_y = 0;
-
for (int k = j; k < j + mw; k++) {
- int y = ct.offsets[k];
+ int y = ct_offsets_ptr[k];
if (y > max_y) {
max_y = y;
}
@@ -1393,7 +1393,10 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f
int error = 0;
if (!ft_library) {
error = FT_Init_FreeType(&ft_library);
- ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
+ if (error != 0) {
+ memdelete(fd);
+ ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
+ }
}
memset(&fd->stream, 0, sizeof(FT_StreamRec));
@@ -1422,6 +1425,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f
if (error) {
FT_Done_Face(fd->face);
fd->face = nullptr;
+ memdelete(fd);
ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
}
@@ -1835,6 +1839,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_f
FT_Done_MM_Var(ft_library, amaster);
}
#else
+ memdelete(fd);
ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
#endif
} else {
@@ -2494,9 +2499,7 @@ void TextServerAdvanced::_font_set_texture_image(const RID &p_font_rid, const Ve
tex.texture_h = p_image->get_height();
tex.format = p_image->get_format();
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -2515,11 +2518,7 @@ Ref<Image> TextServerAdvanced::_font_get_texture_image(const RID &p_font_rid, co
ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), Ref<Image>());
const FontTexture &tex = fd->cache[size]->textures[p_texture_index];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
-
- return img;
+ return Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
}
void TextServerAdvanced::_font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) {
@@ -2853,9 +2852,7 @@ RID TextServerAdvanced::_font_get_glyph_texture_rid(const RID &p_font_rid, const
if (gl[p_glyph | mod].texture_idx != -1) {
if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -2901,9 +2898,7 @@ Size2 TextServerAdvanced::_font_get_glyph_texture_size(const RID &p_font_rid, co
if (gl[p_glyph | mod].texture_idx != -1) {
if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -3248,9 +3243,7 @@ void TextServerAdvanced::_font_draw_glyph(const RID &p_font_rid, const RID &p_ca
if (RenderingServer::get_singleton() != nullptr) {
if (fd->cache[size]->textures[gl.texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -3340,9 +3333,7 @@ void TextServerAdvanced::_font_draw_glyph_outline(const RID &p_font_rid, const R
if (RenderingServer::get_singleton() != nullptr) {
if (fd->cache[size]->textures[gl.texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp
index 518c877baa..4a46e17868 100644
--- a/modules/text_server_fb/text_server_fb.cpp
+++ b/modules/text_server_fb/text_server_fb.cpp
@@ -233,12 +233,13 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_
ret.y = 0x7fffffff;
ret.x = 0;
+ const int *ct_offsets_ptr = ct.offsets.ptr();
for (int j = 0; j < ct.texture_w - mw; j++) {
int max_y = 0;
for (int k = j; k < j + mw; k++) {
- int y = ct.offsets[k];
+ int y = ct_offsets_ptr[k];
if (y > max_y) {
max_y = y;
}
@@ -818,7 +819,10 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f
int error = 0;
if (!ft_library) {
error = FT_Init_FreeType(&ft_library);
- ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
+ if (error != 0) {
+ memdelete(fd);
+ ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
+ }
}
memset(&fd->stream, 0, sizeof(FT_StreamRec));
@@ -847,6 +851,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f
if (error) {
FT_Done_Face(fd->face);
fd->face = nullptr;
+ memdelete(fd);
ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
}
@@ -945,6 +950,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontFallback *p_f
FT_Done_MM_Var(ft_library, amaster);
}
#else
+ memdelete(fd);
ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
#endif
}
@@ -1588,9 +1594,7 @@ void TextServerFallback::_font_set_texture_image(const RID &p_font_rid, const Ve
tex.texture_h = p_image->get_height();
tex.format = p_image->get_format();
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -1609,11 +1613,7 @@ Ref<Image> TextServerFallback::_font_get_texture_image(const RID &p_font_rid, co
ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), Ref<Image>());
const FontTexture &tex = fd->cache[size]->textures[p_texture_index];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
-
- return img;
+ return Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
}
void TextServerFallback::_font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) {
@@ -1933,9 +1933,7 @@ RID TextServerFallback::_font_get_glyph_texture_rid(const RID &p_font_rid, const
if (gl[p_glyph | mod].texture_idx != -1) {
if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -1981,9 +1979,7 @@ Size2 TextServerFallback::_font_get_glyph_texture_size(const RID &p_font_rid, co
if (gl[p_glyph | mod].texture_idx != -1) {
if (fd->cache[size]->textures[gl[p_glyph | mod].texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph | mod].texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -2310,9 +2306,7 @@ void TextServerFallback::_font_draw_glyph(const RID &p_font_rid, const RID &p_ca
if (RenderingServer::get_singleton() != nullptr) {
if (fd->cache[size]->textures[gl.texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
@@ -2402,9 +2396,7 @@ void TextServerFallback::_font_draw_glyph_outline(const RID &p_font_rid, const R
if (RenderingServer::get_singleton() != nullptr) {
if (fd->cache[size]->textures[gl.texture_idx].dirty) {
FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
- Ref<Image> img;
- img.instantiate();
- img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
+ Ref<Image> img = Image::create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
if (fd->mipmaps) {
img->generate_mipmaps();
}
diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp
index aed95294e7..a6fc650414 100644
--- a/modules/tga/image_loader_tga.cpp
+++ b/modules/tga/image_loader_tga.cpp
@@ -246,7 +246,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff
}
}
- p_image->create(width, height, false, Image::FORMAT_RGBA8, image_data);
+ p_image->initialize_data(width, height, false, Image::FORMAT_RGBA8, image_data);
return OK;
}
diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp
index 1284412cd8..69fb079970 100644
--- a/modules/theora/video_stream_theora.cpp
+++ b/modules/theora/video_stream_theora.cpp
@@ -336,9 +336,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) {
size.x = w;
size.y = h;
- Ref<Image> img;
- img.instantiate();
- img->create(w, h, false, Image::FORMAT_RGBA8);
+ Ref<Image> img = Image::create_empty(w, h, false, Image::FORMAT_RGBA8);
texture->set_image(img);
} else {
diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp
index 5c43bfc8b7..c5aa110fe6 100644
--- a/modules/tinyexr/image_loader_tinyexr.cpp
+++ b/modules/tinyexr/image_loader_tinyexr.cpp
@@ -280,7 +280,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitF
}
}
- p_image->create(exr_image.width, exr_image.height, false, format, imgdata);
+ p_image->set_data(exr_image.width, exr_image.height, false, format, imgdata);
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml
index 4888dca822..d4054948f6 100644
--- a/modules/upnp/doc_classes/UPNP.xml
+++ b/modules/upnp/doc_classes/UPNP.xml
@@ -41,7 +41,7 @@
func _ready():
thread = Thread.new()
- thread.start(self, "_upnp_setup", SERVER_PORT)
+ thread.start(_upnp_setup.bind(SERVER_PORT))
func _exit_tree():
# Wait for thread finish here to handle game exit while the thread is running.
diff --git a/modules/webp/webp_common.cpp b/modules/webp/webp_common.cpp
index 8657a98853..049c1c3a32 100644
--- a/modules/webp/webp_common.cpp
+++ b/modules/webp/webp_common.cpp
@@ -183,7 +183,7 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
ERR_FAIL_COND_V_MSG(errdec, ERR_FILE_CORRUPT, "Failed decoding WebP image.");
- p_image->create(features.width, features.height, false, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
+ p_image->set_data(features.width, features.height, false, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
return OK;
}
diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml
index 927888fe21..0b42c6ed35 100644
--- a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml
+++ b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml
@@ -6,7 +6,7 @@
<description>
This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.multiplayer_peer].
You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections.
- [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [MultiplayerPeer].
+ [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless the peer is created using [method create_client]. Beside that data transfer works like in a [MultiplayerPeer].
[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>
<tutorials>
@@ -28,6 +28,31 @@
Close all the add peer connections and channels, freeing all resources.
</description>
</method>
+ <method name="create_client">
+ <return type="int" enum="Error" />
+ <param index="0" name="peer_id" type="int" />
+ <param index="1" name="channels_config" type="Array" default="[]" />
+ <description>
+ Initialize the multiplayer peer as a client with the given [code]peer_id[/code] (must be between 2 and 2147483647). In this mode, you should only call [method add_peer] once and with [code]peer_id[/code] of [code]1[/code]. This mode enables [method MultiplayerPeer.is_server_relay_supported], allowing the upper [MultiplayerAPI] layer to perform peer exchange and packet relaying.
+ You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel).
+ </description>
+ </method>
+ <method name="create_mesh">
+ <return type="int" enum="Error" />
+ <param index="0" name="peer_id" type="int" />
+ <param index="1" name="channels_config" type="Array" default="[]" />
+ <description>
+ Initialize the multiplayer peer as a mesh (i.e. all peers connect to each other) with the given [code]peer_id[/code] (must be between 1 and 2147483647).
+ </description>
+ </method>
+ <method name="create_server">
+ <return type="int" enum="Error" />
+ <param index="0" name="channels_config" type="Array" default="[]" />
+ <description>
+ Initialize the multiplayer peer as a server (with unique ID of [code]1[/code]). This mode enables [method MultiplayerPeer.is_server_relay_supported], allowing the upper [MultiplayerAPI] layer to perform peer exchange and packet relaying.
+ You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel).
+ </description>
+ </method>
<method name="get_peer">
<return type="Dictionary" />
<param index="0" name="peer_id" type="int" />
@@ -48,18 +73,6 @@
Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though).
</description>
</method>
- <method name="initialize">
- <return type="int" enum="Error" />
- <param index="0" name="peer_id" type="int" />
- <param index="1" name="server_compatibility" type="bool" default="false" />
- <param index="2" name="channels_config" type="Array" default="[]" />
- <description>
- Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647).
- If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant MultiplayerPeer.CONNECTION_CONNECTED] and [signal MultiplayerPeer.connection_succeeded] will not be emitted.
- If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal MultiplayerPeer.peer_connected] signals until a peer with id [constant MultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal MultiplayerPeer.connection_succeeded]. After that the signal [signal MultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal MultiplayerPeer.server_disconnected] will be emitted and state will become [constant MultiplayerPeer.CONNECTION_CONNECTED].
- You can optionally specify a [code]channels_config[/code] array of [enum MultiplayerPeer.TransferMode] which will be used to create extra channels (WebRTC only supports one transfer mode per channel).
- </description>
- </method>
<method name="remove_peer">
<return type="void" />
<param index="0" name="peer_id" type="int" />
diff --git a/modules/webrtc/webrtc_multiplayer_peer.cpp b/modules/webrtc/webrtc_multiplayer_peer.cpp
index e03b6b2473..5ea81d5a1b 100644
--- a/modules/webrtc/webrtc_multiplayer_peer.cpp
+++ b/modules/webrtc/webrtc_multiplayer_peer.cpp
@@ -34,7 +34,9 @@
#include "core/os/os.h"
void WebRTCMultiplayerPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility", "channels_config"), &WebRTCMultiplayerPeer::initialize, DEFVAL(false), DEFVAL(Array()));
+ ClassDB::bind_method(D_METHOD("create_server", "channels_config"), &WebRTCMultiplayerPeer::create_server, DEFVAL(Array()));
+ ClassDB::bind_method(D_METHOD("create_client", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_client, DEFVAL(Array()));
+ ClassDB::bind_method(D_METHOD("create_mesh", "peer_id", "channels_config"), &WebRTCMultiplayerPeer::create_mesh, DEFVAL(Array()));
ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1));
ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer);
ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer);
@@ -52,6 +54,15 @@ int WebRTCMultiplayerPeer::get_packet_peer() const {
return next_packet_peer;
}
+int WebRTCMultiplayerPeer::get_packet_channel() const {
+ return next_packet_channel < CH_RESERVED_MAX ? 0 : next_packet_channel - CH_RESERVED_MAX + 1;
+}
+
+MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_packet_mode() const {
+ ERR_FAIL_INDEX_V(next_packet_channel, channels_modes.size(), TRANSFER_MODE_RELIABLE);
+ return channels_modes[next_packet_channel];
+}
+
bool WebRTCMultiplayerPeer::is_server() const {
return unique_id == TARGET_PEER_SERVER;
}
@@ -113,24 +124,14 @@ void WebRTCMultiplayerPeer::poll() {
// Signal newly connected peers
for (int &E : add) {
// Already connected to server: simply notify new peer.
- // NOTE: Mesh is always connected.
- if (connection_status == CONNECTION_CONNECTED) {
- emit_signal(SNAME("peer_connected"), E);
- }
-
- // Server emulation mode suppresses peer_conencted until server connects.
- if (server_compat && E == TARGET_PEER_SERVER) {
+ if (network_mode == MODE_CLIENT) {
+ ERR_CONTINUE(E != TARGET_PEER_SERVER); // Bug.
// Server connected.
connection_status = CONNECTION_CONNECTED;
emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER);
emit_signal(SNAME("connection_succeeded"));
- // Notify of all previously connected peers
- for (const KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
- if (F.key != 1 && F.value->connected) {
- emit_signal(SNAME("peer_connected"), F.key);
- }
- }
- break; // Because we already notified of all newly added peers.
+ } else {
+ emit_signal(SNAME("peer_connected"), E);
}
}
// Fetch next packet
@@ -150,11 +151,14 @@ void WebRTCMultiplayerPeer::_find_next_peer() {
++E;
continue;
}
+ int idx = 0;
for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
if (F->get_available_packet_count()) {
+ next_packet_channel = idx;
next_packet_peer = E->key;
return;
}
+ idx++;
}
++E;
}
@@ -165,11 +169,14 @@ void WebRTCMultiplayerPeer::_find_next_peer() {
++E;
continue;
}
+ int idx = 0;
for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
if (F->get_available_packet_count()) {
+ next_packet_channel = idx;
next_packet_peer = E->key;
return;
}
+ idx++;
}
if (E->key == (int)next_packet_peer) {
break;
@@ -177,6 +184,7 @@ void WebRTCMultiplayerPeer::_find_next_peer() {
++E;
}
// No packet found
+ next_packet_channel = 0;
next_packet_peer = 0;
}
@@ -184,11 +192,28 @@ MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status()
return connection_status;
}
-Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Array p_channels_config) {
+Error WebRTCMultiplayerPeer::create_server(Array p_channels_config) {
+ return _initialize(1, MODE_SERVER, p_channels_config);
+}
+
+Error WebRTCMultiplayerPeer::create_client(int p_self_id, Array p_channels_config) {
+ ERR_FAIL_COND_V_MSG(p_self_id == 1, ERR_INVALID_PARAMETER, "Clients cannot have ID 1.");
+ return _initialize(p_self_id, MODE_CLIENT, p_channels_config);
+}
+
+Error WebRTCMultiplayerPeer::create_mesh(int p_self_id, Array p_channels_config) {
+ return _initialize(p_self_id, MODE_MESH, p_channels_config);
+}
+
+Error WebRTCMultiplayerPeer::_initialize(int p_self_id, NetworkMode p_mode, Array p_channels_config) {
ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
channels_config.clear();
+ channels_modes.clear();
+ channels_modes.push_back(TRANSFER_MODE_RELIABLE);
+ channels_modes.push_back(TRANSFER_MODE_UNRELIABLE_ORDERED);
+ channels_modes.push_back(TRANSFER_MODE_UNRELIABLE);
for (int i = 0; i < p_channels_config.size(); i++) {
- ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'");
+ ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'");
int mode = p_channels_config[i].operator int();
// Initialize data channel configurations.
Dictionary cfg;
@@ -207,16 +232,17 @@ Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Arr
case TRANSFER_MODE_RELIABLE:
break;
default:
- ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'. Got: %d", mode));
+ ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.TransferMode'. Got: %d", mode));
}
channels_config.push_back(cfg);
+ channels_modes.push_back((TransferMode)mode);
}
unique_id = p_self_id;
- server_compat = p_server_compat;
+ network_mode = p_mode;
// Mesh and server are always connected
- if (!server_compat || p_self_id == 1) {
+ if (p_mode != MODE_CLIENT) {
connection_status = CONNECTION_CONNECTED;
} else {
connection_status = CONNECTION_CONNECTING;
@@ -224,6 +250,10 @@ Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Arr
return OK;
}
+bool WebRTCMultiplayerPeer::is_server_relay_supported() const {
+ return network_mode == MODE_SERVER || network_mode == MODE_CLIENT;
+}
+
int WebRTCMultiplayerPeer::get_unique_id() const {
ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
return unique_id;
@@ -261,7 +291,10 @@ Dictionary WebRTCMultiplayerPeer::get_peers() {
}
Error WebRTCMultiplayerPeer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
- ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(network_mode == MODE_NONE, ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(network_mode == MODE_CLIENT && p_peer_id != 1, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(network_mode == MODE_SERVER && p_peer_id == 1, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_peer_id < 1 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED);
// Peer must be valid, and in new state (to create data channels)
@@ -308,8 +341,12 @@ void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) {
if (peer->connected) {
peer->connected = false;
emit_signal(SNAME("peer_disconnected"), p_peer_id);
- if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
- emit_signal(SNAME("server_disconnected"));
+ if (network_mode == MODE_CLIENT && p_peer_id == TARGET_PEER_SERVER) {
+ if (connection_status == CONNECTION_CONNECTING) {
+ emit_signal(SNAME("connection_failed"));
+ } else {
+ emit_signal(SNAME("server_disconnected"));
+ }
connection_status = CONNECTION_DISCONNECTED;
}
}
@@ -403,7 +440,9 @@ void WebRTCMultiplayerPeer::close() {
channels_config.clear();
unique_id = 0;
next_packet_peer = 0;
+ next_packet_channel = 0;
target_peer = 0;
+ network_mode = MODE_NONE;
connection_status = CONNECTION_DISCONNECTED;
}
diff --git a/modules/webrtc/webrtc_multiplayer_peer.h b/modules/webrtc/webrtc_multiplayer_peer.h
index ea7c60036b..3f608200fd 100644
--- a/modules/webrtc/webrtc_multiplayer_peer.h
+++ b/modules/webrtc/webrtc_multiplayer_peer.h
@@ -48,6 +48,13 @@ private:
CH_RESERVED_MAX = 3
};
+ enum NetworkMode {
+ MODE_NONE,
+ MODE_SERVER,
+ MODE_CLIENT,
+ MODE_MESH,
+ };
+
class ConnectedPeer : public RefCounted {
public:
Ref<WebRTCPeerConnection> connection;
@@ -67,19 +74,25 @@ private:
int client_count = 0;
ConnectionStatus connection_status = CONNECTION_DISCONNECTED;
int next_packet_peer = 0;
- bool server_compat = false;
+ int next_packet_channel = 0;
+ NetworkMode network_mode = MODE_NONE;
HashMap<int, Ref<ConnectedPeer>> peer_map;
+ List<TransferMode> channels_modes;
List<Dictionary> channels_config;
void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict);
void _find_next_peer();
+ Ref<ConnectedPeer> _get_next_peer();
+ Error _initialize(int p_self_id, NetworkMode p_mode, Array p_channels_config = Array());
public:
WebRTCMultiplayerPeer() {}
~WebRTCMultiplayerPeer();
- Error initialize(int p_self_id, bool p_server_compat = false, Array p_channels_config = Array());
+ Error create_server(Array p_channels_config = Array());
+ Error create_client(int p_self_id, Array p_channels_config = Array());
+ Error create_mesh(int p_self_id, Array p_channels_config = Array());
Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1);
void remove_peer(int p_peer_id);
bool has_peer(int p_peer_id);
@@ -98,8 +111,11 @@ public:
int get_unique_id() const override;
int get_packet_peer() const override;
+ int get_packet_channel() const override;
+ TransferMode get_packet_mode() const override;
bool is_server() const override;
+ bool is_server_relay_supported() const override;
void poll() override;
diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml
deleted file mode 100644
index 1978d2e7c6..0000000000
--- a/modules/websocket/doc_classes/WebSocketClient.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
- <brief_description>
- A WebSocket client implementation.
- </brief_description>
- <description>
- This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server.
- This client can be optionally used as a multiplayer peer for the [MultiplayerAPI].
- After starting the client ([method connect_to_url]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]).
- You will receive appropriate signals when connecting, disconnecting, or when new data is available.
- [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>
- <tutorials>
- </tutorials>
- <methods>
- <method name="connect_to_url">
- <return type="int" enum="Error" />
- <param index="0" name="url" type="String" />
- <param index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" />
- <param index="2" name="gd_mp_api" type="bool" default="false" />
- <param index="3" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" />
- <description>
- Connects to the given URL requesting one of the given [code]protocols[/code] as sub-protocol. If the list empty (default), no sub-protocol will be requested.
- If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a multiplayer peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted.
- If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.) on the [WebSocketPeer] returned via [code]get_peer(1)[/code] and not on this object directly (e.g. [code]get_peer(1).put_packet(data)[/code]).
- You can optionally pass a list of [code]custom_headers[/code] to be added to the handshake HTTP request.
- [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the TLS certificate.
- [b]Note:[/b] Specifying [code]custom_headers[/code] is not supported in Web exports due to browsers' restrictions.
- </description>
- </method>
- <method name="disconnect_from_host">
- <return type="void" />
- <param index="0" name="code" type="int" default="1000" />
- <param index="1" name="reason" type="String" default="&quot;&quot;" />
- <description>
- Disconnects this client from the connected host. See [method WebSocketPeer.close] for more information.
- </description>
- </method>
- <method name="get_connected_host" qualifiers="const">
- <return type="String" />
- <description>
- Returns the IP address of the currently connected host.
- </description>
- </method>
- <method name="get_connected_port" qualifiers="const">
- <return type="int" />
- <description>
- Returns the IP port of the currently connected host.
- </description>
- </method>
- </methods>
- <members>
- <member name="trusted_tls_certificate" type="X509Certificate" setter="set_trusted_tls_certificate" getter="get_trusted_tls_certificate">
- If specified, this [X509Certificate] will be the only one accepted when connecting to an TLS host. Any other certificate provided by the server will be regarded as invalid.
- [b]Note:[/b] Specifying a custom [code]trusted_tls_certificate[/code] is not supported in Web exports due to browsers' restrictions.
- </member>
- <member name="verify_tls" type="bool" setter="set_verify_tls_enabled" getter="is_verify_tls_enabled">
- If [code]true[/code], TLS certificate verification is enabled.
- [b]Note:[/b] You must specify the certificates to be used in the Project Settings for it to work when exported.
- </member>
- </members>
- <signals>
- <signal name="connection_closed">
- <param index="0" name="was_clean_close" type="bool" />
- <description>
- Emitted when the connection to the server is closed. [code]was_clean_close[/code] will be [code]true[/code] if the connection was shutdown cleanly.
- </description>
- </signal>
- <signal name="connection_error">
- <description>
- Emitted when the connection to the server fails.
- </description>
- </signal>
- <signal name="connection_established">
- <param index="0" name="protocol" type="String" />
- <description>
- Emitted when a connection with the server is established, [code]protocol[/code] will contain the sub-protocol agreed with the server.
- </description>
- </signal>
- <signal name="data_received">
- <description>
- Emitted when a WebSocket message is received.
- [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer.
- </description>
- </signal>
- <signal name="server_close_request">
- <param index="0" name="code" type="int" />
- <param index="1" name="reason" type="String" />
- <description>
- Emitted when the server requests a clean close. You should keep polling until you get a [signal connection_closed] signal to achieve the clean close. See [method WebSocketPeer.close] for more details.
- </description>
- </signal>
- </signals>
-</class>
diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
index 4cc4d515e7..c4481b046b 100644
--- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
+++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
@@ -10,6 +10,42 @@
<tutorials>
</tutorials>
<methods>
+ <method name="close">
+ <return type="void" />
+ <description>
+ Closes this [MultiplayerPeer], resetting the state to [constant MultiplayerPeer.CONNECTION_CONNECTED].
+ [b]Note:[/b] To make sure remote peers receive a clean close prefer disconnecting clients via [method disconnect_peer].
+ </description>
+ </method>
+ <method name="create_client">
+ <return type="int" enum="Error" />
+ <param index="0" name="url" type="String" />
+ <param index="1" name="verify_tls" type="bool" default="true" />
+ <param index="2" name="tls_certificate" type="X509Certificate" default="null" />
+ <description>
+ Starts a new multiplayer client connecting to the given [param url]. If [param verify_tls] is [code]false[/code] certificate validation will be disabled. If specified, the [param tls_certificate] will be used to verify the TLS host.
+ [b]Note[/b]: It is recommended to specify the scheme part of the URL, i.e. the [param url] should start with either [code]ws://[/code] or [code]wss://[/code].
+ </description>
+ </method>
+ <method name="create_server">
+ <return type="int" enum="Error" />
+ <param index="0" name="port" type="int" />
+ <param index="1" name="bind_address" type="String" default="&quot;*&quot;" />
+ <param index="2" name="tls_key" type="CryptoKey" default="null" />
+ <param index="3" name="tls_certificate" type="X509Certificate" default="null" />
+ <description>
+ Starts a new multiplayer server listening on the given [param port]. You can optionally specify a [param bind_address], and provide a [param tls_key] and [param tls_certificate] to use TLS.
+ </description>
+ </method>
+ <method name="disconnect_peer">
+ <return type="void" />
+ <param index="0" name="id" type="int" />
+ <param index="1" name="code" type="int" default="1000" />
+ <param index="2" name="reason" type="String" default="&quot;&quot;" />
+ <description>
+ Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more information.
+ </description>
+ </method>
<method name="get_peer" qualifiers="const">
<return type="WebSocketPeer" />
<param index="0" name="peer_id" type="int" />
@@ -17,27 +53,39 @@
Returns the [WebSocketPeer] associated to the given [code]peer_id[/code].
</description>
</method>
- <method name="set_buffers">
- <return type="int" enum="Error" />
- <param index="0" name="input_buffer_size_kb" type="int" />
- <param index="1" name="input_max_packets" type="int" />
- <param index="2" name="output_buffer_size_kb" type="int" />
- <param index="3" name="output_max_packets" type="int" />
+ <method name="get_peer_address" qualifiers="const">
+ <return type="String" />
+ <param index="0" name="id" type="int" />
<description>
- Configures the buffer sizes for this WebSocket peer. Default values can be specified in the Project Settings under [code]network/limits[/code]. For server, values are meant per connected peer.
- The first two parameters define the size and queued packets limits of the input buffer, the last two of the output buffer.
- Buffer sizes are expressed in KiB, so [code]4 = 2^12 = 4096 bytes[/code]. All parameters will be rounded up to the nearest power of two.
- [b]Note:[/b] Web exports only use the input buffer since the output one is managed by browsers.
+ Returns the IP address of the given peer.
</description>
</method>
- </methods>
- <signals>
- <signal name="peer_packet">
- <param index="0" name="peer_source" type="int" />
+ <method name="get_peer_port" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="id" type="int" />
<description>
- Emitted when a packet is received from a peer.
- [b]Note:[/b] This signal is only emitted when the client or server is configured to use Godot multiplayer API.
+ Returns the remote port of the given peer.
</description>
- </signal>
- </signals>
+ </method>
+ </methods>
+ <members>
+ <member name="handshake_headers" type="PackedStringArray" setter="set_handshake_headers" getter="get_handshake_headers" default="PackedStringArray()">
+ The extra headers to use during handshake. See [member WebSocketPeer.handshake_headers] for more details.
+ </member>
+ <member name="handshake_timeout" type="float" setter="set_handshake_timeout" getter="get_handshake_timeout" default="3.0">
+ The maximum time each peer can stay in a connecting state before being dropped.
+ </member>
+ <member name="inbound_buffer_size" type="int" setter="set_inbound_buffer_size" getter="get_inbound_buffer_size" default="65535">
+ The inbound buffer size for connected peers. See [member WebSocketPeer.inbound_buffer_size] for more details.
+ </member>
+ <member name="max_queued_packets" type="int" setter="set_max_queued_packets" getter="get_max_queued_packets" default="2048">
+ The maximum number of queued packets for connected peers. See [member WebSocketPeer.max_queued_packets] for more details.
+ </member>
+ <member name="outbound_buffer_size" type="int" setter="set_outbound_buffer_size" getter="get_outbound_buffer_size" default="65535">
+ The outbound buffer size for connected peers. See [member WebSocketPeer.outbound_buffer_size] for more details.
+ </member>
+ <member name="supported_protocols" type="PackedStringArray" setter="set_supported_protocols" getter="get_supported_protocols" default="PackedStringArray()">
+ The supported WebSocket sub-protocols. See [member WebSocketPeer.supported_protocols] for more details.
+ </member>
+ </members>
</class>
diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml
index 627b9c607c..fe0aae412e 100644
--- a/modules/websocket/doc_classes/WebSocketPeer.xml
+++ b/modules/websocket/doc_classes/WebSocketPeer.xml
@@ -1,25 +1,82 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="WebSocketPeer" inherits="PacketPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
<brief_description>
- A class representing a specific WebSocket connection.
+ A WebSocket connection.
</brief_description>
<description>
- This class represents a specific WebSocket connection, allowing you to do lower level operations with it.
- You can choose to write to the socket in binary or text mode, and you can recognize the mode used for writing by the other peer.
+ This class represents WebSocket connection, and can be used as a WebSocket client (RFC 6455-compliant) or as a remote peer of a WebSocket server.
+ You can send WebSocket binary frames using [method PacketPeer.put_packet], and WebSocket text frames using [method send] (prefer text frames when interacting with text-based API). You can check the frame type of the last packet via [method was_string_packet].
+ To start a WebSocket client, first call [method connect_to_url], then regularly call [method poll] (e.g. during [Node] process). You can query the socket state via [method get_ready_state], get the number of pending packets using [method PacketPeer.get_available_packet_count], and retrieve them via [method PacketPeer.get_packet].
+ [codeblocks]
+ [gdscript]
+ extends Node
+
+ var socket = WebSocketPeer.new()
+
+ func _ready():
+ socket.connect_to_url("wss://example.com")
+
+ func _process(delta):
+ socket.poll()
+ var state = socket.get_ready_state()
+ if state == WebSocketPeer.STATE_OPEN:
+ while socket.get_available_packet_count():
+ print("Packet: ", socket.get_packet())
+ elif state == WebSocketPeer.STATE_CLOSING:
+ # Keep polling to achieve proper close.
+ pass
+ elif state == WebSocketPeer.STATE_CLOSED:
+ var code = socket.get_close_code()
+ var reason = socket.get_close_reason()
+ print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
+ set_process(false) # Stop processing.
+ [/gdscript]
+ [/codeblocks]
+ To use the peer as part of a WebSocket server refer to [method accept_stream] and the online tutorial.
</description>
<tutorials>
</tutorials>
<methods>
+ <method name="accept_stream">
+ <return type="int" enum="Error" />
+ <param index="0" name="stream" type="StreamPeer" />
+ <description>
+ Accepts a peer connection performing the HTTP handshake as a WebSocket server. The [param stream] must be a valid TCP stream retrieved via [method TCPServer.take_connection], or a TLS stream accepted via [method StreamPeerTLS.accept_stream].
+ [b]Note:[/b] Not supported in Web exports due to browsers' restrictions.
+ </description>
+ </method>
<method name="close">
<return type="void" />
<param index="0" name="code" type="int" default="1000" />
<param index="1" name="reason" type="String" default="&quot;&quot;" />
<description>
- Closes this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes).
- [b]Note:[/b] To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received.
+ Closes this WebSocket connection. [param code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [param reason] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). If [param code] is negative, the connection will be closed immediately without notifying the remote peer.
+ [b]Note:[/b] To achieve a clean close, you will need to keep polling until [constant STATE_CLOSED] is reached.
[b]Note:[/b] The Web export might not support all status codes. Please refer to browser-specific documentation for more details.
</description>
</method>
+ <method name="connect_to_url">
+ <return type="int" enum="Error" />
+ <param index="0" name="url" type="String" />
+ <param index="1" name="verify_tls" type="bool" default="true" />
+ <param index="2" name="trusted_tls_certificate" type="X509Certificate" default="null" />
+ <description>
+ Connects to the given URL. If [param verify_tls] is [code]false[/code] certificate validation will be disabled. If specified, the [param trusted_tls_certificate] will be the only one accepted when connecting to a TLS host.
+ [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the TLS certificate.
+ </description>
+ </method>
+ <method name="get_close_code" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns the received WebSocket close frame status code, or [code]-1[/code] when the connection was not cleanly closed. Only call this method when [method get_ready_state] returns [constant STATE_CLOSED].
+ </description>
+ </method>
+ <method name="get_close_reason" qualifiers="const">
+ <return type="String" />
+ <description>
+ Returns the received WebSocket close frame status reason string. Only call this method when [method get_ready_state] returns [constant STATE_CLOSED].
+ </description>
+ </method>
<method name="get_connected_host" qualifiers="const">
<return type="String" />
<description>
@@ -40,31 +97,51 @@
Returns the current amount of data in the outbound websocket buffer. [b]Note:[/b] Web exports use WebSocket.bufferedAmount, while other platforms use an internal buffer.
</description>
</method>
- <method name="get_write_mode" qualifiers="const">
- <return type="int" enum="WebSocketPeer.WriteMode" />
+ <method name="get_ready_state" qualifiers="const">
+ <return type="int" enum="WebSocketPeer.State" />
<description>
- Gets the current selected write mode. See [enum WriteMode].
+ Returns the ready state of the connection. See [enum State].
</description>
</method>
- <method name="is_connected_to_host" qualifiers="const">
- <return type="bool" />
+ <method name="get_requested_url" qualifiers="const">
+ <return type="String" />
<description>
- Returns [code]true[/code] if this peer is currently connected.
+ Returns the URL requested by this peer. The URL is derived from the [code]url[/code] passed to [method connect_to_url] or from the HTTP headers when acting as server (i.e. when using [method accept_stream]).
</description>
</method>
- <method name="set_no_delay">
+ <method name="get_selected_protocol" qualifiers="const">
+ <return type="String" />
+ <description>
+ Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet.
+ </description>
+ </method>
+ <method name="poll">
<return type="void" />
- <param index="0" name="enabled" type="bool" />
<description>
- Disable Nagle's algorithm on the underling TCP socket (default). See [method StreamPeerTCP.set_no_delay] for more information.
- [b]Note:[/b] Not available in the Web export.
+ Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state.
</description>
</method>
- <method name="set_write_mode">
+ <method name="send">
+ <return type="int" enum="Error" />
+ <param index="0" name="message" type="PackedByteArray" />
+ <param index="1" name="write_mode" type="int" enum="WebSocketPeer.WriteMode" default="1" />
+ <description>
+ Sends the given [param message] using the desired [param write_mode]. When sending a [String], prefer using [method send_text].
+ </description>
+ </method>
+ <method name="send_text">
+ <return type="int" enum="Error" />
+ <param index="0" name="message" type="String" />
+ <description>
+ Sends the given [param message] using WebSocket text mode. Perfer this method over [method PacketPeer.put_packet] when interacting with third-party text-based API (e.g. when using [JSON] formatted messages).
+ </description>
+ </method>
+ <method name="set_no_delay">
<return type="void" />
- <param index="0" name="mode" type="int" enum="WebSocketPeer.WriteMode" />
+ <param index="0" name="enabled" type="bool" />
<description>
- Sets the socket to use the given [enum WriteMode].
+ Disable Nagle's algorithm on the underling TCP socket (default). See [method StreamPeerTCP.set_no_delay] for more information.
+ [b]Note:[/b] Not available in the Web export.
</description>
</method>
<method name="was_string_packet" qualifiers="const">
@@ -74,6 +151,24 @@
</description>
</method>
</methods>
+ <members>
+ <member name="handshake_headers" type="PackedStringArray" setter="set_handshake_headers" getter="get_handshake_headers" default="PackedStringArray()">
+ The extra HTTP headers to be sent during the WebSocket handshake.
+ [b]Note:[/b] Not supported in Web exports due to browsers' restrictions.
+ </member>
+ <member name="inbound_buffer_size" type="int" setter="set_inbound_buffer_size" getter="get_inbound_buffer_size" default="65535">
+ The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the inbound packets).
+ </member>
+ <member name="max_queued_packets" type="int" setter="set_max_queued_packets" getter="get_max_queued_packets" default="2048">
+ The maximum amount of packets that will be allowed in the queues (both inbound and outbound).
+ </member>
+ <member name="outbound_buffer_size" type="int" setter="set_outbound_buffer_size" getter="get_outbound_buffer_size" default="65535">
+ The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the outbound packets).
+ </member>
+ <member name="supported_protocols" type="PackedStringArray" setter="set_supported_protocols" getter="get_supported_protocols" default="PackedStringArray()">
+ The WebSocket sub-protocols allowed during the WebSocket handshake.
+ </member>
+ </members>
<constants>
<constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode">
Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
@@ -81,5 +176,17 @@
<constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode">
Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
</constant>
+ <constant name="STATE_CONNECTING" value="0" enum="State">
+ Socket has been created. The connection is not yet open.
+ </constant>
+ <constant name="STATE_OPEN" value="1" enum="State">
+ The connection is open and ready to communicate.
+ </constant>
+ <constant name="STATE_CLOSING" value="2" enum="State">
+ The connection is in the process of closing. This means a close request has been sent to the remote peer but confirmation has not been received.
+ </constant>
+ <constant name="STATE_CLOSED" value="3" enum="State">
+ The connection is closed or couldn't be opened.
+ </constant>
</constants>
</class>
diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml
deleted file mode 100644
index 07a55b73f1..0000000000
--- a/modules/websocket/doc_classes/WebSocketServer.xml
+++ /dev/null
@@ -1,127 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
- <brief_description>
- A WebSocket server implementation.
- </brief_description>
- <description>
- This class implements a WebSocket server that can also support the high-level multiplayer API.
- After starting the server ([method listen]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal.
- [b]Note:[/b] Not available in Web exports.
- [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>
- <tutorials>
- </tutorials>
- <methods>
- <method name="disconnect_peer">
- <return type="void" />
- <param index="0" name="id" type="int" />
- <param index="1" name="code" type="int" default="1000" />
- <param index="2" name="reason" type="String" default="&quot;&quot;" />
- <description>
- Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more information.
- </description>
- </method>
- <method name="get_peer_address" qualifiers="const">
- <return type="String" />
- <param index="0" name="id" type="int" />
- <description>
- Returns the IP address of the given peer.
- </description>
- </method>
- <method name="get_peer_port" qualifiers="const">
- <return type="int" />
- <param index="0" name="id" type="int" />
- <description>
- Returns the remote port of the given peer.
- </description>
- </method>
- <method name="has_peer" qualifiers="const">
- <return type="bool" />
- <param index="0" name="id" type="int" />
- <description>
- Returns [code]true[/code] if a peer with the given ID is connected.
- </description>
- </method>
- <method name="is_listening" qualifiers="const">
- <return type="bool" />
- <description>
- Returns [code]true[/code] if the server is actively listening on a port.
- </description>
- </method>
- <method name="listen">
- <return type="int" enum="Error" />
- <param index="0" name="port" type="int" />
- <param index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" />
- <param index="2" name="gd_mp_api" type="bool" default="false" />
- <description>
- Starts listening on the given port.
- You can specify the desired subprotocols via the "protocols" array. If the list empty (default), no sub-protocol will be requested.
- If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a multiplayer peer for the [MultiplayerAPI], connections from non-Godot clients will not work, and [signal data_received] will not be emitted.
- If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(id)[/code] to communicate with the peer with given [code]id[/code] (e.g. [code]get_peer(id).get_available_packet_count[/code]).
- </description>
- </method>
- <method name="set_extra_headers">
- <return type="void" />
- <param index="0" name="headers" type="PackedStringArray" default="PackedStringArray()" />
- <description>
- Sets additional headers to be sent to clients during the HTTP handshake.
- </description>
- </method>
- <method name="stop">
- <return type="void" />
- <description>
- Stops the server and clear its state.
- </description>
- </method>
- </methods>
- <members>
- <member name="bind_ip" type="String" setter="set_bind_ip" getter="get_bind_ip" default="&quot;*&quot;">
- When not set to [code]*[/code] will restrict incoming connections to the specified IP address. Setting [code]bind_ip[/code] to [code]127.0.0.1[/code] will cause the server to listen only to the local host.
- </member>
- <member name="ca_chain" type="X509Certificate" setter="set_ca_chain" getter="get_ca_chain">
- When using TLS (see [member private_key] and [member tls_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the TLS handshake.
- </member>
- <member name="handshake_timeout" type="float" setter="set_handshake_timeout" getter="get_handshake_timeout" default="3.0">
- The time in seconds before a pending client (i.e. a client that has not yet finished the HTTP handshake) is considered stale and forcefully disconnected.
- </member>
- <member name="private_key" type="CryptoKey" setter="set_private_key" getter="get_private_key">
- When set to a valid [CryptoKey] (along with [member tls_certificate]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol).
- </member>
- <member name="tls_certificate" type="X509Certificate" setter="set_tls_certificate" getter="get_tls_certificate">
- When set to a valid [X509Certificate] (along with [member private_key]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol).
- </member>
- </members>
- <signals>
- <signal name="client_close_request">
- <param index="0" name="id" type="int" />
- <param index="1" name="code" type="int" />
- <param index="2" name="reason" type="String" />
- <description>
- Emitted when a client requests a clean close. You should keep polling until you get a [signal client_disconnected] signal with the same [code]id[/code] to achieve the clean close. See [method WebSocketPeer.close] for more details.
- </description>
- </signal>
- <signal name="client_connected">
- <param index="0" name="id" type="int" />
- <param index="1" name="protocol" type="String" />
- <param index="2" name="resource_name" type="String" />
- <description>
- Emitted when a new client connects. "protocol" will be the sub-protocol agreed with the client, and "resource_name" will be the resource name of the URI the peer used.
- "resource_name" is a path (at the very least a single forward slash) and potentially a query string.
- </description>
- </signal>
- <signal name="client_disconnected">
- <param index="0" name="id" type="int" />
- <param index="1" name="was_clean_close" type="bool" />
- <description>
- Emitted when a client disconnects. [code]was_clean_close[/code] will be [code]true[/code] if the connection was shutdown cleanly.
- </description>
- </signal>
- <signal name="data_received">
- <param index="0" name="id" type="int" />
- <description>
- Emitted when a new message is received.
- [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer.
- </description>
- </signal>
- </signals>
-</class>
diff --git a/modules/websocket/editor/editor_debugger_server_websocket.cpp b/modules/websocket/editor/editor_debugger_server_websocket.cpp
index 0443147d98..48bfbaa14e 100644
--- a/modules/websocket/editor/editor_debugger_server_websocket.cpp
+++ b/modules/websocket/editor/editor_debugger_server_websocket.cpp
@@ -38,18 +38,31 @@
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
-void EditorDebuggerServerWebSocket::_peer_connected(int p_id, String _protocol) {
- pending_peers.push_back(p_id);
-}
+void EditorDebuggerServerWebSocket::poll() {
+ if (pending_peer.is_null() && tcp_server->is_connection_available()) {
+ Ref<WebSocketPeer> peer = Ref<WebSocketPeer>(WebSocketPeer::create());
+ ERR_FAIL_COND(peer.is_null()); // Bug.
-void EditorDebuggerServerWebSocket::_peer_disconnected(int p_id, bool p_was_clean) {
- if (pending_peers.find(p_id)) {
- pending_peers.erase(p_id);
- }
-}
+ Vector<String> ws_protocols;
+ ws_protocols.push_back("binary"); // Compatibility for emscripten TCP-to-WebSocket.
+ peer->set_supported_protocols(ws_protocols);
-void EditorDebuggerServerWebSocket::poll() {
- server->poll();
+ Error err = peer->accept_stream(tcp_server->take_connection());
+ if (err == OK) {
+ pending_timer = OS::get_singleton()->get_ticks_msec();
+ pending_peer = peer;
+ }
+ }
+ if (pending_peer.is_valid() && pending_peer->get_ready_state() != WebSocketPeer::STATE_OPEN) {
+ pending_peer->poll();
+ WebSocketPeer::State ready_state = pending_peer->get_ready_state();
+ if (ready_state != WebSocketPeer::STATE_CONNECTING && ready_state != WebSocketPeer::STATE_OPEN) {
+ pending_peer.unref(); // Failed.
+ }
+ if (ready_state == WebSocketPeer::STATE_CONNECTING && OS::get_singleton()->get_ticks_msec() - pending_timer > 3000) {
+ pending_peer.unref(); // Timeout.
+ }
+ }
}
String EditorDebuggerServerWebSocket::get_uri() const {
@@ -69,15 +82,10 @@ Error EditorDebuggerServerWebSocket::start(const String &p_uri) {
ERR_FAIL_COND_V(!bind_host.is_valid_ip_address() && bind_host != "*", ERR_INVALID_PARAMETER);
}
- // Set up the server
- server->set_bind_ip(bind_host);
- Vector<String> compatible_protocols;
- compatible_protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer.
-
// Try listening on ports
const int max_attempts = 5;
for (int attempt = 1;; ++attempt) {
- const Error err = server->listen(bind_port, compatible_protocols);
+ const Error err = tcp_server->listen(bind_port, bind_host);
if (err == OK) {
break;
}
@@ -96,31 +104,27 @@ Error EditorDebuggerServerWebSocket::start(const String &p_uri) {
}
void EditorDebuggerServerWebSocket::stop() {
- server->stop();
- pending_peers.clear();
+ pending_peer.unref();
+ tcp_server->stop();
}
bool EditorDebuggerServerWebSocket::is_active() const {
- return server->is_listening();
+ return tcp_server->is_listening();
}
bool EditorDebuggerServerWebSocket::is_connection_available() const {
- return pending_peers.size() > 0;
+ return pending_peer.is_valid() && pending_peer->get_ready_state() == WebSocketPeer::STATE_OPEN;
}
Ref<RemoteDebuggerPeer> EditorDebuggerServerWebSocket::take_connection() {
ERR_FAIL_COND_V(!is_connection_available(), Ref<RemoteDebuggerPeer>());
- RemoteDebuggerPeer *peer = memnew(RemoteDebuggerPeerWebSocket(server->get_peer(pending_peers[0])));
- pending_peers.pop_front();
+ RemoteDebuggerPeer *peer = memnew(RemoteDebuggerPeerWebSocket(pending_peer));
+ pending_peer.unref();
return peer;
}
EditorDebuggerServerWebSocket::EditorDebuggerServerWebSocket() {
- server = Ref<WebSocketServer>(WebSocketServer::create());
- int max_pkts = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages");
- server->set_buffers(8192, max_pkts, 8192, max_pkts);
- server->connect("client_connected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_connected));
- server->connect("client_disconnected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_disconnected));
+ tcp_server.instantiate();
}
EditorDebuggerServerWebSocket::~EditorDebuggerServerWebSocket() {
diff --git a/modules/websocket/editor/editor_debugger_server_websocket.h b/modules/websocket/editor/editor_debugger_server_websocket.h
index 7c0705302d..31e54cb5df 100644
--- a/modules/websocket/editor/editor_debugger_server_websocket.h
+++ b/modules/websocket/editor/editor_debugger_server_websocket.h
@@ -33,15 +33,18 @@
#ifdef TOOLS_ENABLED
-#include "../websocket_server.h"
+#include "../websocket_peer.h"
+
+#include "core/io/tcp_server.h"
#include "editor/debugger/editor_debugger_server.h"
class EditorDebuggerServerWebSocket : public EditorDebuggerServer {
GDCLASS(EditorDebuggerServerWebSocket, EditorDebuggerServer);
private:
- Ref<WebSocketServer> server;
- List<int> pending_peers;
+ Ref<TCPServer> tcp_server;
+ Ref<WebSocketPeer> pending_peer;
+ uint64_t pending_timer = 0;
String endpoint;
public:
diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp
deleted file mode 100644
index 933a1f43e9..0000000000
--- a/modules/websocket/emws_client.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*************************************************************************/
-/* emws_client.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. */
-/*************************************************************************/
-
-#ifdef WEB_ENABLED
-
-#include "emws_client.h"
-
-#include "core/config/project_settings.h"
-#include "core/io/ip.h"
-#include "emscripten.h"
-
-void EMWSClient::_esws_on_connect(void *obj, char *proto) {
- EMWSClient *client = static_cast<EMWSClient *>(obj);
- client->_is_connecting = false;
- client->_on_connect(String(proto));
-}
-
-void EMWSClient::_esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string) {
- EMWSClient *client = static_cast<EMWSClient *>(obj);
-
- Error err = static_cast<EMWSPeer *>(*client->get_peer(1))->read_msg(p_data, p_data_size, p_is_string == 1);
- if (err == OK) {
- client->_on_peer_packet();
- }
-}
-
-void EMWSClient::_esws_on_error(void *obj) {
- EMWSClient *client = static_cast<EMWSClient *>(obj);
- client->_is_connecting = false;
- client->_on_error();
-}
-
-void EMWSClient::_esws_on_close(void *obj, int code, const char *reason, int was_clean) {
- EMWSClient *client = static_cast<EMWSClient *>(obj);
- client->_on_close_request(code, String(reason));
- client->_is_connecting = false;
- client->disconnect_from_host();
- client->_on_disconnect(was_clean != 0);
-}
-
-Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
- if (_js_id) {
- godot_js_websocket_destroy(_js_id);
- _js_id = 0;
- }
-
- String proto_string;
- for (int i = 0; i < p_protocols.size(); i++) {
- if (i != 0) {
- proto_string += ",";
- }
- proto_string += p_protocols[i];
- }
-
- String str = "ws://";
-
- if (p_custom_headers.size()) {
- WARN_PRINT_ONCE("Custom headers are not supported in Web platform.");
- }
- if (p_tls) {
- str = "wss://";
- if (tls_cert.is_valid()) {
- WARN_PRINT_ONCE("Custom SSL certificate is not supported in Web platform.");
- }
- }
- str += p_host + ":" + itos(p_port) + p_path;
- _is_connecting = true;
-
- _js_id = godot_js_websocket_create(this, str.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close);
- if (!_js_id) {
- return FAILED;
- }
-
- static_cast<Ref<EMWSPeer>>(_peer)->set_sock(_js_id, _in_buf_size, _in_pkt_size, _out_buf_size);
-
- return OK;
-}
-
-void EMWSClient::poll() {
-}
-
-Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const {
- return _peer;
-}
-
-MultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const {
- if (_peer->is_connected_to_host()) {
- if (_is_connecting) {
- return CONNECTION_CONNECTING;
- }
- return CONNECTION_CONNECTED;
- }
-
- return CONNECTION_DISCONNECTED;
-}
-
-void EMWSClient::disconnect_from_host(int p_code, String p_reason) {
- _peer->close(p_code, p_reason);
-}
-
-IPAddress EMWSClient::get_connected_host() const {
- ERR_FAIL_V_MSG(IPAddress(), "Not supported in Web export.");
-}
-
-uint16_t EMWSClient::get_connected_port() const {
- ERR_FAIL_V_MSG(0, "Not supported in Web export.");
-}
-
-int EMWSClient::get_max_packet_size() const {
- return (1 << _in_buf_size) - PROTO_SIZE;
-}
-
-Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
- _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
- _in_pkt_size = nearest_shift(p_in_packets - 1);
- _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
- return OK;
-}
-
-EMWSClient::EMWSClient() {
- _peer = Ref<EMWSPeer>(memnew(EMWSPeer));
-}
-
-EMWSClient::~EMWSClient() {
- disconnect_from_host();
- _peer = Ref<EMWSPeer>();
- if (_js_id) {
- godot_js_websocket_destroy(_js_id);
- }
-}
-
-#endif // WEB_ENABLED
diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp
index 859c92b457..3bd132bc73 100644
--- a/modules/websocket/emws_peer.cpp
+++ b/modules/websocket/emws_peer.cpp
@@ -34,55 +34,116 @@
#include "core/io/ip.h"
-void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size) {
- peer_sock = p_sock;
- _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
- _packet_buffer.resize((1 << p_in_buf_size));
- _out_buf_size = p_out_buf_size;
+void EMWSPeer::_esws_on_connect(void *p_obj, char *p_proto) {
+ EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
+ peer->ready_state = STATE_OPEN;
+ peer->selected_protocol.parse_utf8(p_proto);
}
-void EMWSPeer::set_write_mode(WriteMode p_mode) {
- write_mode = p_mode;
+void EMWSPeer::_esws_on_message(void *p_obj, const uint8_t *p_data, int p_data_size, int p_is_string) {
+ EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
+ uint8_t is_string = p_is_string ? 1 : 0;
+ peer->in_buffer.write_packet(p_data, p_data_size, &is_string);
}
-EMWSPeer::WriteMode EMWSPeer::get_write_mode() const {
- return write_mode;
+void EMWSPeer::_esws_on_error(void *p_obj) {
+ EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
+ peer->ready_state = STATE_CLOSED;
}
-Error EMWSPeer::read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string) {
- uint8_t is_string = p_is_string ? 1 : 0;
- return _in_buffer.write_packet(p_data, p_size, &is_string);
+void EMWSPeer::_esws_on_close(void *p_obj, int p_code, const char *p_reason, int p_was_clean) {
+ EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
+ peer->close_code = p_code;
+ peer->close_reason.parse_utf8(p_reason);
+ peer->ready_state = STATE_CLOSED;
}
-Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
- ERR_FAIL_COND_V(_out_buf_size && ((uint64_t)godot_js_websocket_buffered_amount(peer_sock) + p_buffer_size >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY);
+Error EMWSPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
+ ERR_FAIL_COND_V(ready_state != STATE_CLOSED, ERR_ALREADY_IN_USE);
+ _clear();
+
+ String host;
+ String path;
+ String scheme;
+ int port = 0;
+ Error err = p_url.parse_url(scheme, host, port, path);
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);
+
+ if (scheme.is_empty()) {
+ scheme = "ws://";
+ }
+ ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme));
+
+ String proto_string;
+ for (int i = 0; i < supported_protocols.size(); i++) {
+ if (i != 0) {
+ proto_string += ",";
+ }
+ proto_string += supported_protocols[i];
+ }
+
+ if (handshake_headers.size()) {
+ WARN_PRINT_ONCE("Custom headers are not supported in Web platform.");
+ }
+ if (p_tls_certificate.is_valid()) {
+ WARN_PRINT_ONCE("Custom SSL certificates are not supported in Web platform.");
+ }
- int is_bin = write_mode == WebSocketPeer::WRITE_MODE_BINARY ? 1 : 0;
+ requested_url = scheme + host;
- if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, is_bin) != 0) {
+ if (port && ((scheme == "ws://" && port != 80) || (scheme == "wss://" && port != 443))) {
+ requested_url += ":" + String::num(port);
+ }
+
+ peer_sock = godot_js_websocket_create(this, requested_url.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close);
+ if (peer_sock == -1) {
return FAILED;
}
+ in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
+ packet_buffer.resize(inbound_buffer_size);
+ ready_state = STATE_CONNECTING;
+ return OK;
+}
+
+Error EMWSPeer::accept_stream(Ref<StreamPeer> p_stream) {
+ WARN_PRINT_ONCE("Acting as WebSocket server is not supported in Web platforms.");
+ return ERR_UNAVAILABLE;
+}
+
+Error EMWSPeer::_send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary) {
+ ERR_FAIL_COND_V(outbound_buffer_size > 0 && (get_current_outbound_buffered_amount() + p_buffer_size >= outbound_buffer_size), ERR_OUT_OF_MEMORY);
+ if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, p_binary ? 1 : 0) != 0) {
+ return FAILED;
+ }
return OK;
}
+Error EMWSPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) {
+ return _send(p_buffer, p_buffer_size, p_mode == WRITE_MODE_BINARY);
+}
+
+Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+ return _send(p_buffer, p_buffer_size, true);
+}
+
Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
- if (_in_buffer.packets_left() == 0) {
+ if (in_buffer.packets_left() == 0) {
return ERR_UNAVAILABLE;
}
int read = 0;
- Error err = _in_buffer.read_packet(_packet_buffer.ptrw(), _packet_buffer.size(), &_is_string, read);
+ Error err = in_buffer.read_packet(packet_buffer.ptrw(), packet_buffer.size(), &was_string, read);
ERR_FAIL_COND_V(err != OK, err);
- *r_buffer = _packet_buffer.ptr();
+ *r_buffer = packet_buffer.ptr();
r_buffer_size = read;
return OK;
}
int EMWSPeer::get_available_packet_count() const {
- return _in_buffer.packets_left();
+ return in_buffer.packets_left();
}
int EMWSPeer::get_current_outbound_buffered_amount() const {
@@ -93,20 +154,66 @@ int EMWSPeer::get_current_outbound_buffered_amount() const {
}
bool EMWSPeer::was_string_packet() const {
- return _is_string;
+ return was_string;
}
-bool EMWSPeer::is_connected_to_host() const {
- return peer_sock != -1;
+void EMWSPeer::_clear() {
+ if (peer_sock != -1) {
+ godot_js_websocket_destroy(peer_sock);
+ peer_sock = -1;
+ }
+ ready_state = STATE_CLOSED;
+ was_string = 0;
+ close_code = -1;
+ close_reason.clear();
+ selected_protocol.clear();
+ requested_url.clear();
+ in_buffer.clear();
+ packet_buffer.clear();
}
void EMWSPeer::close(int p_code, String p_reason) {
- if (peer_sock != -1) {
- godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data());
+ if (p_code < 0) {
+ if (peer_sock != -1) {
+ godot_js_websocket_destroy(peer_sock);
+ peer_sock = -1;
+ }
+ ready_state = STATE_CLOSED;
+ }
+ if (ready_state == STATE_CONNECTING || ready_state == STATE_OPEN) {
+ ready_state = STATE_CLOSING;
+ if (peer_sock != -1) {
+ godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data());
+ } else {
+ ready_state = STATE_CLOSED;
+ }
}
- _is_string = 0;
- _in_buffer.clear();
- peer_sock = -1;
+ in_buffer.clear();
+ packet_buffer.clear();
+}
+
+void EMWSPeer::poll() {
+ // Automatically polled by the navigator.
+}
+
+WebSocketPeer::State EMWSPeer::get_ready_state() const {
+ return ready_state;
+}
+
+int EMWSPeer::get_close_code() const {
+ return close_code;
+}
+
+String EMWSPeer::get_close_reason() const {
+ return close_reason;
+}
+
+String EMWSPeer::get_selected_protocol() const {
+ return selected_protocol;
+}
+
+String EMWSPeer::get_requested_url() const {
+ return requested_url;
}
IPAddress EMWSPeer::get_connected_host() const {
@@ -122,11 +229,10 @@ void EMWSPeer::set_no_delay(bool p_enabled) {
}
EMWSPeer::EMWSPeer() {
- close();
}
EMWSPeer::~EMWSPeer() {
- close();
+ _clear();
}
#endif // WEB_ENABLED
diff --git a/modules/websocket/emws_peer.h b/modules/websocket/emws_peer.h
index cdbc9212a5..322cc3b700 100644
--- a/modules/websocket/emws_peer.h
+++ b/modules/websocket/emws_peer.h
@@ -54,33 +54,53 @@ extern void godot_js_websocket_destroy(int p_id);
}
class EMWSPeer : public WebSocketPeer {
- GDCIIMPL(EMWSPeer, WebSocketPeer);
-
private:
int peer_sock = -1;
- WriteMode write_mode = WRITE_MODE_BINARY;
- Vector<uint8_t> _packet_buffer;
- PacketBuffer<uint8_t> _in_buffer;
- uint8_t _is_string = 0;
- int _out_buf_size = 0;
+ State ready_state = STATE_CLOSED;
+ Vector<uint8_t> packet_buffer;
+ PacketBuffer<uint8_t> in_buffer;
+ uint8_t was_string = 0;
+ int close_code = -1;
+ String close_reason;
+ String selected_protocol;
+ String requested_url;
+
+ static WebSocketPeer *_create() { return memnew(EMWSPeer); }
+ static void _esws_on_connect(void *obj, char *proto);
+ static void _esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string);
+ static void _esws_on_error(void *obj);
+ static void _esws_on_close(void *obj, int code, const char *reason, int was_clean);
+
+ void _clear();
+ Error _send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary);
public:
- Error read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string);
- void set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size);
+ static void initialize() { WebSocketPeer::_create = EMWSPeer::_create; }
+
+ // PacketPeer
virtual int get_available_packet_count() const override;
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override;
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- virtual int get_max_packet_size() const override { return _packet_buffer.size(); };
- virtual int get_current_outbound_buffered_amount() const override;
+ virtual int get_max_packet_size() const override { return packet_buffer.size(); };
+ // WebSocketPeer
+ virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) override;
+ virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) override;
+ virtual Error accept_stream(Ref<StreamPeer> p_stream) override;
virtual void close(int p_code = 1000, String p_reason = "") override;
- virtual bool is_connected_to_host() const override;
+ virtual void poll() override;
+
+ virtual State get_ready_state() const override;
+ virtual int get_close_code() const override;
+ virtual String get_close_reason() const override;
+ virtual int get_current_outbound_buffered_amount() const override;
+
virtual IPAddress get_connected_host() const override;
virtual uint16_t get_connected_port() const override;
+ virtual String get_selected_protocol() const override;
+ virtual String get_requested_url() const override;
- virtual WriteMode get_write_mode() const override;
- virtual void set_write_mode(WriteMode p_mode) override;
virtual bool was_string_packet() const override;
virtual void set_no_delay(bool p_enabled) override;
diff --git a/modules/websocket/packet_buffer.h b/modules/websocket/packet_buffer.h
index 7b4a164576..cd81dc43cd 100644
--- a/modules/websocket/packet_buffer.h
+++ b/modules/websocket/packet_buffer.h
@@ -41,32 +41,29 @@ private:
T info;
} _Packet;
- RingBuffer<_Packet> _packets;
+ Vector<_Packet> _packets;
+ int _queued = 0;
+ int _write_pos = 0;
+ int _read_pos = 0;
RingBuffer<uint8_t> _payload;
public:
Error write_packet(const uint8_t *p_payload, uint32_t p_size, const T *p_info) {
-#ifdef TOOLS_ENABLED
- // Verbose buffer warnings
- if (p_payload && _payload.space_left() < (int32_t)p_size) {
- ERR_PRINT("Buffer payload full! Dropping data.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
- }
- if (p_info && _packets.space_left() < 1) {
- ERR_PRINT("Too many packets in queue! Dropping data.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
- }
-#else
- ERR_FAIL_COND_V(p_payload && (uint32_t)_payload.space_left() < p_size, ERR_OUT_OF_MEMORY);
- ERR_FAIL_COND_V(p_info && _packets.space_left() < 1, ERR_OUT_OF_MEMORY);
-#endif
+ ERR_FAIL_COND_V_MSG(p_payload && (uint32_t)_payload.space_left() < p_size, ERR_OUT_OF_MEMORY, "Buffer payload full! Dropping data.");
+ ERR_FAIL_COND_V_MSG(p_info && _queued >= _packets.size(), ERR_OUT_OF_MEMORY, "Too many packets in queue! Dropping data.");
// If p_info is nullptr, only the payload is written
if (p_info) {
+ ERR_FAIL_COND_V(_write_pos > _packets.size(), ERR_OUT_OF_MEMORY);
_Packet p;
p.size = p_size;
- memcpy(&p.info, p_info, sizeof(T));
- _packets.write(p);
+ p.info = *p_info;
+ _packets.write[_write_pos] = p;
+ _queued += 1;
+ _write_pos++;
+ if (_write_pos >= _packets.size()) {
+ _write_pos = 0;
+ }
}
// If p_payload is nullptr, only the packet information is written.
@@ -78,9 +75,14 @@ public:
}
Error read_packet(uint8_t *r_payload, int p_bytes, T *r_info, int &r_read) {
- ERR_FAIL_COND_V(_packets.data_left() < 1, ERR_UNAVAILABLE);
- _Packet p;
- _packets.read(&p, 1);
+ ERR_FAIL_COND_V(_queued < 1, ERR_UNAVAILABLE);
+ _Packet p = _packets[_read_pos];
+ _read_pos += 1;
+ if (_read_pos >= _packets.size()) {
+ _read_pos = 0;
+ }
+ _queued -= 1;
+
ERR_FAIL_COND_V(_payload.data_left() < (int)p.size, ERR_BUG);
ERR_FAIL_COND_V(p_bytes < (int)p.size, ERR_OUT_OF_MEMORY);
@@ -90,22 +92,24 @@ public:
return OK;
}
- void discard_payload(int p_size) {
- _packets.decrease_write(p_size);
- }
-
- void resize(int p_pkt_shift, int p_buf_shift) {
- _packets.resize(p_pkt_shift);
+ void resize(int p_buf_shift, int p_max_packets) {
_payload.resize(p_buf_shift);
+ _packets.resize(p_max_packets);
+ _read_pos = 0;
+ _write_pos = 0;
+ _queued = 0;
}
int packets_left() const {
- return _packets.data_left();
+ return _queued;
}
void clear() {
_payload.resize(0);
_packets.resize(0);
+ _read_pos = 0;
+ _write_pos = 0;
+ _queued = 0;
}
PacketBuffer() {
diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp
index faa7021b2f..c55a651ab0 100644
--- a/modules/websocket/register_types.cpp
+++ b/modules/websocket/register_types.cpp
@@ -31,18 +31,18 @@
#include "register_types.h"
#include "core/config/project_settings.h"
+#include "core/debugger/engine_debugger.h"
#include "core/error/error_macros.h"
-#include "websocket_client.h"
-#include "websocket_server.h"
+#include "websocket_multiplayer_peer.h"
+#include "websocket_peer.h"
+
+#include "remote_debugger_peer_websocket.h"
#ifdef WEB_ENABLED
-#include "emscripten.h"
-#include "emws_client.h"
#include "emws_peer.h"
#else
-#include "wsl_client.h"
-#include "wsl_server.h"
+#include "wsl_peer.h"
#endif
#ifdef TOOLS_ENABLED
@@ -58,20 +58,18 @@ static void _editor_init_callback() {
#endif
void initialize_websocket_module(ModuleInitializationLevel p_level) {
- if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) {
+ if (p_level == MODULE_INITIALIZATION_LEVEL_CORE) {
#ifdef WEB_ENABLED
- EMWSPeer::make_default();
- EMWSClient::make_default();
+ EMWSPeer::initialize();
#else
- WSLPeer::make_default();
- WSLClient::make_default();
- WSLServer::make_default();
+ WSLPeer::initialize();
#endif
- GDREGISTER_ABSTRACT_CLASS(WebSocketMultiplayerPeer);
- ClassDB::register_custom_instance_class<WebSocketServer>();
- ClassDB::register_custom_instance_class<WebSocketClient>();
+ GDREGISTER_CLASS(WebSocketMultiplayerPeer);
ClassDB::register_custom_instance_class<WebSocketPeer>();
+
+ EngineDebugger::register_uri_handler("ws://", RemoteDebuggerPeerWebSocket::create);
+ EngineDebugger::register_uri_handler("wss://", RemoteDebuggerPeerWebSocket::create);
}
#ifdef TOOLS_ENABLED
@@ -82,7 +80,10 @@ void initialize_websocket_module(ModuleInitializationLevel p_level) {
}
void uninitialize_websocket_module(ModuleInitializationLevel p_level) {
- if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
+ if (p_level != MODULE_INITIALIZATION_LEVEL_CORE) {
return;
}
+#ifndef WEB_ENABLED
+ WSLPeer::deinitialize();
+#endif
}
diff --git a/modules/websocket/remote_debugger_peer_websocket.cpp b/modules/websocket/remote_debugger_peer_websocket.cpp
index f703873cbf..58adb76208 100644
--- a/modules/websocket/remote_debugger_peer_websocket.cpp
+++ b/modules/websocket/remote_debugger_peer_websocket.cpp
@@ -33,30 +33,39 @@
#include "core/config/project_settings.h"
Error RemoteDebuggerPeerWebSocket::connect_to_host(const String &p_uri) {
+ ws_peer = Ref<WebSocketPeer>(WebSocketPeer::create());
+ ERR_FAIL_COND_V(ws_peer.is_null(), ERR_BUG);
+
Vector<String> protocols;
protocols.push_back("binary"); // Compatibility for emscripten TCP-to-WebSocket.
- ws_client->connect_to_url(p_uri, protocols);
- ws_client->poll();
+ ws_peer->set_supported_protocols(protocols);
+ ws_peer->set_max_queued_packets(max_queued_messages);
+ ws_peer->set_inbound_buffer_size((1 << 23) - 1);
+ ws_peer->set_outbound_buffer_size((1 << 23) - 1);
+
+ Error err = ws_peer->connect_to_url(p_uri);
+ ERR_FAIL_COND_V(err != OK, err);
- if (ws_client->get_connection_status() == WebSocketClient::CONNECTION_DISCONNECTED) {
- ERR_PRINT("Remote Debugger: Unable to connect. Status: " + String::num(ws_client->get_connection_status()) + ".");
+ ws_peer->poll();
+ WebSocketPeer::State ready_state = ws_peer->get_ready_state();
+ if (ready_state != WebSocketPeer::STATE_CONNECTING && ready_state != WebSocketPeer::STATE_OPEN) {
+ ERR_PRINT(vformat("Remote Debugger: Unable to connect. State: %s.", ws_peer->get_ready_state()));
return FAILED;
}
- ws_peer = ws_client->get_peer(1);
-
return OK;
}
bool RemoteDebuggerPeerWebSocket::is_peer_connected() {
- return ws_peer.is_valid() && ws_peer->is_connected_to_host();
+ return ws_peer.is_valid() && (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN || ws_peer->get_ready_state() == WebSocketPeer::STATE_CONNECTING);
}
void RemoteDebuggerPeerWebSocket::poll() {
- ws_client->poll();
+ ERR_FAIL_COND(ws_peer.is_null());
+ ws_peer->poll();
- while (ws_peer->is_connected_to_host() && ws_peer->get_available_packet_count() > 0 && in_queue.size() < max_queued_messages) {
+ while (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN && ws_peer->get_available_packet_count() > 0 && in_queue.size() < max_queued_messages) {
Variant var;
Error err = ws_peer->get_var(var);
ERR_CONTINUE(err != OK);
@@ -64,7 +73,7 @@ void RemoteDebuggerPeerWebSocket::poll() {
in_queue.push_back(var);
}
- while (ws_peer->is_connected_to_host() && out_queue.size() > 0) {
+ while (ws_peer->get_ready_state() == WebSocketPeer::STATE_OPEN && out_queue.size() > 0) {
Array var = out_queue[0];
Error err = ws_peer->put_var(var);
ERR_BREAK(err != OK); // Peer buffer full?
@@ -73,7 +82,8 @@ void RemoteDebuggerPeerWebSocket::poll() {
}
int RemoteDebuggerPeerWebSocket::get_max_message_size() const {
- return 8 << 20; // 8 Mib
+ ERR_FAIL_COND_V(ws_peer.is_null(), 0);
+ return ws_peer->get_max_packet_size();
}
bool RemoteDebuggerPeerWebSocket::has_message() {
@@ -99,7 +109,6 @@ void RemoteDebuggerPeerWebSocket::close() {
if (ws_peer.is_valid()) {
ws_peer.unref();
}
- ws_client->disconnect_from_host();
}
bool RemoteDebuggerPeerWebSocket::can_block() const {
@@ -111,14 +120,13 @@ bool RemoteDebuggerPeerWebSocket::can_block() const {
}
RemoteDebuggerPeerWebSocket::RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer) {
-#ifdef WEB_ENABLED
- ws_client = Ref<WebSocketClient>(memnew(EMWSClient));
-#else
- ws_client = Ref<WebSocketClient>(memnew(WSLClient));
-#endif
max_queued_messages = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages");
- ws_client->set_buffers(8192, max_queued_messages, 8192, max_queued_messages);
ws_peer = p_peer;
+ if (ws_peer.is_valid()) {
+ ws_peer->set_max_queued_packets(max_queued_messages);
+ ws_peer->set_inbound_buffer_size((1 << 23) - 1);
+ ws_peer->set_outbound_buffer_size((1 << 23) - 1);
+ }
}
RemoteDebuggerPeer *RemoteDebuggerPeerWebSocket::create(const String &p_uri) {
diff --git a/modules/websocket/remote_debugger_peer_websocket.h b/modules/websocket/remote_debugger_peer_websocket.h
index 0292de68ad..4d496ae891 100644
--- a/modules/websocket/remote_debugger_peer_websocket.h
+++ b/modules/websocket/remote_debugger_peer_websocket.h
@@ -33,14 +33,9 @@
#include "core/debugger/remote_debugger_peer.h"
-#ifdef WEB_ENABLED
-#include "emws_client.h"
-#else
-#include "wsl_client.h"
-#endif
+#include "websocket_peer.h"
class RemoteDebuggerPeerWebSocket : public RemoteDebuggerPeer {
- Ref<WebSocketClient> ws_client;
Ref<WebSocketPeer> ws_peer;
List<Array> in_queue;
List<Array> out_queue;
diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp
deleted file mode 100644
index 0b2d5d1918..0000000000
--- a/modules/websocket/websocket_client.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-/*************************************************************************/
-/* websocket_client.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 "websocket_client.h"
-
-GDCINULL(WebSocketClient);
-
-WebSocketClient::WebSocketClient() {
-}
-
-WebSocketClient::~WebSocketClient() {
-}
-
-Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_protocols, bool gd_mp_api, const Vector<String> p_custom_headers) {
- _is_multiplayer = gd_mp_api;
-
- String host = p_url;
- String path;
- String scheme;
- int port = 0;
- Error err = p_url.parse_url(scheme, host, port, path);
- ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);
-
- bool tls = false;
- if (scheme == "wss://") {
- tls = true;
- }
- if (port == 0) {
- port = tls ? 443 : 80;
- }
- if (path.is_empty()) {
- path = "/";
- }
- return connect_to_host(host, path, port, tls, p_protocols, p_custom_headers);
-}
-
-void WebSocketClient::set_verify_tls_enabled(bool p_verify_tls) {
- verify_tls = p_verify_tls;
-}
-
-bool WebSocketClient::is_verify_tls_enabled() const {
- return verify_tls;
-}
-
-Ref<X509Certificate> WebSocketClient::get_trusted_tls_certificate() const {
- return tls_cert;
-}
-
-void WebSocketClient::set_trusted_tls_certificate(Ref<X509Certificate> p_cert) {
- ERR_FAIL_COND(get_connection_status() != CONNECTION_DISCONNECTED);
- tls_cert = p_cert;
-}
-
-bool WebSocketClient::is_server() const {
- return false;
-}
-
-void WebSocketClient::_on_peer_packet() {
- if (_is_multiplayer) {
- _process_multiplayer(get_peer(1), 1);
- } else {
- emit_signal(SNAME("data_received"));
- }
-}
-
-void WebSocketClient::_on_connect(String p_protocol) {
- if (_is_multiplayer) {
- // need to wait for ID confirmation...
- } else {
- emit_signal(SNAME("connection_established"), p_protocol);
- }
-}
-
-void WebSocketClient::_on_close_request(int p_code, String p_reason) {
- emit_signal(SNAME("server_close_request"), p_code, p_reason);
-}
-
-void WebSocketClient::_on_disconnect(bool p_was_clean) {
- if (_is_multiplayer) {
- emit_signal(SNAME("connection_failed"));
- } else {
- emit_signal(SNAME("connection_closed"), p_was_clean);
- }
-}
-
-void WebSocketClient::_on_error() {
- if (_is_multiplayer) {
- emit_signal(SNAME("connection_failed"));
- } else {
- emit_signal(SNAME("connection_error"));
- }
-}
-
-void WebSocketClient::_bind_methods() {
- ClassDB::bind_method(D_METHOD("connect_to_url", "url", "protocols", "gd_mp_api", "custom_headers"), &WebSocketClient::connect_to_url, DEFVAL(Vector<String>()), DEFVAL(false), DEFVAL(Vector<String>()));
- ClassDB::bind_method(D_METHOD("disconnect_from_host", "code", "reason"), &WebSocketClient::disconnect_from_host, DEFVAL(1000), DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketClient::get_connected_host);
- ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketClient::get_connected_port);
- ClassDB::bind_method(D_METHOD("set_verify_tls_enabled", "enabled"), &WebSocketClient::set_verify_tls_enabled);
- ClassDB::bind_method(D_METHOD("is_verify_tls_enabled"), &WebSocketClient::is_verify_tls_enabled);
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_tls", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_verify_tls_enabled", "is_verify_tls_enabled");
-
- ClassDB::bind_method(D_METHOD("get_trusted_tls_certificate"), &WebSocketClient::get_trusted_tls_certificate);
- ClassDB::bind_method(D_METHOD("set_trusted_tls_certificate", "cert"), &WebSocketClient::set_trusted_tls_certificate);
-
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_trusted_tls_certificate", "get_trusted_tls_certificate");
-
- ADD_SIGNAL(MethodInfo("data_received"));
- ADD_SIGNAL(MethodInfo("connection_established", PropertyInfo(Variant::STRING, "protocol")));
- ADD_SIGNAL(MethodInfo("server_close_request", PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason")));
- ADD_SIGNAL(MethodInfo("connection_closed", PropertyInfo(Variant::BOOL, "was_clean_close")));
- ADD_SIGNAL(MethodInfo("connection_error"));
-}
diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp
index 7a3bbf1c47..0202c5bac7 100644
--- a/modules/websocket/websocket_multiplayer_peer.cpp
+++ b/modules/websocket/websocket_multiplayer_peer.cpp
@@ -33,72 +33,130 @@
#include "core/os/os.h"
WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() {
+ peer_config = Ref<WebSocketPeer>(WebSocketPeer::create());
}
WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() {
_clear();
}
+Ref<WebSocketPeer> WebSocketMultiplayerPeer::_create_peer() {
+ Ref<WebSocketPeer> peer = Ref<WebSocketPeer>(WebSocketPeer::create());
+ peer->set_supported_protocols(get_supported_protocols());
+ peer->set_handshake_headers(get_handshake_headers());
+ peer->set_inbound_buffer_size(get_inbound_buffer_size());
+ peer->set_outbound_buffer_size(get_outbound_buffer_size());
+ peer->set_max_queued_packets(get_max_queued_packets());
+ return peer;
+}
+
void WebSocketMultiplayerPeer::_clear() {
- _peer_map.clear();
- if (_current_packet.data != nullptr) {
- memfree(_current_packet.data);
+ connection_status = CONNECTION_DISCONNECTED;
+ unique_id = 0;
+ peers_map.clear();
+ use_tls = false;
+ tcp_server.unref();
+ pending_peers.clear();
+ tls_certificate.unref();
+ tls_key.unref();
+ if (current_packet.data != nullptr) {
+ memfree(current_packet.data);
+ current_packet.data = nullptr;
}
- for (Packet &E : _incoming_packets) {
+ for (Packet &E : incoming_packets) {
memfree(E.data);
E.data = nullptr;
}
- _incoming_packets.clear();
+ incoming_packets.clear();
}
void WebSocketMultiplayerPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_buffers", "input_buffer_size_kb", "input_max_packets", "output_buffer_size_kb", "output_max_packets"), &WebSocketMultiplayerPeer::set_buffers);
+ ClassDB::bind_method(D_METHOD("create_client", "url", "verify_tls", "tls_certificate"), &WebSocketMultiplayerPeer::create_client, DEFVAL(true), DEFVAL(Ref<X509Certificate>()));
+ ClassDB::bind_method(D_METHOD("create_server", "port", "bind_address", "tls_key", "tls_certificate"), &WebSocketMultiplayerPeer::create_server, DEFVAL("*"), DEFVAL(Ref<CryptoKey>()), DEFVAL(Ref<X509Certificate>()));
+ ClassDB::bind_method(D_METHOD("close"), &WebSocketMultiplayerPeer::close);
+
ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer);
+ ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketMultiplayerPeer::get_peer_address);
+ ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketMultiplayerPeer::get_peer_port);
+ ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "code", "reason"), &WebSocketMultiplayerPeer::disconnect_peer, DEFVAL(1000), DEFVAL(""));
+
+ ClassDB::bind_method(D_METHOD("get_supported_protocols"), &WebSocketMultiplayerPeer::get_supported_protocols);
+ ClassDB::bind_method(D_METHOD("set_supported_protocols", "protocols"), &WebSocketMultiplayerPeer::set_supported_protocols);
+
+ ClassDB::bind_method(D_METHOD("get_handshake_headers"), &WebSocketMultiplayerPeer::get_handshake_headers);
+ ClassDB::bind_method(D_METHOD("set_handshake_headers", "protocols"), &WebSocketMultiplayerPeer::set_handshake_headers);
+
+ ClassDB::bind_method(D_METHOD("get_inbound_buffer_size"), &WebSocketMultiplayerPeer::get_inbound_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_inbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_inbound_buffer_size);
+
+ ClassDB::bind_method(D_METHOD("get_outbound_buffer_size"), &WebSocketMultiplayerPeer::get_outbound_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_outbound_buffer_size", "buffer_size"), &WebSocketMultiplayerPeer::set_outbound_buffer_size);
+
+ ClassDB::bind_method(D_METHOD("get_handshake_timeout"), &WebSocketMultiplayerPeer::get_handshake_timeout);
+ ClassDB::bind_method(D_METHOD("set_handshake_timeout", "timeout"), &WebSocketMultiplayerPeer::set_handshake_timeout);
+
+ ClassDB::bind_method(D_METHOD("set_max_queued_packets", "max_queued_packets"), &WebSocketMultiplayerPeer::set_max_queued_packets);
+ ClassDB::bind_method(D_METHOD("get_max_queued_packets"), &WebSocketMultiplayerPeer::get_max_queued_packets);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "supported_protocols"), "set_supported_protocols", "get_supported_protocols");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "handshake_headers"), "set_handshake_headers", "get_handshake_headers");
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "inbound_buffer_size"), "set_inbound_buffer_size", "get_inbound_buffer_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "outbound_buffer_size"), "set_outbound_buffer_size", "get_outbound_buffer_size");
+
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "handshake_timeout"), "set_handshake_timeout", "get_handshake_timeout");
- ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "peer_source")));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_queued_packets"), "set_max_queued_packets", "get_max_queued_packets");
}
//
// PacketPeer
//
int WebSocketMultiplayerPeer::get_available_packet_count() const {
- ERR_FAIL_COND_V_MSG(!_is_multiplayer, 0, "Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI.");
-
- return _incoming_packets.size();
+ return incoming_packets.size();
}
Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
- ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI.");
+ ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
r_buffer_size = 0;
- if (_current_packet.data != nullptr) {
- memfree(_current_packet.data);
- _current_packet.data = nullptr;
+ if (current_packet.data != nullptr) {
+ memfree(current_packet.data);
+ current_packet.data = nullptr;
}
- ERR_FAIL_COND_V(_incoming_packets.size() == 0, ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
- _current_packet = _incoming_packets.front()->get();
- _incoming_packets.pop_front();
+ current_packet = incoming_packets.front()->get();
+ incoming_packets.pop_front();
- *r_buffer = _current_packet.data;
- r_buffer_size = _current_packet.size;
+ *r_buffer = current_packet.data;
+ r_buffer_size = current_packet.size;
return OK;
}
Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
- ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI.");
-
- Vector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), _target_peer, p_buffer, p_buffer_size);
+ ERR_FAIL_COND_V(get_connection_status() != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
if (is_server()) {
- return _server_relay(1, _target_peer, &(buffer.ptr()[0]), buffer.size());
+ if (target_peer > 0) {
+ ERR_FAIL_COND_V_MSG(!peers_map.has(target_peer), ERR_INVALID_PARAMETER, "Peer not found: " + itos(target_peer));
+ get_peer(target_peer)->put_packet(p_buffer, p_buffer_size);
+ } else {
+ for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
+ if (target_peer && -target_peer == E.key) {
+ continue; // Excluded.
+ }
+ E.value->put_packet(p_buffer, p_buffer_size);
+ }
+ }
+ return OK;
} else {
- return get_peer(1)->put_packet(&(buffer.ptr()[0]), buffer.size());
+ return get_peer(1)->put_packet(p_buffer, p_buffer_size);
}
}
@@ -106,185 +164,335 @@ Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer
// MultiplayerPeer
//
void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) {
- _target_peer = p_target_peer;
+ target_peer = p_target_peer;
}
int WebSocketMultiplayerPeer::get_packet_peer() const {
- ERR_FAIL_COND_V_MSG(!_is_multiplayer, 1, "This function is not available when not using the MultiplayerAPI.");
- ERR_FAIL_COND_V(_incoming_packets.size() == 0, 1);
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
- return _incoming_packets.front()->get().source;
+ return incoming_packets.front()->get().source;
}
int WebSocketMultiplayerPeer::get_unique_id() const {
- return _peer_id;
+ return unique_id;
}
-void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id) {
- ERR_FAIL_COND(!p_peer.is_valid());
- ERR_FAIL_COND(!p_peer->is_connected_to_host());
-
- Vector<uint8_t> message = _make_pkt(p_type, 1, 0, (uint8_t *)&p_peer_id, 4);
- p_peer->put_packet(&(message.ptr()[0]), message.size());
+int WebSocketMultiplayerPeer::get_max_packet_size() const {
+ return get_outbound_buffer_size() - PROTO_SIZE;
}
-Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) {
- Vector<uint8_t> out;
- out.resize(PROTO_SIZE + p_data_size);
-
- uint8_t *w = out.ptrw();
- memcpy(&w[0], &p_type, 1);
- memcpy(&w[1], &p_from, 4);
- memcpy(&w[5], &p_to, 4);
- memcpy(&w[PROTO_SIZE], p_data, p_data_size);
-
- return out;
+Error WebSocketMultiplayerPeer::create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate) {
+ ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
+ _clear();
+ tcp_server.instantiate();
+ Error err = tcp_server->listen(p_port, p_bind_ip);
+ if (err != OK) {
+ tcp_server.unref();
+ return err;
+ }
+ unique_id = 1;
+ connection_status = CONNECTION_CONNECTED;
+ // TLS config
+ tls_key = p_tls_key;
+ tls_certificate = p_tls_certificate;
+ if (tls_key.is_valid() && tls_certificate.is_valid()) {
+ use_tls = true;
+ }
+ return OK;
}
-void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) {
- // First of all, confirm the ID!
- _send_sys(get_peer(p_peer_id), SYS_ID, p_peer_id);
+Error WebSocketMultiplayerPeer::create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
+ ERR_FAIL_COND_V(get_connection_status() != CONNECTION_DISCONNECTED, ERR_ALREADY_IN_USE);
+ _clear();
+ Ref<WebSocketPeer> peer = _create_peer();
+ Error err = peer->connect_to_url(p_url, p_verify_tls, p_tls_certificate);
+ if (err != OK) {
+ return err;
+ }
+ PendingPeer pending;
+ pending.time = OS::get_singleton()->get_ticks_msec();
+ pending_peers[1] = pending;
+ peers_map[1] = peer;
+ connection_status = CONNECTION_CONNECTING;
+ return OK;
+}
- // Then send the server peer (which will trigger connection_succeded in client)
- _send_sys(get_peer(p_peer_id), SYS_ADD, 1);
+bool WebSocketMultiplayerPeer::is_server() const {
+ return tcp_server.is_valid();
+}
- for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- int32_t id = E.key;
- if (p_peer_id == id) {
- continue; // Skip the newly added peer (already confirmed)
+void WebSocketMultiplayerPeer::_poll_client() {
+ ERR_FAIL_COND(connection_status == CONNECTION_DISCONNECTED); // Bug.
+ ERR_FAIL_COND(!peers_map.has(1) || peers_map[1].is_null()); // Bug.
+ Ref<WebSocketPeer> peer = peers_map[1];
+ peer->poll(); // Update state and fetch packets.
+ WebSocketPeer::State ready_state = peer->get_ready_state();
+ if (ready_state == WebSocketPeer::STATE_OPEN) {
+ if (connection_status == CONNECTION_CONNECTING) {
+ if (peer->get_available_packet_count() > 0) {
+ const uint8_t *in_buffer;
+ int size = 0;
+ Error err = peer->get_packet(&in_buffer, size);
+ if (err != OK || size != 4) {
+ peer->close(); // Will cause connection error on next poll.
+ ERR_FAIL_MSG("Invalid ID received from server");
+ }
+ unique_id = *((int32_t *)in_buffer);
+ if (unique_id < 2) {
+ peer->close(); // Will cause connection error on next poll.
+ ERR_FAIL_MSG("Invalid ID received from server");
+ }
+ connection_status = CONNECTION_CONNECTED;
+ emit_signal("peer_connected", 1);
+ emit_signal("connection_succeeded");
+ } else {
+ return; // Still waiting for an ID.
+ }
}
-
- // Send new peer to others
- _send_sys(get_peer(id), SYS_ADD, p_peer_id);
- // Send others to new peer
- _send_sys(get_peer(p_peer_id), SYS_ADD, id);
+ int pkts = peer->get_available_packet_count();
+ while (pkts > 0 && peer->get_ready_state() == WebSocketPeer::STATE_OPEN) {
+ const uint8_t *in_buffer;
+ int size = 0;
+ Error err = peer->get_packet(&in_buffer, size);
+ ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND(size <= 0);
+ Packet packet;
+ packet.data = (uint8_t *)memalloc(size);
+ memcpy(packet.data, in_buffer, size);
+ packet.size = size;
+ packet.source = 1;
+ incoming_packets.push_back(packet);
+ pkts--;
+ }
+ } else if (peer->get_ready_state() == WebSocketPeer::STATE_CLOSED) {
+ if (connection_status == CONNECTION_CONNECTED) {
+ emit_signal(SNAME("server_disconnected"));
+ } else {
+ emit_signal(SNAME("connection_failed"));
+ }
+ _clear();
+ return;
}
-}
-
-void WebSocketMultiplayerPeer::_send_del(int32_t p_peer_id) {
- for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- int32_t id = E.key;
- if (p_peer_id != id) {
- _send_sys(get_peer(id), SYS_DEL, p_peer_id);
+ if (connection_status == CONNECTION_CONNECTING) {
+ // Still connecting
+ ERR_FAIL_COND(!pending_peers.has(1)); // Bug.
+ if (OS::get_singleton()->get_ticks_msec() - pending_peers[1].time > handshake_timeout) {
+ print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
+ emit_signal(SNAME("connection_failed"));
+ _clear();
+ return;
}
}
}
-void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size) {
- Packet packet;
- packet.data = (uint8_t *)memalloc(p_data_size);
- packet.size = p_data_size;
- packet.source = p_source;
- packet.destination = p_dest;
- memcpy(packet.data, &p_data[PROTO_SIZE], p_data_size);
- _incoming_packets.push_back(packet);
- emit_signal(SNAME("peer_packet"), p_source);
-}
+void WebSocketMultiplayerPeer::_poll_server() {
+ ERR_FAIL_COND(connection_status != CONNECTION_CONNECTED); // Bug.
+ ERR_FAIL_COND(tcp_server.is_null() || !tcp_server->is_listening()); // Bug.
+
+ // Accept new connections.
+ if (!is_refusing_new_connections() && tcp_server->is_connection_available()) {
+ PendingPeer peer;
+ peer.time = OS::get_singleton()->get_ticks_msec();
+ peer.tcp = tcp_server->take_connection();
+ peer.connection = peer.tcp;
+ pending_peers[generate_unique_id()] = peer;
+ }
-Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) {
- if (p_to == 1) {
- return OK; // Will not send to self
+ // Process pending peers.
+ HashSet<int> to_remove;
+ for (KeyValue<int, PendingPeer> &E : pending_peers) {
+ PendingPeer &peer = E.value;
+ int id = E.key;
- } else if (p_to == 0) {
- for (KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- if (E.key != p_from) {
- E.value->put_packet(p_buffer, p_buffer_size);
+ if (OS::get_singleton()->get_ticks_msec() - peer.time > handshake_timeout) {
+ print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", handshake_timeout * 0.001));
+ to_remove.insert(id);
+ continue;
+ }
+
+ if (peer.ws.is_valid()) {
+ peer.ws->poll();
+ WebSocketPeer::State state = peer.ws->get_ready_state();
+ if (state == WebSocketPeer::STATE_OPEN) {
+ // Connected.
+ to_remove.insert(id);
+ if (is_refusing_new_connections()) {
+ // The user does not want new connections, dropping it.
+ continue;
+ }
+ int32_t peer_id = id;
+ Error err = peer.ws->put_packet((const uint8_t *)&peer_id, sizeof(peer_id));
+ if (err == OK) {
+ peers_map[id] = peer.ws;
+ emit_signal("peer_connected", id);
+ } else {
+ ERR_PRINT("Failed to send ID to newly connected peer.");
+ }
+ continue;
+ } else if (state == WebSocketPeer::STATE_CONNECTING) {
+ continue; // Still connecting.
+ }
+ to_remove.insert(id); // Error.
+ continue;
+ }
+ if (peer.tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
+ to_remove.insert(id); // Error.
+ continue;
+ }
+ if (!use_tls) {
+ peer.ws = _create_peer();
+ peer.ws->accept_stream(peer.tcp);
+ continue;
+ } else {
+ if (peer.connection == peer.tcp) {
+ Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
+ Error err = tls->accept_stream(peer.tcp, tls_key, tls_certificate);
+ if (err != OK) {
+ to_remove.insert(id);
+ continue;
+ }
+ }
+ Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(peer.connection);
+ tls->poll();
+ if (tls->get_status() == StreamPeerTLS::STATUS_CONNECTED) {
+ peer.ws = _create_peer();
+ peer.ws->accept_stream(peer.connection);
+ continue;
+ } else if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
+ // Still connecting.
+ continue;
+ } else {
+ // Error
+ to_remove.insert(id);
}
}
- return OK; // Sent to all but sender
+ }
- } else if (p_to < 0) {
- for (KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- if (E.key != p_from && E.key != -p_to) {
- E.value->put_packet(p_buffer, p_buffer_size);
+ // Remove disconnected pending peers.
+ for (const int &pid : to_remove) {
+ pending_peers.erase(pid);
+ }
+ to_remove.clear();
+
+ // Process connected peers.
+ for (KeyValue<int, Ref<WebSocketPeer>> &E : peers_map) {
+ Ref<WebSocketPeer> ws = E.value;
+ int id = E.key;
+ ws->poll();
+ if (ws->get_ready_state() != WebSocketPeer::STATE_OPEN) {
+ to_remove.insert(id); // Disconnected.
+ continue;
+ }
+ // Fetch packets
+ int pkts = ws->get_available_packet_count();
+ while (pkts > 0 && ws->get_ready_state() == WebSocketPeer::STATE_OPEN) {
+ const uint8_t *in_buffer;
+ int size = 0;
+ Error err = ws->get_packet(&in_buffer, size);
+ if (err != OK || size <= 0) {
+ break;
}
+ Packet packet;
+ packet.data = (uint8_t *)memalloc(size);
+ memcpy(packet.data, in_buffer, size);
+ packet.size = size;
+ packet.source = E.key;
+ incoming_packets.push_back(packet);
+ pkts--;
}
- return OK; // Sent to all but sender and excluded
+ }
+
+ // Remove disconnected peers.
+ for (const int &pid : to_remove) {
+ emit_signal(SNAME("peer_disconnected"), pid);
+ peers_map.erase(pid);
+ }
+}
+void WebSocketMultiplayerPeer::poll() {
+ if (connection_status == CONNECTION_DISCONNECTED) {
+ return;
+ }
+ if (is_server()) {
+ _poll_server();
} else {
- ERR_FAIL_COND_V(p_to == p_from, FAILED);
+ _poll_client();
+ }
+}
- Ref<WebSocketPeer> peer_to = get_peer(p_to);
- ERR_FAIL_COND_V(peer_to.is_null(), FAILED);
+MultiplayerPeer::ConnectionStatus WebSocketMultiplayerPeer::get_connection_status() const {
+ return connection_status;
+}
- return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer
- }
+Ref<WebSocketPeer> WebSocketMultiplayerPeer::get_peer(int p_id) const {
+ ERR_FAIL_COND_V(!peers_map.has(p_id), Ref<WebSocketPeer>());
+ return peers_map[p_id];
}
-void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id) {
- ERR_FAIL_COND(!p_peer.is_valid());
+void WebSocketMultiplayerPeer::set_supported_protocols(const Vector<String> &p_protocols) {
+ peer_config->set_supported_protocols(p_protocols);
+}
- const uint8_t *in_buffer;
- int size = 0;
- int data_size = 0;
+Vector<String> WebSocketMultiplayerPeer::get_supported_protocols() const {
+ return peer_config->get_supported_protocols();
+}
- Error err = p_peer->get_packet(&in_buffer, size);
+void WebSocketMultiplayerPeer::set_handshake_headers(const Vector<String> &p_headers) {
+ peer_config->set_handshake_headers(p_headers);
+}
- ERR_FAIL_COND(err != OK);
- ERR_FAIL_COND(size < PROTO_SIZE);
+Vector<String> WebSocketMultiplayerPeer::get_handshake_headers() const {
+ return peer_config->get_handshake_headers();
+}
- data_size = size - PROTO_SIZE;
+void WebSocketMultiplayerPeer::set_outbound_buffer_size(int p_buffer_size) {
+ peer_config->set_outbound_buffer_size(p_buffer_size);
+}
- uint8_t type = 0;
- uint32_t from = 0;
- int32_t to = 0;
- memcpy(&type, in_buffer, 1);
- memcpy(&from, &in_buffer[1], 4);
- memcpy(&to, &in_buffer[5], 4);
+int WebSocketMultiplayerPeer::get_outbound_buffer_size() const {
+ return peer_config->get_outbound_buffer_size();
+}
- if (is_server()) { // Server can resend
+void WebSocketMultiplayerPeer::set_inbound_buffer_size(int p_buffer_size) {
+ peer_config->set_inbound_buffer_size(p_buffer_size);
+}
- ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages
- ERR_FAIL_COND(from != p_peer_id); // Someone is cheating
+int WebSocketMultiplayerPeer::get_inbound_buffer_size() const {
+ return peer_config->get_inbound_buffer_size();
+}
- if (to == 1) { // This is for the server
+void WebSocketMultiplayerPeer::set_max_queued_packets(int p_max_queued_packets) {
+ peer_config->set_max_queued_packets(p_max_queued_packets);
+}
- _store_pkt(from, to, in_buffer, data_size);
+int WebSocketMultiplayerPeer::get_max_queued_packets() const {
+ return peer_config->get_max_queued_packets();
+}
- } else if (to == 0) {
- // Broadcast, for us too
- _store_pkt(from, to, in_buffer, data_size);
+float WebSocketMultiplayerPeer::get_handshake_timeout() const {
+ return handshake_timeout / 1000.0;
+}
- } else if (to < 0) {
- // All but one, for us if not excluded
- if (_peer_id != -(int32_t)p_peer_id) {
- _store_pkt(from, to, in_buffer, data_size);
- }
- }
- // Relay if needed (i.e. "to" includes a peer that is not the server)
- _server_relay(from, to, in_buffer, size);
+void WebSocketMultiplayerPeer::set_handshake_timeout(float p_timeout) {
+ ERR_FAIL_COND(p_timeout <= 0.0);
+ handshake_timeout = p_timeout * 1000;
+}
- } else {
- if (type == SYS_NONE) { // Payload message
+IPAddress WebSocketMultiplayerPeer::get_peer_address(int p_peer_id) const {
+ ERR_FAIL_COND_V(!peers_map.has(p_peer_id), IPAddress());
+ return peers_map[p_peer_id]->get_connected_host();
+}
- _store_pkt(from, to, in_buffer, data_size);
- return;
- }
+int WebSocketMultiplayerPeer::get_peer_port(int p_peer_id) const {
+ ERR_FAIL_COND_V(!peers_map.has(p_peer_id), 0);
+ return peers_map[p_peer_id]->get_connected_port();
+}
- // System message
- ERR_FAIL_COND(data_size < 4);
- int id = 0;
- memcpy(&id, &in_buffer[PROTO_SIZE], 4);
-
- switch (type) {
- case SYS_ADD: // Add peer
- _peer_map[id] = Ref<WebSocketPeer>();
- emit_signal(SNAME("peer_connected"), id);
- if (id == 1) { // We just connected to the server
- emit_signal(SNAME("connection_succeeded"));
- }
- break;
+void WebSocketMultiplayerPeer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
+ ERR_FAIL_COND(!peers_map.has(p_peer_id));
+ peers_map[p_peer_id]->close(p_code, p_reason);
+}
- case SYS_DEL: // Remove peer
- _peer_map.erase(id);
- emit_signal(SNAME("peer_disconnected"), id);
- break;
- case SYS_ID: // Hello, server assigned ID
- _peer_id = id;
- break;
- default:
- ERR_FAIL_MSG("Invalid multiplayer message.");
- break;
- }
- }
+void WebSocketMultiplayerPeer::close() {
+ _clear();
}
diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h
index 3259e78b3b..ebe013a7bf 100644
--- a/modules/websocket/websocket_multiplayer_peer.h
+++ b/modules/websocket/websocket_multiplayer_peer.h
@@ -32,6 +32,8 @@
#define WEBSOCKET_MULTIPLAYER_PEER_H
#include "core/error/error_list.h"
+#include "core/io/stream_peer_tls.h"
+#include "core/io/tcp_server.h"
#include "core/templates/list.h"
#include "scene/main/multiplayer_peer.h"
#include "websocket_peer.h"
@@ -40,9 +42,7 @@ class WebSocketMultiplayerPeer : public MultiplayerPeer {
GDCLASS(WebSocketMultiplayerPeer, MultiplayerPeer);
private:
- Vector<uint8_t> _make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size);
- void _store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size);
- Error _server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size);
+ Ref<WebSocketPeer> _create_peer();
protected:
enum {
@@ -56,30 +56,53 @@ protected:
struct Packet {
int source = 0;
- int destination = 0;
uint8_t *data = nullptr;
uint32_t size = 0;
};
- List<Packet> _incoming_packets;
- HashMap<int, Ref<WebSocketPeer>> _peer_map;
- Packet _current_packet;
+ struct PendingPeer {
+ uint64_t time = 0;
+ Ref<StreamPeerTCP> tcp;
+ Ref<StreamPeer> connection;
+ Ref<WebSocketPeer> ws;
+ };
+
+ uint64_t handshake_timeout = 3000;
+ Ref<WebSocketPeer> peer_config;
+ HashMap<int, PendingPeer> pending_peers;
+ Ref<TCPServer> tcp_server;
+ bool use_tls = false;
+ Ref<X509Certificate> tls_certificate;
+ Ref<CryptoKey> tls_key;
+
+ ConnectionStatus connection_status = CONNECTION_DISCONNECTED;
+
+ List<Packet> incoming_packets;
+ HashMap<int, Ref<WebSocketPeer>> peers_map;
+ Packet current_packet;
- bool _is_multiplayer = false;
- int _target_peer = 0;
- int _peer_id = 0;
+ int target_peer = 0;
+ int unique_id = 0;
static void _bind_methods();
- void _send_add(int32_t p_peer_id);
- void _send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id);
- void _send_del(int32_t p_peer_id);
+ void _poll_client();
+ void _poll_server();
+ void _clear();
public:
/* MultiplayerPeer */
- void set_target_peer(int p_target_peer) override;
- int get_packet_peer() const override;
- int get_unique_id() const override;
+ virtual void set_target_peer(int p_target_peer) override;
+ virtual int get_packet_peer() const override;
+ virtual int get_packet_channel() const override { return 0; }
+ virtual TransferMode get_packet_mode() const override { return TRANSFER_MODE_RELIABLE; }
+ virtual int get_unique_id() const override;
+ virtual bool is_server_relay_supported() const override { return true; }
+
+ virtual int get_max_packet_size() const override;
+ virtual bool is_server() const override;
+ virtual void poll() override;
+ virtual ConnectionStatus get_connection_status() const override;
/* PacketPeer */
virtual int get_available_packet_count() const override;
@@ -87,11 +110,33 @@ public:
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
/* WebSocketPeer */
- virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0;
- virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const = 0;
+ virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const;
- void _process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id);
- void _clear();
+ Error create_client(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate);
+ Error create_server(int p_port, IPAddress p_bind_ip, Ref<CryptoKey> p_tls_key, Ref<X509Certificate> p_tls_certificate);
+
+ void set_supported_protocols(const Vector<String> &p_protocols);
+ Vector<String> get_supported_protocols() const;
+
+ void set_handshake_headers(const Vector<String> &p_headers);
+ Vector<String> get_handshake_headers() const;
+
+ void set_outbound_buffer_size(int p_buffer_size);
+ int get_outbound_buffer_size() const;
+
+ void set_inbound_buffer_size(int p_buffer_size);
+ int get_inbound_buffer_size() const;
+
+ float get_handshake_timeout() const;
+ void set_handshake_timeout(float p_timeout);
+
+ IPAddress get_peer_address(int p_peer_id) const;
+ int get_peer_port(int p_peer_id) const;
+ void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "");
+ void close();
+
+ void set_max_queued_packets(int p_max_queued_packets);
+ int get_max_queued_packets() const;
WebSocketMultiplayerPeer();
~WebSocketMultiplayerPeer();
diff --git a/modules/websocket/websocket_peer.cpp b/modules/websocket/websocket_peer.cpp
index a0af9303b8..b46b20bef2 100644
--- a/modules/websocket/websocket_peer.cpp
+++ b/modules/websocket/websocket_peer.cpp
@@ -30,7 +30,7 @@
#include "websocket_peer.h"
-GDCINULL(WebSocketPeer);
+WebSocketPeer *(*WebSocketPeer::_create)() = nullptr;
WebSocketPeer::WebSocketPeer() {
}
@@ -39,16 +39,115 @@ WebSocketPeer::~WebSocketPeer() {
}
void WebSocketPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_write_mode"), &WebSocketPeer::get_write_mode);
- ClassDB::bind_method(D_METHOD("set_write_mode", "mode"), &WebSocketPeer::set_write_mode);
- ClassDB::bind_method(D_METHOD("is_connected_to_host"), &WebSocketPeer::is_connected_to_host);
+ ClassDB::bind_method(D_METHOD("connect_to_url", "url", "verify_tls", "trusted_tls_certificate"), &WebSocketPeer::connect_to_url, DEFVAL(true), DEFVAL(Ref<X509Certificate>()));
+ ClassDB::bind_method(D_METHOD("accept_stream", "stream"), &WebSocketPeer::accept_stream);
+ ClassDB::bind_method(D_METHOD("send", "message", "write_mode"), &WebSocketPeer::_send_bind, DEFVAL(WRITE_MODE_BINARY));
+ ClassDB::bind_method(D_METHOD("send_text", "message"), &WebSocketPeer::send_text);
ClassDB::bind_method(D_METHOD("was_string_packet"), &WebSocketPeer::was_string_packet);
+ ClassDB::bind_method(D_METHOD("poll"), &WebSocketPeer::poll);
ClassDB::bind_method(D_METHOD("close", "code", "reason"), &WebSocketPeer::close, DEFVAL(1000), DEFVAL(""));
ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketPeer::get_connected_host);
ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketPeer::get_connected_port);
+ ClassDB::bind_method(D_METHOD("get_selected_protocol"), &WebSocketPeer::get_selected_protocol);
+ ClassDB::bind_method(D_METHOD("get_requested_url"), &WebSocketPeer::get_requested_url);
ClassDB::bind_method(D_METHOD("set_no_delay", "enabled"), &WebSocketPeer::set_no_delay);
ClassDB::bind_method(D_METHOD("get_current_outbound_buffered_amount"), &WebSocketPeer::get_current_outbound_buffered_amount);
+ ClassDB::bind_method(D_METHOD("get_ready_state"), &WebSocketPeer::get_ready_state);
+ ClassDB::bind_method(D_METHOD("get_close_code"), &WebSocketPeer::get_close_code);
+ ClassDB::bind_method(D_METHOD("get_close_reason"), &WebSocketPeer::get_close_reason);
+
+ ClassDB::bind_method(D_METHOD("get_supported_protocols"), &WebSocketPeer::_get_supported_protocols);
+ ClassDB::bind_method(D_METHOD("set_supported_protocols", "protocols"), &WebSocketPeer::set_supported_protocols);
+ ClassDB::bind_method(D_METHOD("get_handshake_headers"), &WebSocketPeer::_get_handshake_headers);
+ ClassDB::bind_method(D_METHOD("set_handshake_headers", "protocols"), &WebSocketPeer::set_handshake_headers);
+
+ ClassDB::bind_method(D_METHOD("get_inbound_buffer_size"), &WebSocketPeer::get_inbound_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_inbound_buffer_size", "buffer_size"), &WebSocketPeer::set_inbound_buffer_size);
+ ClassDB::bind_method(D_METHOD("get_outbound_buffer_size"), &WebSocketPeer::get_outbound_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_outbound_buffer_size", "buffer_size"), &WebSocketPeer::set_outbound_buffer_size);
+
+ ClassDB::bind_method(D_METHOD("set_max_queued_packets", "buffer_size"), &WebSocketPeer::set_max_queued_packets);
+ ClassDB::bind_method(D_METHOD("get_max_queued_packets"), &WebSocketPeer::get_max_queued_packets);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "supported_protocols"), "set_supported_protocols", "get_supported_protocols");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "handshake_headers"), "set_handshake_headers", "get_handshake_headers");
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "inbound_buffer_size"), "set_inbound_buffer_size", "get_inbound_buffer_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "outbound_buffer_size"), "set_outbound_buffer_size", "get_outbound_buffer_size");
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_queued_packets"), "set_max_queued_packets", "get_max_queued_packets");
+
BIND_ENUM_CONSTANT(WRITE_MODE_TEXT);
BIND_ENUM_CONSTANT(WRITE_MODE_BINARY);
+
+ BIND_ENUM_CONSTANT(STATE_CONNECTING);
+ BIND_ENUM_CONSTANT(STATE_OPEN);
+ BIND_ENUM_CONSTANT(STATE_CLOSING);
+ BIND_ENUM_CONSTANT(STATE_CLOSED);
+}
+
+Error WebSocketPeer::_send_bind(const PackedByteArray &p_message, WriteMode p_mode) {
+ return send(p_message.ptr(), p_message.size(), p_mode);
+}
+
+Error WebSocketPeer::send_text(const String &p_text) {
+ const CharString cs = p_text.utf8();
+ return send((const uint8_t *)cs.ptr(), cs.length(), WRITE_MODE_TEXT);
+}
+
+void WebSocketPeer::set_supported_protocols(const Vector<String> &p_protocols) {
+ // Strip edges from protocols.
+ supported_protocols.resize(p_protocols.size());
+ for (int i = 0; i < p_protocols.size(); i++) {
+ supported_protocols.write[i] = p_protocols[i].strip_edges();
+ }
+}
+
+const Vector<String> WebSocketPeer::get_supported_protocols() const {
+ return supported_protocols;
+}
+
+Vector<String> WebSocketPeer::_get_supported_protocols() const {
+ Vector<String> out;
+ out.append_array(supported_protocols);
+ return out;
+}
+
+void WebSocketPeer::set_handshake_headers(const Vector<String> &p_headers) {
+ handshake_headers = p_headers;
+}
+
+const Vector<String> WebSocketPeer::get_handshake_headers() const {
+ return handshake_headers;
+}
+
+Vector<String> WebSocketPeer::_get_handshake_headers() const {
+ Vector<String> out;
+ out.append_array(handshake_headers);
+ return out;
+}
+
+void WebSocketPeer::set_outbound_buffer_size(int p_buffer_size) {
+ outbound_buffer_size = p_buffer_size;
+}
+
+int WebSocketPeer::get_outbound_buffer_size() const {
+ return outbound_buffer_size;
+}
+
+void WebSocketPeer::set_inbound_buffer_size(int p_buffer_size) {
+ inbound_buffer_size = p_buffer_size;
+}
+
+int WebSocketPeer::get_inbound_buffer_size() const {
+ return inbound_buffer_size;
+}
+
+void WebSocketPeer::set_max_queued_packets(int p_max_queued_packets) {
+ max_queued_packets = p_max_queued_packets;
+}
+
+int WebSocketPeer::get_max_queued_packets() const {
+ return max_queued_packets;
}
diff --git a/modules/websocket/websocket_peer.h b/modules/websocket/websocket_peer.h
index 22099f7258..db969dd08e 100644
--- a/modules/websocket/websocket_peer.h
+++ b/modules/websocket/websocket_peer.h
@@ -31,40 +31,97 @@
#ifndef WEBSOCKET_PEER_H
#define WEBSOCKET_PEER_H
+#include "core/crypto/crypto.h"
#include "core/error/error_list.h"
#include "core/io/packet_peer.h"
-#include "websocket_macros.h"
class WebSocketPeer : public PacketPeer {
GDCLASS(WebSocketPeer, PacketPeer);
- GDCICLASS(WebSocketPeer);
public:
+ enum State {
+ STATE_CONNECTING,
+ STATE_OPEN,
+ STATE_CLOSING,
+ STATE_CLOSED
+ };
+
enum WriteMode {
WRITE_MODE_TEXT,
WRITE_MODE_BINARY,
};
+ enum {
+ DEFAULT_BUFFER_SIZE = 65535,
+ };
+
+private:
+ virtual Error _send_bind(const PackedByteArray &p_data, WriteMode p_mode = WRITE_MODE_BINARY);
+
protected:
+ static WebSocketPeer *(*_create)();
+
static void _bind_methods();
+ Vector<String> supported_protocols;
+ Vector<String> handshake_headers;
+
+ Vector<String> _get_supported_protocols() const;
+ Vector<String> _get_handshake_headers() const;
+
+ int outbound_buffer_size = DEFAULT_BUFFER_SIZE;
+ int inbound_buffer_size = DEFAULT_BUFFER_SIZE;
+ int max_queued_packets = 2048;
+
public:
- virtual WriteMode get_write_mode() const = 0;
- virtual void set_write_mode(WriteMode p_mode) = 0;
+ static WebSocketPeer *create() {
+ if (!_create) {
+ return nullptr;
+ }
+ return _create();
+ }
+ virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) { return ERR_UNAVAILABLE; };
+ virtual Error accept_stream(Ref<StreamPeer> p_stream) = 0;
+
+ virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) = 0;
virtual void close(int p_code = 1000, String p_reason = "") = 0;
- virtual bool is_connected_to_host() const = 0;
virtual IPAddress get_connected_host() const = 0;
virtual uint16_t get_connected_port() const = 0;
virtual bool was_string_packet() const = 0;
virtual void set_no_delay(bool p_enabled) = 0;
virtual int get_current_outbound_buffered_amount() const = 0;
+ virtual String get_selected_protocol() const = 0;
+ virtual String get_requested_url() const = 0;
+
+ virtual void poll() = 0;
+ virtual State get_ready_state() const = 0;
+ virtual int get_close_code() const = 0;
+ virtual String get_close_reason() const = 0;
+
+ Error send_text(const String &p_text);
+
+ void set_supported_protocols(const Vector<String> &p_protocols);
+ const Vector<String> get_supported_protocols() const;
+
+ void set_handshake_headers(const Vector<String> &p_headers);
+ const Vector<String> get_handshake_headers() const;
+
+ void set_outbound_buffer_size(int p_buffer_size);
+ int get_outbound_buffer_size() const;
+
+ void set_inbound_buffer_size(int p_buffer_size);
+ int get_inbound_buffer_size() const;
+
+ void set_max_queued_packets(int p_max_queued_packets);
+ int get_max_queued_packets() const;
WebSocketPeer();
~WebSocketPeer();
};
VARIANT_ENUM_CAST(WebSocketPeer::WriteMode);
+VARIANT_ENUM_CAST(WebSocketPeer::State);
#endif // WEBSOCKET_PEER_H
diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp
deleted file mode 100644
index 25a6e420fc..0000000000
--- a/modules/websocket/websocket_server.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-/*************************************************************************/
-/* websocket_server.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 "websocket_server.h"
-
-GDCINULL(WebSocketServer);
-
-WebSocketServer::WebSocketServer() {
- _peer_id = 1;
- bind_ip = IPAddress("*");
-}
-
-WebSocketServer::~WebSocketServer() {
-}
-
-void WebSocketServer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("is_listening"), &WebSocketServer::is_listening);
- ClassDB::bind_method(D_METHOD("set_extra_headers", "headers"), &WebSocketServer::set_extra_headers, DEFVAL(Vector<String>()));
- ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(Vector<String>()), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("stop"), &WebSocketServer::stop);
- ClassDB::bind_method(D_METHOD("has_peer", "id"), &WebSocketServer::has_peer);
- ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketServer::get_peer_address);
- ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketServer::get_peer_port);
- ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "code", "reason"), &WebSocketServer::disconnect_peer, DEFVAL(1000), DEFVAL(""));
-
- ClassDB::bind_method(D_METHOD("get_bind_ip"), &WebSocketServer::get_bind_ip);
- ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &WebSocketServer::set_bind_ip);
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "bind_ip"), "set_bind_ip", "get_bind_ip");
-
- ClassDB::bind_method(D_METHOD("get_private_key"), &WebSocketServer::get_private_key);
- ClassDB::bind_method(D_METHOD("set_private_key", "key"), &WebSocketServer::set_private_key);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "private_key", PROPERTY_HINT_RESOURCE_TYPE, "CryptoKey", PROPERTY_USAGE_NONE), "set_private_key", "get_private_key");
-
- ClassDB::bind_method(D_METHOD("get_tls_certificate"), &WebSocketServer::get_tls_certificate);
- ClassDB::bind_method(D_METHOD("set_tls_certificate", "cert"), &WebSocketServer::set_tls_certificate);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_tls_certificate", "get_tls_certificate");
-
- ClassDB::bind_method(D_METHOD("get_ca_chain"), &WebSocketServer::get_ca_chain);
- ClassDB::bind_method(D_METHOD("set_ca_chain", "ca_chain"), &WebSocketServer::set_ca_chain);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ca_chain", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_ca_chain", "get_ca_chain");
-
- ClassDB::bind_method(D_METHOD("get_handshake_timeout"), &WebSocketServer::get_handshake_timeout);
- ClassDB::bind_method(D_METHOD("set_handshake_timeout", "timeout"), &WebSocketServer::set_handshake_timeout);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "handshake_timeout"), "set_handshake_timeout", "get_handshake_timeout");
-
- ADD_SIGNAL(MethodInfo("client_close_request", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason")));
- ADD_SIGNAL(MethodInfo("client_disconnected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::BOOL, "was_clean_close")));
- ADD_SIGNAL(MethodInfo("client_connected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::STRING, "protocol"), PropertyInfo(Variant::STRING, "resource_name")));
- ADD_SIGNAL(MethodInfo("data_received", PropertyInfo(Variant::INT, "id")));
-}
-
-IPAddress WebSocketServer::get_bind_ip() const {
- return bind_ip;
-}
-
-void WebSocketServer::set_bind_ip(const IPAddress &p_bind_ip) {
- ERR_FAIL_COND(is_listening());
- ERR_FAIL_COND(!p_bind_ip.is_valid() && !p_bind_ip.is_wildcard());
- bind_ip = p_bind_ip;
-}
-
-Ref<CryptoKey> WebSocketServer::get_private_key() const {
- return private_key;
-}
-
-void WebSocketServer::set_private_key(Ref<CryptoKey> p_key) {
- ERR_FAIL_COND(is_listening());
- private_key = p_key;
-}
-
-Ref<X509Certificate> WebSocketServer::get_tls_certificate() const {
- return tls_cert;
-}
-
-void WebSocketServer::set_tls_certificate(Ref<X509Certificate> p_cert) {
- ERR_FAIL_COND(is_listening());
- tls_cert = p_cert;
-}
-
-Ref<X509Certificate> WebSocketServer::get_ca_chain() const {
- return ca_chain;
-}
-
-void WebSocketServer::set_ca_chain(Ref<X509Certificate> p_ca_chain) {
- ERR_FAIL_COND(is_listening());
- ca_chain = p_ca_chain;
-}
-
-float WebSocketServer::get_handshake_timeout() const {
- return handshake_timeout / 1000.0;
-}
-
-void WebSocketServer::set_handshake_timeout(float p_timeout) {
- ERR_FAIL_COND(p_timeout <= 0.0);
- handshake_timeout = p_timeout * 1000;
-}
-
-MultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const {
- if (is_listening()) {
- return CONNECTION_CONNECTED;
- }
-
- return CONNECTION_DISCONNECTED;
-}
-
-bool WebSocketServer::is_server() const {
- return true;
-}
-
-void WebSocketServer::_on_peer_packet(int32_t p_peer_id) {
- if (_is_multiplayer) {
- _process_multiplayer(get_peer(p_peer_id), p_peer_id);
- } else {
- emit_signal(SNAME("data_received"), p_peer_id);
- }
-}
-
-void WebSocketServer::_on_connect(int32_t p_peer_id, String p_protocol, String p_resource_name) {
- if (_is_multiplayer) {
- // Send add to clients
- _send_add(p_peer_id);
- emit_signal(SNAME("peer_connected"), p_peer_id);
- } else {
- emit_signal(SNAME("client_connected"), p_peer_id, p_protocol, p_resource_name);
- }
-}
-
-void WebSocketServer::_on_disconnect(int32_t p_peer_id, bool p_was_clean) {
- if (_is_multiplayer) {
- // Send delete to clients
- _send_del(p_peer_id);
- emit_signal(SNAME("peer_disconnected"), p_peer_id);
- } else {
- emit_signal(SNAME("client_disconnected"), p_peer_id, p_was_clean);
- }
-}
-
-void WebSocketServer::_on_close_request(int32_t p_peer_id, int p_code, String p_reason) {
- emit_signal(SNAME("client_close_request"), p_peer_id, p_code, p_reason);
-}
diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h
deleted file mode 100644
index de23ee884d..0000000000
--- a/modules/websocket/websocket_server.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*************************************************************************/
-/* websocket_server.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 WEBSOCKET_SERVER_H
-#define WEBSOCKET_SERVER_H
-
-#include "core/crypto/crypto.h"
-#include "core/object/ref_counted.h"
-#include "websocket_multiplayer_peer.h"
-#include "websocket_peer.h"
-
-class WebSocketServer : public WebSocketMultiplayerPeer {
- GDCLASS(WebSocketServer, WebSocketMultiplayerPeer);
- GDCICLASS(WebSocketServer);
-
- IPAddress bind_ip;
-
-protected:
- static void _bind_methods();
-
- Ref<CryptoKey> private_key;
- Ref<X509Certificate> tls_cert;
- Ref<X509Certificate> ca_chain;
- uint32_t handshake_timeout = 3000;
-
-public:
- virtual void set_extra_headers(const Vector<String> &p_headers) = 0;
- virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0;
- virtual void stop() = 0;
- virtual bool is_listening() const = 0;
- virtual bool has_peer(int p_id) const = 0;
- virtual bool is_server() const override;
- ConnectionStatus get_connection_status() const override;
-
- virtual IPAddress get_peer_address(int p_peer_id) const = 0;
- virtual int get_peer_port(int p_peer_id) const = 0;
- virtual void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") = 0;
-
- void _on_peer_packet(int32_t p_peer_id);
- void _on_connect(int32_t p_peer_id, String p_protocol, String p_resource_name);
- void _on_disconnect(int32_t p_peer_id, bool p_was_clean);
- void _on_close_request(int32_t p_peer_id, int p_code, String p_reason);
-
- IPAddress get_bind_ip() const;
- void set_bind_ip(const IPAddress &p_bind_ip);
-
- Ref<CryptoKey> get_private_key() const;
- void set_private_key(Ref<CryptoKey> p_key);
-
- Ref<X509Certificate> get_tls_certificate() const;
- void set_tls_certificate(Ref<X509Certificate> p_cert);
-
- Ref<X509Certificate> get_ca_chain() const;
- void set_ca_chain(Ref<X509Certificate> p_ca_chain);
-
- float get_handshake_timeout() const;
- void set_handshake_timeout(float p_timeout);
-
- WebSocketServer();
- ~WebSocketServer();
-};
-
-#endif // WEBSOCKET_SERVER_H
diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp
deleted file mode 100644
index 50ef53e267..0000000000
--- a/modules/websocket/wsl_client.cpp
+++ /dev/null
@@ -1,407 +0,0 @@
-/*************************************************************************/
-/* wsl_client.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. */
-/*************************************************************************/
-
-#ifndef WEB_ENABLED
-
-#include "wsl_client.h"
-#include "core/config/project_settings.h"
-#include "core/io/ip.h"
-
-void WSLClient::_do_handshake() {
- if (_requested < _request.size() - 1) {
- int sent = 0;
- Error err = _connection->put_partial_data(((const uint8_t *)_request.get_data() + _requested), _request.size() - _requested - 1, sent);
- // Sending handshake failed
- if (err != OK) {
- disconnect_from_host();
- _on_error();
- return;
- }
- _requested += sent;
-
- } else {
- int read = 0;
- while (true) {
- if (_resp_pos >= WSL_MAX_HEADER_SIZE) {
- // Header is too big
- disconnect_from_host();
- _on_error();
- ERR_FAIL_MSG("Response headers too big.");
- }
- Error err = _connection->get_partial_data(&_resp_buf[_resp_pos], 1, read);
- if (err == ERR_FILE_EOF) {
- // We got a disconnect.
- disconnect_from_host();
- _on_error();
- return;
- } else if (err != OK) {
- // Got some error.
- disconnect_from_host();
- _on_error();
- return;
- } else if (read != 1) {
- // Busy, wait next poll.
- break;
- }
- // Check "\r\n\r\n" header terminator
- char *r = (char *)_resp_buf;
- int l = _resp_pos;
- if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
- r[l - 3] = '\0';
- String protocol;
- // Response is over, verify headers and create peer.
- if (!_verify_headers(protocol)) {
- disconnect_from_host();
- _on_error();
- ERR_FAIL_MSG("Invalid response headers.");
- }
- // Create peer.
- WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
- data->obj = this;
- data->conn = _connection;
- data->tcp = _tcp;
- data->is_server = false;
- data->id = 1;
- _peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
- _peer->set_no_delay(true);
- _status = CONNECTION_CONNECTED;
- _on_connect(protocol);
- break;
- }
- _resp_pos += 1;
- }
- }
-}
-
-bool WSLClient::_verify_headers(String &r_protocol) {
- String s = (char *)_resp_buf;
- Vector<String> psa = s.split("\r\n");
- int len = psa.size();
- ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4.");
-
- Vector<String> req = psa[0].split(" ", false);
- ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'.");
-
- // Wrong protocol
- ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'.");
- ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'.");
-
- HashMap<String, String> headers;
- for (int i = 1; i < len; i++) {
- Vector<String> header = psa[i].split(":", false, 1);
- ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + ".");
- String name = header[0].to_lower();
- String value = header[1].strip_edges();
- if (headers.has(name)) {
- headers[name] += "," + value;
- } else {
- headers[name] = value;
- }
- }
-
-#define WSL_CHECK(NAME, VALUE) \
- ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
- "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
-#define WSL_CHECK_NC(NAME, VALUE) \
- ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \
- "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
- WSL_CHECK("connection", "upgrade");
- WSL_CHECK("upgrade", "websocket");
- WSL_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
-#undef WSL_CHECK_NC
-#undef WSL_CHECK
- if (_protocols.size() == 0) {
- // We didn't request a custom protocol
- ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]);
- } else {
- // We requested at least one custom protocol but didn't receive one
- ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none.");
- // Check received sub-protocol was one of those requested.
- r_protocol = headers["sec-websocket-protocol"];
- bool valid = false;
- for (int i = 0; i < _protocols.size(); i++) {
- if (_protocols[i] != r_protocol) {
- continue;
- }
- valid = true;
- break;
- }
- if (!valid) {
- ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + r_protocol);
- return false;
- }
- }
- return true;
-}
-
-Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
- ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE);
- ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER);
-
- _peer = Ref<WSLPeer>(memnew(WSLPeer));
-
- if (p_host.is_valid_ip_address()) {
- _ip_candidates.push_back(IPAddress(p_host));
- } else {
- // Queue hostname for resolution.
- _resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host);
- ERR_FAIL_COND_V(_resolver_id == IP::RESOLVER_INVALID_ID, ERR_INVALID_PARAMETER);
- // Check if it was found in cache.
- IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id);
- if (ip_status == IP::RESOLVER_STATUS_DONE) {
- _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id);
- IP::get_singleton()->erase_resolve_item(_resolver_id);
- _resolver_id = IP::RESOLVER_INVALID_ID;
- }
- }
-
- // We assume OK while hostname resolution is pending.
- Error err = _resolver_id != IP::RESOLVER_INVALID_ID ? OK : FAILED;
- while (_ip_candidates.size()) {
- err = _tcp->connect_to_host(_ip_candidates.pop_front(), p_port);
- if (err == OK) {
- break;
- }
- }
- if (err != OK) {
- _tcp->disconnect_from_host();
- _on_error();
- return err;
- }
- _connection = _tcp;
- _use_tls = p_tls;
- _host = p_host;
- _port = p_port;
- // Strip edges from protocols.
- _protocols.resize(p_protocols.size());
- String *pw = _protocols.ptrw();
- for (int i = 0; i < p_protocols.size(); i++) {
- pw[i] = p_protocols[i].strip_edges();
- }
-
- _key = WSLPeer::generate_key();
- String request = "GET " + p_path + " HTTP/1.1\r\n";
- String port = "";
- if ((p_port != 80 && !p_tls) || (p_port != 443 && p_tls)) {
- port = ":" + itos(p_port);
- }
- request += "Host: " + p_host + port + "\r\n";
- request += "Upgrade: websocket\r\n";
- request += "Connection: Upgrade\r\n";
- request += "Sec-WebSocket-Key: " + _key + "\r\n";
- request += "Sec-WebSocket-Version: 13\r\n";
- if (p_protocols.size() > 0) {
- request += "Sec-WebSocket-Protocol: ";
- for (int i = 0; i < p_protocols.size(); i++) {
- if (i != 0) {
- request += ",";
- }
- request += p_protocols[i];
- }
- request += "\r\n";
- }
- for (int i = 0; i < p_custom_headers.size(); i++) {
- request += p_custom_headers[i] + "\r\n";
- }
- request += "\r\n";
- _request = request.utf8();
- _status = CONNECTION_CONNECTING;
-
- return OK;
-}
-
-int WSLClient::get_max_packet_size() const {
- return (1 << _out_buf_size) - PROTO_SIZE;
-}
-
-void WSLClient::poll() {
- if (_resolver_id != IP::RESOLVER_INVALID_ID) {
- IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(_resolver_id);
- if (ip_status == IP::RESOLVER_STATUS_WAITING) {
- return;
- }
- // Anything else is either a candidate or a failure.
- Error err = FAILED;
- if (ip_status == IP::RESOLVER_STATUS_DONE) {
- _ip_candidates = IP::get_singleton()->get_resolve_item_addresses(_resolver_id);
- while (_ip_candidates.size()) {
- err = _tcp->connect_to_host(_ip_candidates.pop_front(), _port);
- if (err == OK) {
- break;
- }
- }
- }
- IP::get_singleton()->erase_resolve_item(_resolver_id);
- _resolver_id = IP::RESOLVER_INVALID_ID;
- if (err != OK) {
- disconnect_from_host();
- _on_error();
- return;
- }
- }
- if (_peer->is_connected_to_host()) {
- _peer->poll();
- if (!_peer->is_connected_to_host()) {
- disconnect_from_host();
- _on_disconnect(_peer->close_code != -1);
- }
- return;
- }
-
- if (_connection.is_null()) {
- return; // Not connected.
- }
-
- _tcp->poll();
- switch (_tcp->get_status()) {
- case StreamPeerTCP::STATUS_NONE:
- // Clean close
- disconnect_from_host();
- _on_error();
- break;
- case StreamPeerTCP::STATUS_CONNECTED: {
- _ip_candidates.clear();
- Ref<StreamPeerTLS> tls;
- if (_use_tls) {
- if (_connection == _tcp) {
- // Start SSL handshake
- tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
- ERR_FAIL_COND_MSG(tls.is_null(), "SSL is not available in this build.");
- tls->set_blocking_handshake_enabled(false);
- if (tls->connect_to_stream(_tcp, verify_tls, _host, tls_cert) != OK) {
- disconnect_from_host();
- _on_error();
- return;
- }
- _connection = tls;
- } else {
- tls = static_cast<Ref<StreamPeerTLS>>(_connection);
- ERR_FAIL_COND(tls.is_null()); // Bug?
- tls->poll();
- }
- if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
- return; // Need more polling.
- } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
- disconnect_from_host();
- _on_error();
- return; // Error.
- }
- }
- // Do websocket handshake.
- _do_handshake();
- } break;
- case StreamPeerTCP::STATUS_ERROR:
- while (_ip_candidates.size() > 0) {
- _tcp->disconnect_from_host();
- if (_tcp->connect_to_host(_ip_candidates.pop_front(), _port) == OK) {
- return;
- }
- }
- disconnect_from_host();
- _on_error();
- break;
- case StreamPeerTCP::STATUS_CONNECTING:
- break; // Wait for connection
- }
-}
-
-Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const {
- ERR_FAIL_COND_V(p_peer_id != 1, nullptr);
-
- return _peer;
-}
-
-MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
- // This is surprising, but keeps the current behaviour to allow clean close requests.
- // TODO Refactor WebSocket and split Client/Server/Multiplayer like done in other peers.
- if (_peer->is_connected_to_host()) {
- return CONNECTION_CONNECTED;
- }
- return _status;
-}
-
-void WSLClient::disconnect_from_host(int p_code, String p_reason) {
- _peer->close(p_code, p_reason);
- _connection = Ref<StreamPeer>(nullptr);
- _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP));
- _status = CONNECTION_DISCONNECTED;
-
- _key = "";
- _host = "";
- _protocols.clear();
- _use_tls = false;
-
- _request = "";
- _requested = 0;
-
- memset(_resp_buf, 0, sizeof(_resp_buf));
- _resp_pos = 0;
-
- if (_resolver_id != IP::RESOLVER_INVALID_ID) {
- IP::get_singleton()->erase_resolve_item(_resolver_id);
- _resolver_id = IP::RESOLVER_INVALID_ID;
- }
-
- _ip_candidates.clear();
-}
-
-IPAddress WSLClient::get_connected_host() const {
- ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IPAddress());
- return _peer->get_connected_host();
-}
-
-uint16_t WSLClient::get_connected_port() const {
- ERR_FAIL_COND_V(!_peer->is_connected_to_host(), 0);
- return _peer->get_connected_port();
-}
-
-Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
- ERR_FAIL_COND_V_MSG(_connection.is_valid(), FAILED, "Buffers sizes can only be set before listening or connecting.");
-
- _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
- _in_pkt_size = nearest_shift(p_in_packets - 1);
- _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
- _out_pkt_size = nearest_shift(p_out_packets - 1);
- return OK;
-}
-
-WSLClient::WSLClient() {
- _peer.instantiate();
- _tcp.instantiate();
- disconnect_from_host();
-}
-
-WSLClient::~WSLClient() {
- _peer->close_now();
- _peer->invalidate();
- disconnect_from_host();
-}
-
-#endif // WEB_ENABLED
diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp
index 97bd87a526..84e022182e 100644
--- a/modules/websocket/wsl_peer.cpp
+++ b/modules/websocket/wsl_peer.cpp
@@ -32,71 +32,537 @@
#include "wsl_peer.h"
-#include "wsl_client.h"
-#include "wsl_server.h"
+#include "wsl_peer.h"
-#include "core/crypto/crypto_core.h"
-#include "core/math/random_number_generator.h"
-#include "core/os/os.h"
+#include "core/io/stream_peer_tls.h"
-String WSLPeer::generate_key() {
- // Random key
- RandomNumberGenerator rng;
- rng.set_seed(OS::get_singleton()->get_unix_time());
- Vector<uint8_t> bkey;
- int len = 16; // 16 bytes, as per RFC
- bkey.resize(len);
- uint8_t *w = bkey.ptrw();
- for (int i = 0; i < len; i++) {
- w[i] = (uint8_t)rng.randi_range(0, 255);
+CryptoCore::RandomGenerator *WSLPeer::_static_rng = nullptr;
+
+void WSLPeer::initialize() {
+ WebSocketPeer::_create = WSLPeer::_create;
+ _static_rng = memnew(CryptoCore::RandomGenerator);
+ _static_rng->init();
+}
+
+void WSLPeer::deinitialize() {
+ if (_static_rng) {
+ memdelete(_static_rng);
+ _static_rng = nullptr;
}
- return CryptoCore::b64_encode_str(&w[0], len);
}
-String WSLPeer::compute_key_response(String p_key) {
- String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC
- Vector<uint8_t> sha = key.sha1_buffer();
- return CryptoCore::b64_encode_str(sha.ptr(), sha.size());
+///
+/// Resolver
+///
+void WSLPeer::Resolver::start(const String &p_host, int p_port) {
+ stop();
+
+ port = p_port;
+ if (p_host.is_valid_ip_address()) {
+ ip_candidates.push_back(IPAddress(p_host));
+ } else {
+ // Queue hostname for resolution.
+ resolver_id = IP::get_singleton()->resolve_hostname_queue_item(p_host);
+ ERR_FAIL_COND(resolver_id == IP::RESOLVER_INVALID_ID);
+ // Check if it was found in cache.
+ IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id);
+ if (ip_status == IP::RESOLVER_STATUS_DONE) {
+ ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id);
+ IP::get_singleton()->erase_resolve_item(resolver_id);
+ resolver_id = IP::RESOLVER_INVALID_ID;
+ }
+ }
}
-void WSLPeer::_wsl_destroy(struct PeerData **p_data) {
- if (!p_data || !(*p_data)) {
- return;
+void WSLPeer::Resolver::stop() {
+ if (resolver_id != IP::RESOLVER_INVALID_ID) {
+ IP::get_singleton()->erase_resolve_item(resolver_id);
+ resolver_id = IP::RESOLVER_INVALID_ID;
+ }
+ port = 0;
+}
+
+void WSLPeer::Resolver::try_next_candidate(Ref<StreamPeerTCP> &p_tcp) {
+ // Check if we still need resolving.
+ if (resolver_id != IP::RESOLVER_INVALID_ID) {
+ IP::ResolverStatus ip_status = IP::get_singleton()->get_resolve_item_status(resolver_id);
+ if (ip_status == IP::RESOLVER_STATUS_WAITING) {
+ return;
+ }
+ if (ip_status == IP::RESOLVER_STATUS_DONE) {
+ ip_candidates = IP::get_singleton()->get_resolve_item_addresses(resolver_id);
+ }
+ IP::get_singleton()->erase_resolve_item(resolver_id);
+ resolver_id = IP::RESOLVER_INVALID_ID;
}
- struct PeerData *data = *p_data;
- if (data->polling) {
- data->destroy = true;
+
+ // Try the current candidate if we have one.
+ if (p_tcp->get_status() != StreamPeerTCP::STATUS_NONE) {
+ p_tcp->poll();
+ StreamPeerTCP::Status status = p_tcp->get_status();
+ if (status == StreamPeerTCP::STATUS_CONNECTED) {
+ p_tcp->set_no_delay(true);
+ ip_candidates.clear();
+ return;
+ } else if (status == StreamPeerTCP::STATUS_CONNECTING) {
+ return; // Keep connecting.
+ } else {
+ p_tcp->disconnect_from_host();
+ }
+ }
+
+ // Keep trying next candidate.
+ while (ip_candidates.size()) {
+ Error err = p_tcp->connect_to_host(ip_candidates.pop_front(), port);
+ if (err == OK) {
+ return;
+ } else {
+ p_tcp->disconnect_from_host();
+ }
+ }
+}
+
+///
+/// Server functions
+///
+Error WSLPeer::accept_stream(Ref<StreamPeer> p_stream) {
+ ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(p_stream.is_null(), ERR_INVALID_PARAMETER);
+
+ _clear();
+
+ if (p_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static())) {
+ tcp = p_stream;
+ connection = p_stream;
+ use_tls = false;
+ } else if (p_stream->is_class_ptr(StreamPeerTLS::get_class_ptr_static())) {
+ Ref<StreamPeer> base_stream = static_cast<Ref<StreamPeerTLS>>(p_stream)->get_stream();
+ ERR_FAIL_COND_V(base_stream.is_null() || !base_stream->is_class_ptr(StreamPeerTCP::get_class_ptr_static()), ERR_INVALID_PARAMETER);
+ tcp = static_cast<Ref<StreamPeerTCP>>(base_stream);
+ connection = p_stream;
+ use_tls = true;
+ }
+ ERR_FAIL_COND_V(connection.is_null() || tcp.is_null(), ERR_INVALID_PARAMETER);
+ is_server = true;
+ ready_state = STATE_CONNECTING;
+ handshake_buffer->resize(WSL_MAX_HEADER_SIZE);
+ handshake_buffer->seek(0);
+ return OK;
+}
+
+bool WSLPeer::_parse_client_request() {
+ Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n");
+ int len = psa.size();
+ ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
+
+ Vector<String> req = psa[0].split(" ", false);
+ ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
+
+ // Wrong protocol
+ ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
+
+ HashMap<String, String> headers;
+ for (int i = 1; i < len; i++) {
+ Vector<String> header = psa[i].split(":", false, 1);
+ ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
+ String name = header[0].to_lower();
+ String value = header[1].strip_edges();
+ if (headers.has(name)) {
+ headers[name] += "," + value;
+ } else {
+ headers[name] = value;
+ }
+ }
+ requested_host = headers.has("host") ? headers.get("host") : "";
+ requested_url = (use_tls ? "wss://" : "ws://") + requested_host + req[1];
+#define WSL_CHECK(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+#define WSL_CHECK_EX(NAME) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
+ WSL_CHECK("upgrade", "websocket");
+ WSL_CHECK("sec-websocket-version", "13");
+ WSL_CHECK_EX("sec-websocket-key");
+ WSL_CHECK_EX("connection");
+#undef WSL_CHECK_EX
+#undef WSL_CHECK
+ session_key = headers["sec-websocket-key"];
+ if (headers.has("sec-websocket-protocol")) {
+ Vector<String> protos = headers["sec-websocket-protocol"].split(",");
+ for (int i = 0; i < protos.size(); i++) {
+ String proto = protos[i].strip_edges();
+ // Check if we have the given protocol
+ for (int j = 0; j < supported_protocols.size(); j++) {
+ if (proto != supported_protocols[j]) {
+ continue;
+ }
+ selected_protocol = proto;
+ break;
+ }
+ // Found a protocol
+ if (!selected_protocol.is_empty()) {
+ break;
+ }
+ }
+ if (selected_protocol.is_empty()) { // Invalid protocol(s) requested
+ return false;
+ }
+ } else if (supported_protocols.size() > 0) { // No protocol requested, but we need one
+ return false;
+ }
+ return true;
+}
+
+Error WSLPeer::_do_server_handshake() {
+ if (use_tls) {
+ Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection);
+ if (tls.is_null()) {
+ ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake.");
+ close(-1);
+ return FAILED;
+ }
+ tls->poll();
+ if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
+ return OK; // Pending handshake
+ } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
+ print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status()));
+ close(-1);
+ return FAILED;
+ }
+ }
+
+ if (pending_request) {
+ int read = 0;
+ while (true) {
+ ERR_FAIL_COND_V_MSG(handshake_buffer->get_available_bytes() < 1, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big.");
+ int pos = handshake_buffer->get_position();
+ uint8_t byte;
+ Error err = connection->get_partial_data(&byte, 1, read);
+ if (err != OK) { // Got an error
+ print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err));
+ close(-1);
+ return FAILED;
+ } else if (read != 1) { // Busy, wait next poll
+ return OK;
+ }
+ handshake_buffer->put_u8(byte);
+ const char *r = (const char *)handshake_buffer->get_data_array().ptr();
+ int l = pos;
+ if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
+ if (!_parse_client_request()) {
+ close(-1);
+ return FAILED;
+ }
+ String s = "HTTP/1.1 101 Switching Protocols\r\n";
+ s += "Upgrade: websocket\r\n";
+ s += "Connection: Upgrade\r\n";
+ s += "Sec-WebSocket-Accept: " + _compute_key_response(session_key) + "\r\n";
+ if (!selected_protocol.is_empty()) {
+ s += "Sec-WebSocket-Protocol: " + selected_protocol + "\r\n";
+ }
+ for (int i = 0; i < handshake_headers.size(); i++) {
+ s += handshake_headers[i] + "\r\n";
+ }
+ s += "\r\n";
+ CharString cs = s.utf8();
+ handshake_buffer->clear();
+ handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length());
+ handshake_buffer->seek(0);
+ pending_request = false;
+ break;
+ }
+ }
+ }
+
+ if (pending_request) { // Still pending.
+ return OK;
+ }
+
+ int left = handshake_buffer->get_available_bytes();
+ if (left) {
+ Vector<uint8_t> data = handshake_buffer->get_data_array();
+ int pos = handshake_buffer->get_position();
+ int sent = 0;
+ Error err = connection->put_partial_data(data.ptr() + pos, left, sent);
+ if (err != OK) {
+ print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err));
+ close(-1);
+ return err;
+ }
+ handshake_buffer->seek(pos + sent);
+ left -= sent;
+ if (left == 0) {
+ resolver.stop();
+ // Response sent, initialize wslay context.
+ wslay_event_context_server_init(&wsl_ctx, &_wsl_callbacks, this);
+ wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size);
+ in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
+ packet_buffer.resize(inbound_buffer_size);
+ ready_state = STATE_OPEN;
+ }
+ }
+
+ return OK;
+}
+
+///
+/// Client functions
+///
+void WSLPeer::_do_client_handshake() {
+ ERR_FAIL_COND(tcp.is_null());
+
+ // Try to connect to candidates.
+ if (resolver.has_more_candidates()) {
+ resolver.try_next_candidate(tcp);
+ if (resolver.has_more_candidates()) {
+ return; // Still pending.
+ }
+ }
+
+ tcp->poll();
+ if (tcp->get_status() == StreamPeerTCP::STATUS_CONNECTING) {
+ return; // Keep connecting.
+ } else if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
+ close(-1); // Failed to connect.
return;
}
- wslay_event_context_free(data->ctx);
- memdelete(data);
- *p_data = nullptr;
+
+ if (use_tls) {
+ Ref<StreamPeerTLS> tls;
+ if (connection == tcp) {
+ // Start SSL handshake
+ tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
+ ERR_FAIL_COND_MSG(tls.is_null(), "SSL is not available in this build.");
+ tls->set_blocking_handshake_enabled(false);
+ if (tls->connect_to_stream(tcp, verify_tls, requested_host, tls_cert) != OK) {
+ close(-1);
+ return; // Error.
+ }
+ connection = tls;
+ } else {
+ tls = static_cast<Ref<StreamPeerTLS>>(connection);
+ ERR_FAIL_COND(tls.is_null());
+ tls->poll();
+ }
+ if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
+ return; // Need more polling.
+ } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
+ close(-1);
+ return; // Error.
+ }
+ }
+
+ // Do websocket handshake.
+ if (pending_request) {
+ int left = handshake_buffer->get_available_bytes();
+ int pos = handshake_buffer->get_position();
+ const Vector<uint8_t> data = handshake_buffer->get_data_array();
+ int sent = 0;
+ Error err = connection->put_partial_data(data.ptr() + pos, left, sent);
+ // Sending handshake failed
+ if (err != OK) {
+ close(-1);
+ return; // Error.
+ }
+ handshake_buffer->seek(pos + sent);
+ if (handshake_buffer->get_available_bytes() == 0) {
+ pending_request = false;
+ handshake_buffer->clear();
+ handshake_buffer->resize(WSL_MAX_HEADER_SIZE);
+ handshake_buffer->seek(0);
+ }
+ } else {
+ int read = 0;
+ while (true) {
+ int left = handshake_buffer->get_available_bytes();
+ int pos = handshake_buffer->get_position();
+ if (left == 0) {
+ // Header is too big
+ close(-1);
+ ERR_FAIL_MSG("Response headers too big.");
+ return;
+ }
+
+ uint8_t byte;
+ Error err = connection->get_partial_data(&byte, 1, read);
+ if (err != OK) {
+ // Got some error.
+ close(-1);
+ return;
+ } else if (read != 1) {
+ // Busy, wait next poll.
+ break;
+ }
+ handshake_buffer->put_u8(byte);
+
+ // Check "\r\n\r\n" header terminator
+ const char *r = (const char *)handshake_buffer->get_data_array().ptr();
+ int l = pos;
+ if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
+ // Response is over, verify headers and initialize wslay context/
+ if (!_verify_server_response()) {
+ close(-1);
+ ERR_FAIL_MSG("Invalid response headers.");
+ return;
+ }
+ wslay_event_context_client_init(&wsl_ctx, &_wsl_callbacks, this);
+ wslay_event_config_set_max_recv_msg_length(wsl_ctx, inbound_buffer_size);
+ in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
+ packet_buffer.resize(inbound_buffer_size);
+ ready_state = STATE_OPEN;
+ break;
+ }
+ }
+ }
}
-bool WSLPeer::_wsl_poll(struct PeerData *p_data) {
- p_data->polling = true;
- int err = 0;
- if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) {
- print_verbose("Websocket (wslay) poll error: " + itos(err));
- p_data->destroy = true;
+bool WSLPeer::_verify_server_response() {
+ Vector<String> psa = String((const char *)handshake_buffer->get_data_array().ptr(), handshake_buffer->get_position() - 4).split("\r\n");
+ int len = psa.size();
+ ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers. Got: " + itos(len) + ", expected >= 4.");
+
+ Vector<String> req = psa[0].split(" ", false);
+ ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code. Got '" + psa[0] + "', expected 'HTTP/1.1 101'.");
+
+ // Wrong protocol
+ ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1", false, "Invalid protocol. Got: '" + req[0] + "', expected 'HTTP/1.1'.");
+ ERR_FAIL_COND_V_MSG(req[1] != "101", false, "Invalid status code. Got: '" + req[1] + "', expected '101'.");
+
+ HashMap<String, String> headers;
+ for (int i = 1; i < len; i++) {
+ Vector<String> header = psa[i].split(":", false, 1);
+ ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + ".");
+ String name = header[0].to_lower();
+ String value = header[1].strip_edges();
+ if (headers.has(name)) {
+ headers[name] += "," + value;
+ } else {
+ headers[name] = value;
+ }
}
- p_data->polling = false;
- if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) {
- bool valid = p_data->valid;
- _wsl_destroy(&p_data);
- return valid;
+#define WSL_CHECK(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+#define WSL_CHECK_NC(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+ WSL_CHECK("connection", "upgrade");
+ WSL_CHECK("upgrade", "websocket");
+ WSL_CHECK_NC("sec-websocket-accept", _compute_key_response(session_key));
+#undef WSL_CHECK_NC
+#undef WSL_CHECK
+ if (supported_protocols.size() == 0) {
+ // We didn't request a custom protocol
+ ERR_FAIL_COND_V_MSG(headers.has("sec-websocket-protocol"), false, "Received unrequested sub-protocol -> " + headers["sec-websocket-protocol"]);
+ } else {
+ // We requested at least one custom protocol but didn't receive one
+ ERR_FAIL_COND_V_MSG(!headers.has("sec-websocket-protocol"), false, "Requested sub-protocol(s) but received none.");
+ // Check received sub-protocol was one of those requested.
+ selected_protocol = headers["sec-websocket-protocol"];
+ bool valid = false;
+ for (int i = 0; i < supported_protocols.size(); i++) {
+ if (supported_protocols[i] != selected_protocol) {
+ continue;
+ }
+ valid = true;
+ break;
+ }
+ if (!valid) {
+ ERR_FAIL_V_MSG(false, "Received unrequested sub-protocol -> " + selected_protocol);
+ return false;
+ }
+ }
+ return true;
+}
+
+Error WSLPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_cert) {
+ ERR_FAIL_COND_V(wsl_ctx || tcp.is_valid(), ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(p_url.is_empty(), ERR_INVALID_PARAMETER);
+
+ _clear();
+
+ String host;
+ String path;
+ String scheme;
+ int port = 0;
+ Error err = p_url.parse_url(scheme, host, port, path);
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);
+ if (scheme.is_empty()) {
+ scheme = "ws://";
+ }
+ ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme));
+
+ use_tls = false;
+ if (scheme == "wss://") {
+ use_tls = true;
+ }
+ if (port == 0) {
+ port = use_tls ? 443 : 80;
+ }
+ if (path.is_empty()) {
+ path = "/";
+ }
+
+ requested_url = p_url;
+ requested_host = host;
+ verify_tls = p_verify_tls;
+ tls_cert = p_cert;
+ tcp.instantiate();
+
+ resolver.start(host, port);
+ resolver.try_next_candidate(tcp);
+
+ if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTING && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED && !resolver.has_more_candidates()) {
+ _clear();
+ return FAILED;
+ }
+ connection = tcp;
+
+ // Prepare handshake request.
+ session_key = _generate_key();
+ String request = "GET " + path + " HTTP/1.1\r\n";
+ String port_string;
+ if ((port != 80 && !use_tls) || (port != 443 && use_tls)) {
+ port_string = ":" + itos(port);
+ }
+ request += "Host: " + host + port_string + "\r\n";
+ request += "Upgrade: websocket\r\n";
+ request += "Connection: Upgrade\r\n";
+ request += "Sec-WebSocket-Key: " + session_key + "\r\n";
+ request += "Sec-WebSocket-Version: 13\r\n";
+ if (supported_protocols.size() > 0) {
+ request += "Sec-WebSocket-Protocol: ";
+ for (int i = 0; i < supported_protocols.size(); i++) {
+ if (i != 0) {
+ request += ",";
+ }
+ request += supported_protocols[i];
+ }
+ request += "\r\n";
}
- return false;
+ for (int i = 0; i < handshake_headers.size(); i++) {
+ request += handshake_headers[i] + "\r\n";
+ }
+ request += "\r\n";
+ CharString cs = request.utf8();
+ handshake_buffer->put_data((const uint8_t *)cs.get_data(), cs.length());
+ handshake_buffer->seek(0);
+ ready_state = STATE_CONNECTING;
+ is_server = false;
+ return OK;
}
-ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
- struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
- if (!peer_data->valid) {
+///
+/// Callback functions.
+///
+ssize_t WSLPeer::_wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
+ WSLPeer *peer = (WSLPeer *)user_data;
+ Ref<StreamPeer> conn = peer->connection;
+ if (conn.is_null()) {
wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
return -1;
}
- Ref<StreamPeer> conn = peer_data->conn;
int read = 0;
Error err = conn->get_partial_data(data, len, read);
if (err != OK) {
@@ -111,13 +577,13 @@ ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len
return read;
}
-ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
- struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
- if (!peer_data->valid) {
+ssize_t WSLPeer::_wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
+ WSLPeer *peer = (WSLPeer *)user_data;
+ Ref<StreamPeer> conn = peer->connection;
+ if (conn.is_null()) {
wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
return -1;
}
- Ref<StreamPeer> conn = peer_data->conn;
int sent = 0;
Error err = conn->put_partial_data(data, len, sent);
if (err != OK) {
@@ -131,144 +597,142 @@ ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size
return sent;
}
-int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
- RandomNumberGenerator rng;
- // TODO maybe use crypto in the future?
- rng.set_seed(OS::get_singleton()->get_unix_time());
- for (unsigned int i = 0; i < len; i++) {
- buf[i] = (uint8_t)rng.randi_range(0, 255);
- }
+int WSLPeer::_wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
+ ERR_FAIL_COND_V(!_static_rng, WSLAY_ERR_CALLBACK_FAILURE);
+ Error err = _static_rng->get_random_bytes(buf, len);
+ ERR_FAIL_COND_V(err != OK, WSLAY_ERR_CALLBACK_FAILURE);
return 0;
}
-void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
- struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
- if (!peer_data->valid || peer_data->closing) {
+void WSLPeer::_wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
+ WSLPeer *peer = (WSLPeer *)user_data;
+ uint8_t op = arg->opcode;
+
+ if (op == WSLAY_CONNECTION_CLOSE) {
+ // Close request or confirmation.
+ peer->close_code = arg->status_code;
+ size_t len = arg->msg_length;
+ peer->close_reason = "";
+ if (len > 2 /* first 2 bytes = close code */) {
+ peer->close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
+ }
+ if (peer->ready_state == STATE_OPEN) {
+ peer->ready_state = STATE_CLOSING;
+ }
return;
}
- WSLPeer *peer = static_cast<WSLPeer *>(peer_data->peer);
- if (peer->parse_message(arg) != OK) {
+ if (peer->ready_state == STATE_CLOSING) {
return;
}
- if (peer_data->is_server) {
- WSLServer *helper = static_cast<WSLServer *>(peer_data->obj);
- helper->_on_peer_packet(peer_data->id);
- } else {
- WSLClient *helper = static_cast<WSLClient *>(peer_data->obj);
- helper->_on_peer_packet();
+ if (op == WSLAY_TEXT_FRAME || op == WSLAY_BINARY_FRAME) {
+ // Message.
+ uint8_t is_string = arg->opcode == WSLAY_TEXT_FRAME ? 1 : 0;
+ peer->in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
}
+ // Ping or pong.
}
-wslay_event_callbacks wsl_callbacks = {
- wsl_recv_callback,
- wsl_send_callback,
- wsl_genmask_callback,
+wslay_event_callbacks WSLPeer::_wsl_callbacks = {
+ _wsl_recv_callback,
+ _wsl_send_callback,
+ _wsl_genmask_callback,
nullptr, /* on_frame_recv_start_callback */
nullptr, /* on_frame_recv_callback */
nullptr, /* on_frame_recv_end_callback */
- wsl_msg_recv_callback
+ _wsl_msg_recv_callback
};
-Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) {
- uint8_t is_string = 0;
- if (arg->opcode == WSLAY_TEXT_FRAME) {
- is_string = 1;
- } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) {
- close_code = arg->status_code;
- size_t len = arg->msg_length;
- close_reason = "";
- if (len > 2 /* first 2 bytes = close code */) {
- close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
- }
- if (!wslay_event_get_close_sent(_data->ctx)) {
- if (_data->is_server) {
- WSLServer *helper = static_cast<WSLServer *>(_data->obj);
- helper->_on_close_request(_data->id, close_code, close_reason);
- } else {
- WSLClient *helper = static_cast<WSLClient *>(_data->obj);
- helper->_on_close_request(close_code, close_reason);
- }
- }
- return ERR_FILE_EOF;
- } else if (arg->opcode != WSLAY_BINARY_FRAME) {
- // Ping or pong
- return ERR_SKIP;
- }
- _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
- return OK;
-}
-
-void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) {
- ERR_FAIL_COND(_data != nullptr);
- ERR_FAIL_COND(p_data == nullptr);
-
- _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
- _packet_buffer.resize(1 << p_in_buf_size);
- _out_buf_size = p_out_buf_size;
- _out_pkt_size = p_out_pkt_size;
-
- _data = p_data;
- _data->peer = this;
- _data->valid = true;
-
- if (_data->is_server) {
- wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data);
- } else {
- wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data);
- }
- wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size));
-}
-
-void WSLPeer::set_write_mode(WriteMode p_mode) {
- write_mode = p_mode;
+String WSLPeer::_generate_key() {
+ // Random key
+ Vector<uint8_t> bkey;
+ int len = 16; // 16 bytes, as per RFC
+ bkey.resize(len);
+ _wsl_genmask_callback(nullptr, bkey.ptrw(), len, nullptr);
+ return CryptoCore::b64_encode_str(bkey.ptrw(), len);
}
-WSLPeer::WriteMode WSLPeer::get_write_mode() const {
- return write_mode;
+String WSLPeer::_compute_key_response(String p_key) {
+ String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC
+ Vector<uint8_t> sha = key.sha1_buffer();
+ return CryptoCore::b64_encode_str(sha.ptr(), sha.size());
}
void WSLPeer::poll() {
- if (!_data) {
+ // Nothing to do.
+ if (ready_state == STATE_CLOSED) {
return;
}
- if (_wsl_poll(_data)) {
- _data = nullptr;
+ if (ready_state == STATE_CONNECTING) {
+ if (is_server) {
+ _do_server_handshake();
+ } else {
+ _do_client_handshake();
+ }
+ }
+
+ if (ready_state == STATE_OPEN || ready_state == STATE_CLOSING) {
+ ERR_FAIL_COND(!wsl_ctx);
+ int err = 0;
+ if ((err = wslay_event_recv(wsl_ctx)) != 0 || (err = wslay_event_send(wsl_ctx)) != 0) {
+ // Error close.
+ print_verbose("Websocket (wslay) poll error: " + itos(err));
+ wslay_event_context_free(wsl_ctx);
+ wsl_ctx = nullptr;
+ close(-1);
+ return;
+ }
+ if (wslay_event_get_close_sent(wsl_ctx) && wslay_event_get_close_received(wsl_ctx)) {
+ // Clean close.
+ wslay_event_context_free(wsl_ctx);
+ wsl_ctx = nullptr;
+ close(-1);
+ return;
+ }
}
}
-Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
- ERR_FAIL_COND_V(_out_pkt_size && (wslay_event_get_queued_msg_count(_data->ctx) >= (1ULL << _out_pkt_size)), ERR_OUT_OF_MEMORY);
- ERR_FAIL_COND_V(_out_buf_size && (wslay_event_get_queued_msg_length(_data->ctx) + p_buffer_size >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY);
+Error WSLPeer::_send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode) {
+ ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED);
+ ERR_FAIL_COND_V(wslay_event_get_queued_msg_count(wsl_ctx) >= (uint32_t)max_queued_packets, ERR_OUT_OF_MEMORY);
+ ERR_FAIL_COND_V(outbound_buffer_size > 0 && (wslay_event_get_queued_msg_length(wsl_ctx) + p_buffer_size > (uint32_t)outbound_buffer_size), ERR_OUT_OF_MEMORY);
struct wslay_event_msg msg;
- msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
+ msg.opcode = p_opcode;
msg.msg = p_buffer;
msg.msg_length = p_buffer_size;
// Queue & send message.
- if (wslay_event_queue_msg(_data->ctx, &msg) != 0 || wslay_event_send(_data->ctx) != 0) {
- close_now();
+ if (wslay_event_queue_msg(wsl_ctx, &msg) != 0 || wslay_event_send(wsl_ctx) != 0) {
+ close(-1);
return FAILED;
}
return OK;
}
+Error WSLPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) {
+ wslay_opcode opcode = p_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
+ return _send(p_buffer, p_buffer_size, opcode);
+}
+
+Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+ return _send(p_buffer, p_buffer_size, WSLAY_BINARY_FRAME);
+}
+
Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
r_buffer_size = 0;
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
+ ERR_FAIL_COND_V(ready_state != STATE_OPEN, FAILED);
- if (_in_buffer.packets_left() == 0) {
+ if (in_buffer.packets_left() == 0) {
return ERR_UNAVAILABLE;
}
int read = 0;
- uint8_t *rw = _packet_buffer.ptrw();
- _in_buffer.read_packet(rw, _packet_buffer.size(), &_is_string, read);
+ uint8_t *rw = packet_buffer.ptrw();
+ in_buffer.read_packet(rw, packet_buffer.size(), &was_string, read);
*r_buffer = rw;
r_buffer_size = read;
@@ -277,75 +741,106 @@ Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
}
int WSLPeer::get_available_packet_count() const {
- if (!is_connected_to_host()) {
+ if (ready_state != STATE_OPEN) {
return 0;
}
- return _in_buffer.packets_left();
+ return in_buffer.packets_left();
}
int WSLPeer::get_current_outbound_buffered_amount() const {
- ERR_FAIL_COND_V(!_data, 0);
-
- return wslay_event_get_queued_msg_length(_data->ctx);
-}
-
-bool WSLPeer::was_string_packet() const {
- return _is_string;
-}
-
-bool WSLPeer::is_connected_to_host() const {
- return _data != nullptr;
-}
+ if (ready_state != STATE_OPEN) {
+ return 0;
+ }
-void WSLPeer::close_now() {
- close(1000, "");
- _wsl_destroy(&_data);
+ return wslay_event_get_queued_msg_length(wsl_ctx);
}
void WSLPeer::close(int p_code, String p_reason) {
- if (_data && !wslay_event_get_close_sent(_data->ctx)) {
+ if (p_code < 0) {
+ // Force immediate close.
+ ready_state = STATE_CLOSED;
+ }
+
+ if (ready_state == STATE_OPEN && !wslay_event_get_close_sent(wsl_ctx)) {
CharString cs = p_reason.utf8();
- wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size());
- wslay_event_send(_data->ctx);
- _data->closing = true;
+ wslay_event_queue_close(wsl_ctx, p_code, (uint8_t *)cs.ptr(), cs.length());
+ wslay_event_send(wsl_ctx);
+ ready_state = STATE_CLOSING;
+ } else if (ready_state == STATE_CONNECTING || ready_state == STATE_CLOSED) {
+ ready_state = STATE_CLOSED;
+ connection.unref();
+ if (tcp.is_valid()) {
+ tcp->disconnect_from_host();
+ tcp.unref();
+ }
}
- _in_buffer.clear();
- _packet_buffer.resize(0);
+ in_buffer.clear();
+ packet_buffer.resize(0);
}
IPAddress WSLPeer::get_connected_host() const {
- ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IPAddress());
-
- return _data->tcp->get_connected_host();
+ ERR_FAIL_COND_V(tcp.is_null(), IPAddress());
+ return tcp->get_connected_host();
}
uint16_t WSLPeer::get_connected_port() const {
- ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0);
+ ERR_FAIL_COND_V(tcp.is_null(), 0);
+ return tcp->get_connected_port();
+}
+
+String WSLPeer::get_selected_protocol() const {
+ return selected_protocol;
+}
- return _data->tcp->get_connected_port();
+String WSLPeer::get_requested_url() const {
+ return requested_url;
}
void WSLPeer::set_no_delay(bool p_enabled) {
- ERR_FAIL_COND(!is_connected_to_host() || _data->tcp.is_null());
- _data->tcp->set_no_delay(p_enabled);
+ ERR_FAIL_COND(tcp.is_null());
+ tcp->set_no_delay(p_enabled);
}
-void WSLPeer::invalidate() {
- if (_data) {
- _data->valid = false;
+void WSLPeer::_clear() {
+ // Connection info.
+ ready_state = STATE_CLOSED;
+ is_server = false;
+ connection.unref();
+ if (tcp.is_valid()) {
+ tcp->disconnect_from_host();
+ tcp.unref();
}
+ if (wsl_ctx) {
+ wslay_event_context_free(wsl_ctx);
+ wsl_ctx = nullptr;
+ }
+
+ resolver.stop();
+ requested_url.clear();
+ requested_host.clear();
+ pending_request = true;
+ handshake_buffer->clear();
+ selected_protocol.clear();
+ session_key.clear();
+
+ // Pending packets info.
+ was_string = 0;
+ in_buffer.clear();
+ packet_buffer.clear();
+
+ // Close code info.
+ close_code = -1;
+ close_reason.clear();
}
WSLPeer::WSLPeer() {
+ handshake_buffer.instantiate();
}
WSLPeer::~WSLPeer() {
- close();
- invalidate();
- _wsl_destroy(&_data);
- _data = nullptr;
+ close(-1);
}
#endif // WEB_ENABLED
diff --git a/modules/websocket/wsl_peer.h b/modules/websocket/wsl_peer.h
index 92672eb2c4..379002739c 100644
--- a/modules/websocket/wsl_peer.h
+++ b/modules/websocket/wsl_peer.h
@@ -33,79 +33,123 @@
#ifndef WEB_ENABLED
+#include "websocket_peer.h"
+
+#include "packet_buffer.h"
+
+#include "core/crypto/crypto_core.h"
#include "core/error/error_list.h"
#include "core/io/packet_peer.h"
#include "core/io/stream_peer_tcp.h"
#include "core/templates/ring_buffer.h"
-#include "packet_buffer.h"
-#include "websocket_peer.h"
#include "wslay/wslay.h"
#define WSL_MAX_HEADER_SIZE 4096
class WSLPeer : public WebSocketPeer {
- GDCIIMPL(WSLPeer, WebSocketPeer);
-
-public:
- struct PeerData {
- bool polling = false;
- bool destroy = false;
- bool valid = false;
- bool is_server = false;
- bool closing = false;
- void *obj = nullptr;
- void *peer = nullptr;
- Ref<StreamPeer> conn;
- Ref<StreamPeerTCP> tcp;
- int id = 1;
- wslay_event_context_ptr ctx = nullptr;
+private:
+ static CryptoCore::RandomGenerator *_static_rng;
+ static WebSocketPeer *_create() { return memnew(WSLPeer); }
+
+ // Callbacks.
+ static ssize_t _wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data);
+ static ssize_t _wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data);
+ static int _wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data);
+ static void _wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data);
+
+ static wslay_event_callbacks _wsl_callbacks;
+
+ // Helpers
+ static String _compute_key_response(String p_key);
+ static String _generate_key();
+
+ // Client IP resolver.
+ class Resolver {
+ Array ip_candidates;
+ IP::ResolverID resolver_id = IP::RESOLVER_INVALID_ID;
+ int port = 0;
+
+ public:
+ bool has_more_candidates() {
+ return ip_candidates.size() > 0 || resolver_id != IP::RESOLVER_INVALID_ID;
+ }
+
+ void try_next_candidate(Ref<StreamPeerTCP> &p_tcp);
+ void start(const String &p_host, int p_port);
+ void stop();
+ Resolver() {}
};
- static String compute_key_response(String p_key);
- static String generate_key();
+ Resolver resolver;
-private:
- static bool _wsl_poll(struct PeerData *p_data);
- static void _wsl_destroy(struct PeerData **p_data);
+ // WebSocket connection state.
+ WebSocketPeer::State ready_state = WebSocketPeer::STATE_CLOSED;
+ bool is_server = false;
+ Ref<StreamPeerTCP> tcp;
+ Ref<StreamPeer> connection;
+ wslay_event_context_ptr wsl_ctx = nullptr;
+
+ String requested_url;
+ String requested_host;
+ bool pending_request = true;
+ Ref<StreamPeerBuffer> handshake_buffer;
+ String selected_protocol;
+ String session_key;
- struct PeerData *_data = nullptr;
- uint8_t _is_string = 0;
+ int close_code = -1;
+ String close_reason;
+ uint8_t was_string = 0;
+
+ // WebSocket configuration.
+ bool use_tls = true;
+ bool verify_tls = true;
+ Ref<X509Certificate> tls_cert;
+
+ // Packet buffers.
+ Vector<uint8_t> packet_buffer;
// Our packet info is just a boolean (is_string), using uint8_t for it.
- PacketBuffer<uint8_t> _in_buffer;
+ PacketBuffer<uint8_t> in_buffer;
- Vector<uint8_t> _packet_buffer;
+ Error _send(const uint8_t *p_buffer, int p_buffer_size, wslay_opcode p_opcode);
- WriteMode write_mode = WRITE_MODE_BINARY;
+ Error _do_server_handshake();
+ bool _parse_client_request();
- int _out_buf_size = 0;
- int _out_pkt_size = 0;
+ void _do_client_handshake();
+ bool _verify_server_response();
+
+ void _clear();
public:
- int close_code = -1;
- String close_reason;
- void poll(); // Used by client and server.
+ static void initialize();
+ static void deinitialize();
+ // PacketPeer
virtual int get_available_packet_count() const override;
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override;
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- virtual int get_max_packet_size() const override { return _packet_buffer.size(); };
- virtual int get_current_outbound_buffered_amount() const override;
+ virtual int get_max_packet_size() const override { return packet_buffer.size(); };
- virtual void close_now();
+ // WebSocketPeer
+ virtual Error send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) override;
+ virtual Error connect_to_url(const String &p_url, bool p_verify_tls = true, Ref<X509Certificate> p_cert = Ref<X509Certificate>()) override;
+ virtual Error accept_stream(Ref<StreamPeer> p_stream) override;
virtual void close(int p_code = 1000, String p_reason = "") override;
- virtual bool is_connected_to_host() const override;
+ virtual void poll() override;
+
+ virtual State get_ready_state() const override { return ready_state; }
+ virtual int get_close_code() const override { return close_code; }
+ virtual String get_close_reason() const override { return close_reason; }
+ virtual int get_current_outbound_buffered_amount() const override;
+
virtual IPAddress get_connected_host() const override;
virtual uint16_t get_connected_port() const override;
+ virtual String get_selected_protocol() const override;
+ virtual String get_requested_url() const override;
- virtual WriteMode get_write_mode() const override;
- virtual void set_write_mode(WriteMode p_mode) override;
- virtual bool was_string_packet() const override;
+ virtual bool was_string_packet() const override { return was_string; }
virtual void set_no_delay(bool p_enabled) override;
- void make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size);
- Error parse_message(const wslay_event_on_msg_recv_arg *arg);
- void invalidate();
-
WSLPeer();
~WSLPeer();
};
diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp
deleted file mode 100644
index 01dcd53839..0000000000
--- a/modules/websocket/wsl_server.cpp
+++ /dev/null
@@ -1,329 +0,0 @@
-/*************************************************************************/
-/* wsl_server.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. */
-/*************************************************************************/
-
-#ifndef WEB_ENABLED
-
-#include "wsl_server.h"
-#include "core/config/project_settings.h"
-#include "core/os/os.h"
-
-bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols, String &r_resource_name) {
- Vector<String> psa = String((char *)req_buf).split("\r\n");
- int len = psa.size();
- ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
-
- Vector<String> req = psa[0].split(" ", false);
- ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code.");
-
- // Wrong protocol
- ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version.");
-
- r_resource_name = req[1];
- HashMap<String, String> headers;
- for (int i = 1; i < len; i++) {
- Vector<String> header = psa[i].split(":", false, 1);
- ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
- String name = header[0].to_lower();
- String value = header[1].strip_edges();
- if (headers.has(name)) {
- headers[name] += "," + value;
- } else {
- headers[name] = value;
- }
- }
-#define WSL_CHECK(NAME, VALUE) \
- ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
- "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
-#define WSL_CHECK_EX(NAME) \
- ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
- WSL_CHECK("upgrade", "websocket");
- WSL_CHECK("sec-websocket-version", "13");
- WSL_CHECK_EX("sec-websocket-key");
- WSL_CHECK_EX("connection");
-#undef WSL_CHECK_EX
-#undef WSL_CHECK
- key = headers["sec-websocket-key"];
- if (headers.has("sec-websocket-protocol")) {
- Vector<String> protos = headers["sec-websocket-protocol"].split(",");
- for (int i = 0; i < protos.size(); i++) {
- String proto = protos[i].strip_edges();
- // Check if we have the given protocol
- for (int j = 0; j < p_protocols.size(); j++) {
- if (proto != p_protocols[j]) {
- continue;
- }
- protocol = proto;
- break;
- }
- // Found a protocol
- if (!protocol.is_empty()) {
- break;
- }
- }
- if (protocol.is_empty()) { // Invalid protocol(s) requested
- return false;
- }
- } else if (p_protocols.size() > 0) { // No protocol requested, but we need one
- return false;
- }
- return true;
-}
-
-Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers) {
- if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) {
- print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", p_timeout * 0.001));
- return ERR_TIMEOUT;
- }
-
- if (use_tls) {
- Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection);
- if (tls.is_null()) {
- ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake.");
- }
- tls->poll();
- if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) {
- return ERR_BUSY;
- } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) {
- print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status()));
- return FAILED;
- }
- }
-
- if (!has_request) {
- int read = 0;
- while (true) {
- ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "WebSocket response headers are too big.");
- Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
- if (err != OK) { // Got an error
- print_verbose(vformat("WebSocket error while getting partial data (StreamPeer error code %d).", err));
- return FAILED;
- } else if (read != 1) { // Busy, wait next poll
- return ERR_BUSY;
- }
- char *r = (char *)req_buf;
- int l = req_pos;
- if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
- r[l - 3] = '\0';
- if (!_parse_request(p_protocols, r_resource_name)) {
- return FAILED;
- }
- String s = "HTTP/1.1 101 Switching Protocols\r\n";
- s += "Upgrade: websocket\r\n";
- s += "Connection: Upgrade\r\n";
- s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
- if (!protocol.is_empty()) {
- s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
- }
- for (int i = 0; i < p_extra_headers.size(); i++) {
- s += p_extra_headers[i] + "\r\n";
- }
- s += "\r\n";
- response = s.utf8();
- has_request = true;
- break;
- }
- req_pos += 1;
- }
- }
-
- if (has_request && response_sent < response.size() - 1) {
- int sent = 0;
- Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
- if (err != OK) {
- print_verbose(vformat("WebSocket error while putting partial data (StreamPeer error code %d).", err));
- return err;
- }
- response_sent += sent;
- }
-
- if (response_sent < response.size() - 1) {
- return ERR_BUSY;
- }
-
- return OK;
-}
-
-void WSLServer::set_extra_headers(const Vector<String> &p_headers) {
- _extra_headers = p_headers;
-}
-
-Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) {
- ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
-
- _is_multiplayer = gd_mp_api;
- // Strip edges from protocols.
- _protocols.resize(p_protocols.size());
- String *pw = _protocols.ptrw();
- for (int i = 0; i < p_protocols.size(); i++) {
- pw[i] = p_protocols[i].strip_edges();
- }
- return _server->listen(p_port, bind_ip);
-}
-
-void WSLServer::poll() {
- List<int> remove_ids;
- for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr()));
- peer->poll();
- if (!peer->is_connected_to_host()) {
- _on_disconnect(E.key, peer->close_code != -1);
- remove_ids.push_back(E.key);
- }
- }
- for (int &E : remove_ids) {
- _peer_map.erase(E);
- }
- remove_ids.clear();
-
- List<Ref<PendingPeer>> remove_peers;
- for (const Ref<PendingPeer> &E : _pending) {
- String resource_name;
- Ref<PendingPeer> ppeer = E;
- Error err = ppeer->do_handshake(_protocols, handshake_timeout, resource_name, _extra_headers);
- if (err == ERR_BUSY) {
- continue;
- } else if (err != OK) {
- remove_peers.push_back(ppeer);
- continue;
- }
- // Creating new peer
- int32_t id = generate_unique_id();
-
- WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
- data->obj = this;
- data->conn = ppeer->connection;
- data->tcp = ppeer->tcp;
- data->is_server = true;
- data->id = id;
-
- Ref<WSLPeer> ws_peer = memnew(WSLPeer);
- ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
- ws_peer->set_no_delay(true);
-
- _peer_map[id] = ws_peer;
- remove_peers.push_back(ppeer);
- _on_connect(id, ppeer->protocol, resource_name);
- }
- for (const Ref<PendingPeer> &E : remove_peers) {
- _pending.erase(E);
- }
- remove_peers.clear();
-
- if (!_server->is_listening()) {
- return;
- }
-
- while (_server->is_connection_available()) {
- Ref<StreamPeerTCP> conn = _server->take_connection();
- if (is_refusing_new_connections()) {
- continue; // Conn will go out-of-scope and be closed.
- }
-
- Ref<PendingPeer> peer = memnew(PendingPeer);
- if (private_key.is_valid() && tls_cert.is_valid()) {
- Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create());
- tls->set_blocking_handshake_enabled(false);
- tls->accept_stream(conn, private_key, tls_cert, ca_chain);
- peer->connection = tls;
- peer->use_tls = true;
- } else {
- peer->connection = conn;
- }
- peer->tcp = conn;
- peer->time = OS::get_singleton()->get_ticks_msec();
- _pending.push_back(peer);
- }
-}
-
-bool WSLServer::is_listening() const {
- return _server->is_listening();
-}
-
-int WSLServer::get_max_packet_size() const {
- return (1 << _out_buf_size) - PROTO_SIZE;
-}
-
-void WSLServer::stop() {
- _server->stop();
- for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) {
- Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr()));
- peer->close_now();
- }
- _pending.clear();
- _peer_map.clear();
- _protocols.clear();
-}
-
-bool WSLServer::has_peer(int p_id) const {
- return _peer_map.has(p_id);
-}
-
-Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
- ERR_FAIL_COND_V(!has_peer(p_id), nullptr);
- return _peer_map[p_id];
-}
-
-IPAddress WSLServer::get_peer_address(int p_peer_id) const {
- ERR_FAIL_COND_V(!has_peer(p_peer_id), IPAddress());
-
- return _peer_map[p_peer_id]->get_connected_host();
-}
-
-int WSLServer::get_peer_port(int p_peer_id) const {
- ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
-
- return _peer_map[p_peer_id]->get_connected_port();
-}
-
-void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
- ERR_FAIL_COND(!has_peer(p_peer_id));
-
- get_peer(p_peer_id)->close(p_code, p_reason);
-}
-
-Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
- ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting.");
-
- _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
- _in_pkt_size = nearest_shift(p_in_packets - 1);
- _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
- _out_pkt_size = nearest_shift(p_out_packets - 1);
- return OK;
-}
-
-WSLServer::WSLServer() {
- _server.instantiate();
-}
-
-WSLServer::~WSLServer() {
- stop();
-}
-
-#endif // WEB_ENABLED
diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h
deleted file mode 100644
index df0c1dc68a..0000000000
--- a/modules/websocket/wsl_server.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*************************************************************************/
-/* wsl_server.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 WSL_SERVER_H
-#define WSL_SERVER_H
-
-#ifndef WEB_ENABLED
-
-#include "websocket_server.h"
-#include "wsl_peer.h"
-
-#include "core/io/stream_peer_tcp.h"
-#include "core/io/stream_peer_tls.h"
-#include "core/io/tcp_server.h"
-
-class WSLServer : public WebSocketServer {
- GDCIIMPL(WSLServer, WebSocketServer);
-
-private:
- class PendingPeer : public RefCounted {
- private:
- bool _parse_request(const Vector<String> p_protocols, String &r_resource_name);
-
- public:
- Ref<StreamPeerTCP> tcp;
- Ref<StreamPeer> connection;
- bool use_tls = false;
-
- uint64_t time = 0;
- uint8_t req_buf[WSL_MAX_HEADER_SIZE] = {};
- int req_pos = 0;
- String key;
- String protocol;
- bool has_request = false;
- CharString response;
- int response_sent = 0;
-
- Error do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers);
- };
-
- int _in_buf_size = DEF_BUF_SHIFT;
- int _in_pkt_size = DEF_PKT_SHIFT;
- int _out_buf_size = DEF_BUF_SHIFT;
- int _out_pkt_size = DEF_PKT_SHIFT;
-
- List<Ref<PendingPeer>> _pending;
- Ref<TCPServer> _server;
- Vector<String> _protocols;
- Vector<String> _extra_headers;
-
-public:
- Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override;
- void set_extra_headers(const Vector<String> &p_headers) override;
- Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) override;
- void stop() override;
- bool is_listening() const override;
- int get_max_packet_size() const override;
- bool has_peer(int p_id) const override;
- Ref<WebSocketPeer> get_peer(int p_id) const override;
- IPAddress get_peer_address(int p_peer_id) const override;
- int get_peer_port(int p_peer_id) const override;
- void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") override;
- virtual void poll() override;
-
- WSLServer();
- ~WSLServer();
-};
-
-#endif // WEB_ENABLED
-
-#endif // WSL_SERVER_H
diff --git a/modules/webxr/godot_webxr.h b/modules/webxr/godot_webxr.h
index 34d068be3e..d8d5bd99cc 100644
--- a/modules/webxr/godot_webxr.h
+++ b/modules/webxr/godot_webxr.h
@@ -65,7 +65,7 @@ extern int godot_webxr_get_view_count();
extern int *godot_webxr_get_render_target_size();
extern float *godot_webxr_get_transform_for_eye(int p_eye);
extern float *godot_webxr_get_projection_for_eye(int p_eye);
-extern void godot_webxr_commit_for_eye(int p_eye, unsigned int p_destination_fbo);
+extern void godot_webxr_commit(unsigned int p_texture);
extern void godot_webxr_sample_controller_data();
extern int godot_webxr_get_controller_count();
diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js
index 9b75796ee5..c476a54c59 100644
--- a/modules/webxr/native/library_godot_webxr.js
+++ b/modules/webxr/native/library_godot_webxr.js
@@ -337,20 +337,18 @@ const GodotWebXR = {
return buf;
},
- godot_webxr_commit_for_eye__proxy: 'sync',
- godot_webxr_commit_for_eye__sig: 'vii',
- godot_webxr_commit_for_eye: function (p_eye, p_destination_fbo) {
+ godot_webxr_commit__proxy: 'sync',
+ godot_webxr_commit__sig: 'vi',
+ godot_webxr_commit: function (p_texture) {
if (!GodotWebXR.session || !GodotWebXR.pose) {
return;
}
- const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0;
const glLayer = GodotWebXR.session.renderState.baseLayer;
- const view = GodotWebXR.pose.views[view_index];
- const viewport = glLayer.getViewport(view);
+ const views = GodotWebXR.pose.views;
const gl = GodotWebXR.gl;
- const framebuffer = GL.framebuffers[p_destination_fbo];
+ const texture = GL.textures[p_texture];
const orig_framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
const orig_read_framebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);
@@ -359,14 +357,27 @@ const GodotWebXR = {
// Copy from Godot render target into framebuffer from WebXR.
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer);
- gl.readBuffer(gl.COLOR_ATTACHMENT0);
- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glLayer.framebuffer);
-
- // Flip Y upside down on destination.
- gl.blitFramebuffer(0, 0, viewport.width, viewport.height,
- viewport.x, viewport.height, viewport.width, viewport.y,
- gl.COLOR_BUFFER_BIT, gl.NEAREST);
+ for (let i = 0; i < views.length; i++) {
+ const viewport = glLayer.getViewport(views[i]);
+
+ const read_fbo = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, read_fbo);
+ if (views.length > 1) {
+ gl.framebufferTextureLayer(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, texture, 0, i);
+ } else {
+ gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ }
+ gl.readBuffer(gl.COLOR_ATTACHMENT0);
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glLayer.framebuffer);
+
+ // Flip Y upside down on destination.
+ gl.blitFramebuffer(0, 0, viewport.width, viewport.height,
+ viewport.x, viewport.y + viewport.height, viewport.x + viewport.width, viewport.y,
+ gl.COLOR_BUFFER_BIT, gl.NEAREST);
+
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
+ gl.deleteFramebuffer(read_fbo);
+ }
// Restore state.
gl.bindFramebuffer(gl.FRAMEBUFFER, orig_framebuffer);
diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp
index 6b671c1660..f6ed9f027e 100644
--- a/modules/webxr/webxr_interface_js.cpp
+++ b/modules/webxr/webxr_interface_js.cpp
@@ -415,8 +415,7 @@ Vector<BlitToScreen> WebXRInterfaceJS::post_draw_viewport(RID p_render_target, c
GLES3::RenderTarget *rt = texture_storage->get_render_target(p_render_target);
- // @todo Support multiple eyes!
- godot_webxr_commit_for_eye(1, rt->fbo);
+ godot_webxr_commit(rt->color);
return blit_to_screen;
};
diff --git a/modules/zip/SCsub b/modules/zip/SCsub
new file mode 100644
index 0000000000..b7710123fd
--- /dev/null
+++ b/modules/zip/SCsub
@@ -0,0 +1,9 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_zip = env_modules.Clone()
+
+# Module files
+env_zip.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/zip/config.py b/modules/zip/config.py
new file mode 100644
index 0000000000..96cd2fc5bd
--- /dev/null
+++ b/modules/zip/config.py
@@ -0,0 +1,17 @@
+def can_build(env, platform):
+ return env["minizip"]
+
+
+def configure(env):
+ pass
+
+
+def get_doc_classes():
+ return [
+ "ZIPReader",
+ "ZIPPacker",
+ ]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/zip/doc_classes/ZIPPacker.xml b/modules/zip/doc_classes/ZIPPacker.xml
new file mode 100644
index 0000000000..95d7ef50f9
--- /dev/null
+++ b/modules/zip/doc_classes/ZIPPacker.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="ZIPPacker" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
+ <brief_description>
+ Allows the creation of zip files.
+ </brief_description>
+ <description>
+ This class implements a writer that allows storing the multiple blobs in a zip archive.
+ [codeblock]
+ func write_zip_file():
+ var writer := ZIPPacker.new()
+ var err := writer.open("user://archive.zip")
+ if err != OK:
+ return err
+ writer.start_file("hello.txt")
+ writer.write_file("Hello World".to_utf8_buffer())
+ writer.close_file()
+
+ writer.close()
+ return OK
+ [/codeblock]
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="close">
+ <return type="int" enum="Error" />
+ <description>
+ Closes the underlying resources used by this instance.
+ </description>
+ </method>
+ <method name="close_file">
+ <return type="int" enum="Error" />
+ <description>
+ Stops writing to a file within the archive.
+ It will fail if there is no open file.
+ </description>
+ </method>
+ <method name="open">
+ <return type="int" enum="Error" />
+ <param index="0" name="path" type="String" />
+ <param index="1" name="append" type="int" enum="ZIPPacker.ZipAppend" default="0" />
+ <description>
+ Opens a zip file for writing at the given path using the specified write mode.
+ This must be called before everything else.
+ </description>
+ </method>
+ <method name="start_file">
+ <return type="int" enum="Error" />
+ <param index="0" name="path" type="String" />
+ <description>
+ Starts writing to a file within the archive. Only one file can be written at the same time.
+ Must be called after [method open].
+ </description>
+ </method>
+ <method name="write_file">
+ <return type="int" enum="Error" />
+ <param index="0" name="data" type="PackedByteArray" />
+ <description>
+ Write the given [param data] to the file.
+ Needs to be called after [method start_file].
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="APPEND_CREATE" value="0" enum="ZipAppend">
+ </constant>
+ <constant name="APPEND_CREATEAFTER" value="1" enum="ZipAppend">
+ </constant>
+ <constant name="APPEND_ADDINZIP" value="2" enum="ZipAppend">
+ </constant>
+ </constants>
+</class>
diff --git a/modules/zip/doc_classes/ZIPReader.xml b/modules/zip/doc_classes/ZIPReader.xml
new file mode 100644
index 0000000000..717116a531
--- /dev/null
+++ b/modules/zip/doc_classes/ZIPReader.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="ZIPReader" inherits="RefCounted" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
+ <brief_description>
+ Allows reading the content of a zip file.
+ </brief_description>
+ <description>
+ This class implements a reader that can extract the content of individual files inside a zip archive.
+ [codeblock]
+ func read_zip_file():
+ var reader := ZIPReader.new()
+ var err := reader.open("user://archive.zip")
+ if err == OK:
+ return PackedByteArray()
+ var res := reader.read_file("hello.txt")
+ reader.close()
+ return res
+ [/codeblock]
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="close">
+ <return type="int" enum="Error" />
+ <description>
+ Closes the underlying resources used by this instance.
+ </description>
+ </method>
+ <method name="get_files">
+ <return type="PackedStringArray" />
+ <description>
+ Returns the list of names of all files in the loaded archive.
+ Must be called after [method open].
+ </description>
+ </method>
+ <method name="open">
+ <return type="int" enum="Error" />
+ <param index="0" name="path" type="String" />
+ <description>
+ Opens the zip archive at the given [param path] and reads its file index.
+ </description>
+ </method>
+ <method name="read_file">
+ <return type="PackedByteArray" />
+ <param index="0" name="path" type="String" />
+ <param index="1" name="case_sensitive" type="bool" default="true" />
+ <description>
+ Loads the whole content of a file in the loaded zip archive into memory and returns it.
+ Must be called after [method open].
+ </description>
+ </method>
+ </methods>
+</class>
diff --git a/modules/websocket/wsl_client.h b/modules/zip/register_types.cpp
index dfb989fdd3..20fb484cfe 100644
--- a/modules/websocket/wsl_client.h
+++ b/modules/zip/register_types.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* wsl_client.h */
+/* register_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,64 +28,23 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef WSL_CLIENT_H
-#define WSL_CLIENT_H
+#include "register_types.h"
-#ifndef WEB_ENABLED
+#include "core/object/class_db.h"
+#include "zip_packer.h"
+#include "zip_reader.h"
-#include "core/error/error_list.h"
-#include "core/io/stream_peer_tcp.h"
-#include "core/io/stream_peer_tls.h"
-#include "websocket_client.h"
-#include "wsl_peer.h"
-#include "wslay/wslay.h"
+void initialize_zip_module(ModuleInitializationLevel p_level) {
+ if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
+ return;
+ }
-class WSLClient : public WebSocketClient {
- GDCIIMPL(WSLClient, WebSocketClient);
+ GDREGISTER_CLASS(ZIPPacker);
+ GDREGISTER_CLASS(ZIPReader);
+}
-private:
- int _in_buf_size = DEF_BUF_SHIFT;
- int _in_pkt_size = DEF_PKT_SHIFT;
- int _out_buf_size = DEF_BUF_SHIFT;
- int _out_pkt_size = DEF_PKT_SHIFT;
-
- Ref<WSLPeer> _peer;
- Ref<StreamPeerTCP> _tcp;
- Ref<StreamPeer> _connection;
- ConnectionStatus _status = CONNECTION_DISCONNECTED;
-
- CharString _request;
- int _requested = 0;
-
- uint8_t _resp_buf[WSL_MAX_HEADER_SIZE];
- int _resp_pos = 0;
-
- String _key;
- String _host;
- uint16_t _port = 0;
- Array _ip_candidates;
- Vector<String> _protocols;
- bool _use_tls = false;
- IP::ResolverID _resolver_id = IP::RESOLVER_INVALID_ID;
-
- void _do_handshake();
- bool _verify_headers(String &r_protocol);
-
-public:
- Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override;
- Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override;
- int get_max_packet_size() const override;
- Ref<WebSocketPeer> get_peer(int p_peer_id) const override;
- void disconnect_from_host(int p_code = 1000, String p_reason = "") override;
- IPAddress get_connected_host() const override;
- uint16_t get_connected_port() const override;
- virtual ConnectionStatus get_connection_status() const override;
- virtual void poll() override;
-
- WSLClient();
- ~WSLClient();
-};
-
-#endif // WEB_ENABLED
-
-#endif // WSL_CLIENT_H
+void uninitialize_zip_module(ModuleInitializationLevel p_level) {
+ if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
+ return;
+ }
+}
diff --git a/modules/zip/register_types.h b/modules/zip/register_types.h
new file mode 100644
index 0000000000..2640be12b8
--- /dev/null
+++ b/modules/zip/register_types.h
@@ -0,0 +1,39 @@
+/*************************************************************************/
+/* register_types.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 ZIP_REGISTER_TYPES_H
+#define ZIP_REGISTER_TYPES_H
+
+#include "modules/register_module_types.h"
+
+void initialize_zip_module(ModuleInitializationLevel p_level);
+void uninitialize_zip_module(ModuleInitializationLevel p_level);
+
+#endif // ZIP_REGISTER_TYPES_H
diff --git a/modules/zip/zip_packer.cpp b/modules/zip/zip_packer.cpp
new file mode 100644
index 0000000000..c37fc0945e
--- /dev/null
+++ b/modules/zip/zip_packer.cpp
@@ -0,0 +1,108 @@
+/*************************************************************************/
+/* zip_packer.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 "zip_packer.h"
+
+#include "core/io/zip_io.h"
+#include "core/os/os.h"
+
+Error ZIPPacker::open(String p_path, ZipAppend p_append) {
+ if (fa.is_valid()) {
+ close();
+ }
+
+ zlib_filefunc_def io = zipio_create_io(&fa);
+ zf = zipOpen2(p_path.utf8().get_data(), p_append, NULL, &io);
+ return zf != NULL ? OK : FAILED;
+}
+
+Error ZIPPacker::close() {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker cannot be closed because it is not open.");
+
+ return zipClose(zf, NULL) == ZIP_OK ? OK : FAILED;
+}
+
+Error ZIPPacker::start_file(String p_path) {
+ ERR_FAIL_COND_V_MSG(zf != NULL, FAILED, "ZIPPacker is already in use.");
+ ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use.");
+
+ zip_fileinfo zipfi;
+
+ OS::DateTime time = OS::get_singleton()->get_datetime();
+
+ zipfi.tmz_date.tm_hour = time.hour;
+ zipfi.tmz_date.tm_mday = time.day;
+ zipfi.tmz_date.tm_min = time.minute;
+ zipfi.tmz_date.tm_mon = time.month - 1;
+ zipfi.tmz_date.tm_sec = time.second;
+ zipfi.tmz_date.tm_year = time.year;
+ zipfi.dosDate = 0;
+ zipfi.external_fa = 0;
+ zipfi.internal_fa = 0;
+
+ int ret = zipOpenNewFileInZip(zf, p_path.utf8().get_data(), &zipfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
+ return ret == ZIP_OK ? OK : FAILED;
+}
+
+Error ZIPPacker::write_file(Vector<uint8_t> p_data) {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use.");
+
+ return zipWriteInFileInZip(zf, p_data.ptr(), p_data.size()) == ZIP_OK ? OK : FAILED;
+}
+
+Error ZIPPacker::close_file() {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPPacker must be opened before use.");
+
+ Error err = zipCloseFileInZip(zf) == ZIP_OK ? OK : FAILED;
+ if (err == OK) {
+ zf = NULL;
+ }
+ return err;
+}
+
+void ZIPPacker::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("open", "path", "append"), &ZIPPacker::open, DEFVAL(Variant(APPEND_CREATE)));
+ ClassDB::bind_method(D_METHOD("start_file", "path"), &ZIPPacker::start_file);
+ ClassDB::bind_method(D_METHOD("write_file", "data"), &ZIPPacker::write_file);
+ ClassDB::bind_method(D_METHOD("close_file"), &ZIPPacker::close_file);
+ ClassDB::bind_method(D_METHOD("close"), &ZIPPacker::close);
+
+ BIND_ENUM_CONSTANT(APPEND_CREATE);
+ BIND_ENUM_CONSTANT(APPEND_CREATEAFTER);
+ BIND_ENUM_CONSTANT(APPEND_ADDINZIP);
+}
+
+ZIPPacker::ZIPPacker() {}
+
+ZIPPacker::~ZIPPacker() {
+ if (fa.is_valid()) {
+ close();
+ }
+}
diff --git a/modules/websocket/websocket_macros.h b/modules/zip/zip_packer.h
index b03bd8f45c..23e96b5ad2 100644
--- a/modules/websocket/websocket_macros.h
+++ b/modules/zip/zip_packer.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* websocket_macros.h */
+/* zip_packer.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,39 +28,41 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef WEBSOCKET_MACROS_H
-#define WEBSOCKET_MACROS_H
+#ifndef ZIP_PACKER_H
+#define ZIP_PACKER_H
-// Defaults per peer buffers, 1024 packets with a shared 65536 bytes payload.
-#define DEF_PKT_SHIFT 10
-#define DEF_BUF_SHIFT 16
+#include "core/io/file_access.h"
+#include "core/object/ref_counted.h"
-#define GDCICLASS(CNAME) \
-public: \
- static CNAME *(*_create)(); \
- \
- static Ref<CNAME> create_ref() { \
- if (!_create) \
- return Ref<CNAME>(); \
- return Ref<CNAME>(_create()); \
- } \
- \
- static CNAME *create() { \
- if (!_create) \
- return nullptr; \
- return _create(); \
- } \
- \
-protected:
+#include "thirdparty/minizip/zip.h"
+
+class ZIPPacker : public RefCounted {
+ GDCLASS(ZIPPacker, RefCounted);
-#define GDCINULL(CNAME) \
- CNAME *(*CNAME::_create)() = nullptr;
+ Ref<FileAccess> fa;
+ zipFile zf;
-#define GDCIIMPL(IMPNAME, CNAME) \
-public: \
- static CNAME *_create() { return memnew(IMPNAME); } \
- static void make_default() { CNAME::_create = IMPNAME::_create; } \
- \
protected:
+ static void _bind_methods();
+
+public:
+ enum ZipAppend {
+ APPEND_CREATE = 0,
+ APPEND_CREATEAFTER = 1,
+ APPEND_ADDINZIP = 2,
+ };
+
+ Error open(String p_path, ZipAppend p_append);
+ Error close();
+
+ Error start_file(String p_path);
+ Error write_file(Vector<uint8_t> p_data);
+ Error close_file();
+
+ ZIPPacker();
+ ~ZIPPacker();
+};
+
+VARIANT_ENUM_CAST(ZIPPacker::ZipAppend)
-#endif // WEBSOCKET_MACROS_H
+#endif // ZIP_PACKER_H
diff --git a/modules/zip/zip_reader.cpp b/modules/zip/zip_reader.cpp
new file mode 100644
index 0000000000..f35b947cef
--- /dev/null
+++ b/modules/zip/zip_reader.cpp
@@ -0,0 +1,123 @@
+/*************************************************************************/
+/* zip_reader.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 "zip_reader.h"
+
+#include "core/error/error_macros.h"
+#include "core/io/zip_io.h"
+
+Error ZIPReader::open(String p_path) {
+ if (fa.is_valid()) {
+ close();
+ }
+
+ zlib_filefunc_def io = zipio_create_io(&fa);
+ uzf = unzOpen2(p_path.utf8().get_data(), &io);
+ return uzf != NULL ? OK : FAILED;
+}
+
+Error ZIPReader::close() {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), FAILED, "ZIPReader cannot be closed because it is not open.");
+
+ return unzClose(uzf) == UNZ_OK ? OK : FAILED;
+}
+
+PackedStringArray ZIPReader::get_files() {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), PackedStringArray(), "ZIPReader must be opened before use.");
+
+ List<String> s;
+
+ if (unzGoToFirstFile(uzf) != UNZ_OK) {
+ return PackedStringArray();
+ }
+
+ do {
+ unz_file_info64 file_info;
+ char filename[256]; // Note filename is a path !
+ int err = unzGetCurrentFileInfo64(uzf, &file_info, filename, sizeof(filename), NULL, 0, NULL, 0);
+ if (err == UNZ_OK) {
+ s.push_back(filename);
+ } else {
+ // Assume filename buffer was too small
+ char *long_filename_buff = (char *)memalloc(file_info.size_filename);
+ int err2 = unzGetCurrentFileInfo64(uzf, NULL, long_filename_buff, sizeof(long_filename_buff), NULL, 0, NULL, 0);
+ if (err2 == UNZ_OK) {
+ s.push_back(long_filename_buff);
+ memfree(long_filename_buff);
+ }
+ }
+ } while (unzGoToNextFile(uzf) == UNZ_OK);
+
+ PackedStringArray arr;
+ arr.resize(s.size());
+ int idx = 0;
+ for (const List<String>::Element *E = s.front(); E; E = E->next()) {
+ arr.set(idx++, E->get());
+ }
+ return arr;
+}
+
+PackedByteArray ZIPReader::read_file(String p_path, bool p_case_sensitive) {
+ ERR_FAIL_COND_V_MSG(fa.is_null(), PackedByteArray(), "ZIPReader must be opened before use.");
+
+ int cs = p_case_sensitive ? 1 : 2;
+ if (unzLocateFile(uzf, p_path.utf8().get_data(), cs) != UNZ_OK) {
+ ERR_FAIL_V_MSG(PackedByteArray(), "File does not exist in zip archive: " + p_path);
+ }
+ if (unzOpenCurrentFile(uzf) != UNZ_OK) {
+ ERR_FAIL_V_MSG(PackedByteArray(), "Could not open file within zip archive.");
+ }
+
+ unz_file_info info;
+ unzGetCurrentFileInfo(uzf, &info, NULL, 0, NULL, 0, NULL, 0);
+ PackedByteArray data;
+ data.resize(info.uncompressed_size);
+
+ uint8_t *w = data.ptrw();
+ unzReadCurrentFile(uzf, &w[0], info.uncompressed_size);
+
+ unzCloseCurrentFile(uzf);
+ return data;
+}
+
+ZIPReader::ZIPReader() {}
+
+ZIPReader::~ZIPReader() {
+ if (fa.is_valid()) {
+ close();
+ }
+}
+
+void ZIPReader::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("open", "path"), &ZIPReader::open);
+ ClassDB::bind_method(D_METHOD("close"), &ZIPReader::close);
+ ClassDB::bind_method(D_METHOD("get_files"), &ZIPReader::get_files);
+ ClassDB::bind_method(D_METHOD("read_file", "path", "case_sensitive"), &ZIPReader::read_file, DEFVAL(Variant(true)));
+}
diff --git a/modules/websocket/emws_client.h b/modules/zip/zip_reader.h
index cdcec31e19..fbc2fc0409 100644
--- a/modules/websocket/emws_client.h
+++ b/modules/zip/zip_reader.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* emws_client.h */
+/* zip_reader.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,44 +28,32 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef EMWS_CLIENT_H
-#define EMWS_CLIENT_H
+#ifndef ZIP_READER_H
+#define ZIP_READER_H
-#ifdef WEB_ENABLED
+#include "core/io/file_access.h"
+#include "core/object/ref_counted.h"
-#include "core/error/error_list.h"
-#include "emws_peer.h"
-#include "websocket_client.h"
+#include "thirdparty/minizip/unzip.h"
-class EMWSClient : public WebSocketClient {
- GDCIIMPL(EMWSClient, WebSocketClient);
+class ZIPReader : public RefCounted {
+ GDCLASS(ZIPReader, RefCounted)
-private:
- int _js_id = 0;
- bool _is_connecting = false;
- int _in_buf_size = DEF_BUF_SHIFT;
- int _in_pkt_size = DEF_PKT_SHIFT;
- int _out_buf_size = DEF_BUF_SHIFT;
+ Ref<FileAccess> fa;
+ unzFile uzf;
- static void _esws_on_connect(void *obj, char *proto);
- static void _esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string);
- static void _esws_on_error(void *obj);
- static void _esws_on_close(void *obj, int code, const char *reason, int was_clean);
+protected:
+ static void _bind_methods();
public:
- Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override;
- Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override;
- Ref<WebSocketPeer> get_peer(int p_peer_id) const override;
- void disconnect_from_host(int p_code = 1000, String p_reason = "") override;
- IPAddress get_connected_host() const override;
- uint16_t get_connected_port() const override;
- virtual ConnectionStatus get_connection_status() const override;
- int get_max_packet_size() const override;
- virtual void poll() override;
- EMWSClient();
- ~EMWSClient();
-};
+ Error open(String p_path);
+ Error close();
+
+ PackedStringArray get_files();
+ PackedByteArray read_file(String p_path, bool p_case_sensitive);
-#endif // WEB_ENABLED
+ ZIPReader();
+ ~ZIPReader();
+};
-#endif // EMWS_CLIENT_H
+#endif // ZIP_READER_H
diff --git a/platform/android/android_input_handler.cpp b/platform/android/android_input_handler.cpp
index 454bcd2eda..c0b098cd7f 100644
--- a/platform/android/android_input_handler.cpp
+++ b/platform/android/android_input_handler.cpp
@@ -118,7 +118,7 @@ void AndroidInputHandler::process_key_event(int p_keycode, int p_physical_keycod
Input::get_singleton()->parse_input_event(ev);
}
-void AndroidInputHandler::_parse_all_touch(bool p_pressed) {
+void AndroidInputHandler::_parse_all_touch(bool p_pressed, bool p_double_tap) {
if (touch.size()) {
//end all if exist
for (int i = 0; i < touch.size(); i++) {
@@ -127,17 +127,18 @@ void AndroidInputHandler::_parse_all_touch(bool p_pressed) {
ev->set_index(touch[i].id);
ev->set_pressed(p_pressed);
ev->set_position(touch[i].pos);
+ ev->set_double_tap(p_double_tap);
Input::get_singleton()->parse_input_event(ev);
}
}
}
void AndroidInputHandler::_release_all_touch() {
- _parse_all_touch(false);
+ _parse_all_touch(false, false);
touch.clear();
}
-void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points) {
+void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap) {
switch (p_event) {
case AMOTION_EVENT_ACTION_DOWN: { //gesture begin
// Release any remaining touches or mouse event
@@ -151,7 +152,7 @@ void AndroidInputHandler::process_touch_event(int p_event, int p_pointer, const
}
//send touch
- _parse_all_touch(true);
+ _parse_all_touch(true, p_double_tap);
} break;
case AMOTION_EVENT_ACTION_MOVE: { //motion
diff --git a/platform/android/android_input_handler.h b/platform/android/android_input_handler.h
index 88490f0407..4da8a910c0 100644
--- a/platform/android/android_input_handler.h
+++ b/platform/android/android_input_handler.h
@@ -87,13 +87,13 @@ private:
void _release_mouse_event_info(bool p_source_mouse_relative = false);
- void _parse_all_touch(bool p_pressed);
+ void _parse_all_touch(bool p_pressed, bool p_double_tap);
void _release_all_touch();
public:
void process_mouse_event(int p_event_action, int p_event_android_buttons_mask, Point2 p_event_pos, Vector2 p_delta, bool p_double_click, bool p_source_mouse_relative);
- void process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points);
+ void process_touch_event(int p_event, int p_pointer, const Vector<TouchPos> &p_points, bool p_double_tap);
void process_magnify(Point2 p_pos, float p_factor);
void process_pan(Point2 p_pos, Vector2 p_delta);
void process_joy_event(JoypadEvent p_event);
diff --git a/platform/android/api/jni_singleton.h b/platform/android/api/jni_singleton.h
index 690fddae21..895bc70103 100644
--- a/platform/android/api/jni_singleton.h
+++ b/platform/android/api/jni_singleton.h
@@ -150,9 +150,8 @@ public:
env->DeleteLocalRef(arr);
} break;
-#ifndef _MSC_VER
-#warning This is missing 64 bits arrays, I have no idea how to do it in JNI
-#endif
+ // TODO: This is missing 64 bits arrays, I have no idea how to do it in JNI.
+
case Variant::DICTIONARY: {
jobject obj = env->CallObjectMethodA(instance, E->get().method, v);
ret = _jobject_to_variant(env, obj);
diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp
index 6f8efbf069..08369e735d 100644
--- a/platform/android/display_server_android.cpp
+++ b/platform/android/display_server_android.cpp
@@ -440,8 +440,8 @@ Vector<String> DisplayServerAndroid::get_rendering_drivers_func() {
return drivers;
}
-DisplayServer *DisplayServerAndroid::create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- DisplayServer *ds = memnew(DisplayServerAndroid(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerAndroid::create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
+ DisplayServer *ds = memnew(DisplayServerAndroid(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
if (r_error != OK) {
OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan versions.", "Unable to initialize Video driver");
}
@@ -485,7 +485,7 @@ void DisplayServerAndroid::notify_surface_changed(int p_width, int p_height) {
rect_changed_callback.callp(reinterpret_cast<const Variant **>(&sizep), 1, ret, ce);
}
-DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
rendering_driver = p_rendering_driver;
// TODO: rendering_driver is broken, change when different drivers are supported again
diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h
index 6e14ba3e23..a6bc88e048 100644
--- a/platform/android/display_server_android.h
+++ b/platform/android/display_server_android.h
@@ -194,7 +194,7 @@ public:
virtual void mouse_set_mode(MouseMode p_mode) override;
virtual MouseMode mouse_get_mode() const override;
- static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static Vector<String> get_rendering_drivers_func();
static void register_android_driver();
@@ -204,7 +204,7 @@ public:
virtual Point2i mouse_get_position() const override;
virtual MouseButton mouse_get_button_state() const override;
- DisplayServerAndroid(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ DisplayServerAndroid(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
~DisplayServerAndroid();
};
diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp
index 366bd1c48c..6426f95b42 100644
--- a/platform/android/export/export_plugin.cpp
+++ b/platform/android/export/export_plugin.cpp
@@ -1551,7 +1551,7 @@ String EditorExportPlatformAndroid::load_splash_refs(Ref<Image> &splash_image, R
print_verbose("Creating splash background color image.");
splash_bg_color_image.instantiate();
- splash_bg_color_image->create(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format());
+ splash_bg_color_image->initialize_data(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format());
splash_bg_color_image->fill(bg_color);
String processed_splash_config_xml = vformat(SPLASH_CONFIG_XML_CONTENT, bool_to_string(apply_filter));
@@ -2639,8 +2639,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP
}
if (user_data.libs.size() > 0) {
Ref<FileAccess> fa = FileAccess::open(GDNATIVE_LIBS_PATH, FileAccess::WRITE);
- JSON json;
- fa->store_string(json.stringify(user_data.libs, "\t"));
+ fa->store_string(JSON::stringify(user_data.libs, "\t"));
}
} else {
print_verbose("Saving apk expansion file..");
@@ -2902,20 +2901,22 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP
_load_image_data(splash_bg_color_image, data);
}
- for (int i = 0; i < icon_densities_count; ++i) {
- if (main_image.is_valid() && !main_image->is_empty()) {
- if (file == launcher_icons[i].export_path) {
- _process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data);
+ if (file.ends_with(".png") && file.contains("mipmap")) {
+ for (int i = 0; i < icon_densities_count; ++i) {
+ if (main_image.is_valid() && !main_image->is_empty()) {
+ if (file == launcher_icons[i].export_path) {
+ _process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data);
+ }
}
- }
- if (foreground.is_valid() && !foreground->is_empty()) {
- if (file == launcher_adaptive_icon_foregrounds[i].export_path) {
- _process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data);
+ if (foreground.is_valid() && !foreground->is_empty()) {
+ if (file == launcher_adaptive_icon_foregrounds[i].export_path) {
+ _process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data);
+ }
}
- }
- if (background.is_valid() && !background->is_empty()) {
- if (file == launcher_adaptive_icon_backgrounds[i].export_path) {
- _process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data);
+ if (background.is_valid() && !background->is_empty()) {
+ if (file == launcher_adaptive_icon_backgrounds[i].export_path) {
+ _process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data);
+ }
}
}
}
diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index 05608883d7..5a91e5ce32 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -276,6 +276,11 @@ task generateDevTemplate {
finalizedBy 'zipCustomBuild'
}
+task clean(type: Delete) {
+ dependsOn 'cleanGodotEditor'
+ dependsOn 'cleanGodotTemplates'
+}
+
/**
* Clean the generated editor artifacts.
*/
@@ -292,8 +297,6 @@ task cleanGodotEditor(type: Delete) {
// Delete the Godot editor apks in the Godot bin directory
delete("$binDir/android_editor.apk")
delete("$binDir/android_editor_dev.apk")
-
- finalizedBy getTasksByName("clean", true)
}
/**
@@ -321,5 +324,8 @@ task cleanGodotTemplates(type: Delete) {
delete("$binDir/godot-lib.template_debug.dev.aar")
delete("$binDir/godot-lib.template_release.aar")
- finalizedBy getTasksByName("clean", true)
+ // Cover deletion for the libs using the previous naming scheme
+ delete("$binDir/godot-lib.debug.aar")
+ delete("$binDir/godot-lib.dev.aar")
+ delete("$binDir/godot-lib.release.aar")
}
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 26aad867b1..33896ecb95 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
@@ -110,7 +110,7 @@ public class GodotLib {
/**
* Forward touch events.
*/
- public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions);
+ public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap);
/**
* Dispatch mouse events
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.kt b/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.kt
index 9715c31fc1..a7a57621de 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.kt
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.kt
@@ -55,18 +55,15 @@ internal class GodotGestureHandler : SimpleOnGestureListener(), OnScaleGestureLi
*/
var panningAndScalingEnabled = false
- private var doubleTapInProgress = false
+ private var nextDownIsDoubleTap = false
private var dragInProgress = false
private var scaleInProgress = false
private var contextClickInProgress = false
private var pointerCaptureInProgress = false
override fun onDown(event: MotionEvent): Boolean {
- // Don't send / register a down event while we're in the middle of a double-tap
- if (!doubleTapInProgress) {
- // Send the down event
- GodotInputHandler.handleMotionEvent(event)
- }
+ GodotInputHandler.handleMotionEvent(event.source, MotionEvent.ACTION_DOWN, event.buttonState, event.x, event.y, nextDownIsDoubleTap)
+ nextDownIsDoubleTap = false
return true
}
@@ -209,24 +206,14 @@ internal class GodotGestureHandler : SimpleOnGestureListener(), OnScaleGestureLi
override fun onDoubleTapEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_UP) {
- doubleTapInProgress = false
+ nextDownIsDoubleTap = false
+ GodotInputHandler.handleMotionEvent(event)
}
return true
}
override fun onDoubleTap(event: MotionEvent): Boolean {
- doubleTapInProgress = true
- val x = event.x
- val y = event.y
- val buttonMask =
- if (GodotInputHandler.isMouseEvent(event)) {
- event.buttonState
- } else {
- MotionEvent.BUTTON_PRIMARY
- }
- GodotInputHandler.handleMouseEvent(MotionEvent.ACTION_DOWN, buttonMask, x, y, true)
- GodotInputHandler.handleMouseEvent(MotionEvent.ACTION_UP, 0, x, y, false)
-
+ nextDownIsDoubleTap = true
return true
}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
index 03cb8034fa..d2f3c5aed2 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
@@ -438,15 +438,19 @@ public class GodotInputHandler implements InputManager.InputDeviceListener {
}
static boolean handleMotionEvent(int eventSource, int eventAction, int buttonsMask, float x, float y) {
- return handleMotionEvent(eventSource, eventAction, buttonsMask, x, y, 0, 0);
+ return handleMotionEvent(eventSource, eventAction, buttonsMask, x, y, false);
}
- static boolean handleMotionEvent(int eventSource, int eventAction, int buttonsMask, float x, float y, float deltaX, float deltaY) {
+ static boolean handleMotionEvent(int eventSource, int eventAction, int buttonsMask, float x, float y, boolean doubleTap) {
+ return handleMotionEvent(eventSource, eventAction, buttonsMask, x, y, 0, 0, doubleTap);
+ }
+
+ static boolean handleMotionEvent(int eventSource, int eventAction, int buttonsMask, float x, float y, float deltaX, float deltaY, boolean doubleTap) {
if (isMouseEvent(eventSource)) {
- return handleMouseEvent(eventAction, buttonsMask, x, y, deltaX, deltaY, false, false);
+ return handleMouseEvent(eventAction, buttonsMask, x, y, deltaX, deltaY, doubleTap, false);
}
- return handleTouchEvent(eventAction, x, y);
+ return handleTouchEvent(eventAction, x, y, doubleTap);
}
static boolean handleMouseEvent(final MotionEvent event) {
@@ -468,10 +472,6 @@ public class GodotInputHandler implements InputManager.InputDeviceListener {
return handleMouseEvent(eventAction, buttonsMask, x, y, 0, 0, false, false);
}
- static boolean handleMouseEvent(int eventAction, int buttonsMask, float x, float y, boolean doubleClick) {
- return handleMouseEvent(eventAction, buttonsMask, x, y, 0, 0, doubleClick, false);
- }
-
static boolean handleMouseEvent(int eventAction, int buttonsMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative) {
switch (eventAction) {
case MotionEvent.ACTION_CANCEL:
@@ -508,14 +508,14 @@ public class GodotInputHandler implements InputManager.InputDeviceListener {
final int action = event.getActionMasked();
final int actionPointerId = event.getPointerId(event.getActionIndex());
- return handleTouchEvent(action, actionPointerId, pointerCount, positions);
+ return handleTouchEvent(action, actionPointerId, pointerCount, positions, false);
}
- static boolean handleTouchEvent(int eventAction, float x, float y) {
- return handleTouchEvent(eventAction, 0, 1, new float[] { 0, x, y });
+ static boolean handleTouchEvent(int eventAction, float x, float y, boolean doubleTap) {
+ return handleTouchEvent(eventAction, 0, 1, new float[] { 0, x, y }, doubleTap);
}
- static boolean handleTouchEvent(int eventAction, int actionPointerId, int pointerCount, float[] positions) {
+ static boolean handleTouchEvent(int eventAction, int actionPointerId, int pointerCount, float[] positions, boolean doubleTap) {
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_CANCEL:
@@ -523,7 +523,7 @@ public class GodotInputHandler implements InputManager.InputDeviceListener {
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_POINTER_DOWN: {
- GodotLib.dispatchTouchEvent(eventAction, actionPointerId, pointerCount, positions);
+ GodotLib.dispatchTouchEvent(eventAction, actionPointerId, pointerCount, positions, doubleTap);
return true;
}
}
diff --git a/platform/android/java_godot_lib_jni.cpp b/platform/android/java_godot_lib_jni.cpp
index 04b69d5b86..5bf550a2b8 100644
--- a/platform/android/java_godot_lib_jni.cpp
+++ b/platform/android/java_godot_lib_jni.cpp
@@ -265,7 +265,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchMouseEvent(JN
}
// Called on the UI thread
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint pointer_count, jfloatArray position) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint pointer_count, jfloatArray position, jboolean p_double_tap) {
if (step.get() <= 0) {
return;
}
@@ -280,7 +280,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JN
points.push_back(tp);
}
- input_handler->process_touch_event(ev, pointer, points);
+ input_handler->process_touch_event(ev, pointer, points, p_double_tap);
}
// Called on the UI thread
diff --git a/platform/android/java_godot_lib_jni.h b/platform/android/java_godot_lib_jni.h
index 09fed15690..f3f2646bfb 100644
--- a/platform/android/java_godot_lib_jni.h
+++ b/platform/android/java_godot_lib_jni.h
@@ -46,7 +46,7 @@ JNIEXPORT jboolean JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env,
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);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchMouseEvent(JNIEnv *env, jclass clazz, jint p_event_type, jint p_button_mask, jfloat p_x, jfloat p_y, jfloat p_delta_x, jfloat p_delta_y, jboolean p_double_click, jboolean p_source_mouse_relative);
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint pointer_count, jfloatArray positions);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_dispatchTouchEvent(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint pointer_count, jfloatArray positions, jboolean p_double_tap);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnify(JNIEnv *env, jclass clazz, jfloat p_x, jfloat p_y, jfloat p_factor);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_pan(JNIEnv *env, jclass clazz, jfloat p_x, jfloat p_y, jfloat p_delta_x, jfloat p_delta_y);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv *env, jclass clazz, jint p_keycode, jint p_physical_keycode, jint p_unicode, jboolean p_pressed);
diff --git a/platform/android/jni_utils.cpp b/platform/android/jni_utils.cpp
index 193ef61264..d46b4f39de 100644
--- a/platform/android/jni_utils.cpp
+++ b/platform/android/jni_utils.cpp
@@ -167,9 +167,8 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant *p_a
v.obj = arr;
} break;
-#ifndef _MSC_VER
-#warning This is missing 64 bits arrays, I have no idea how to do it in JNI
-#endif
+
+ // TODO: This is missing 64 bits arrays, I have no idea how to do it in JNI.
default: {
v.val.i = 0;
diff --git a/platform/ios/display_server_ios.h b/platform/ios/display_server_ios.h
index f3624f24ab..da06ff7431 100644
--- a/platform/ios/display_server_ios.h
+++ b/platform/ios/display_server_ios.h
@@ -73,7 +73,7 @@ class DisplayServerIOS : public DisplayServer {
void perform_event(const Ref<InputEvent> &p_event);
- DisplayServerIOS(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ DisplayServerIOS(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
~DisplayServerIOS();
public:
@@ -82,7 +82,7 @@ public:
static DisplayServerIOS *get_singleton();
static void register_ios_driver();
- static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static Vector<String> get_rendering_drivers_func();
// MARK: - Events
diff --git a/platform/ios/display_server_ios.mm b/platform/ios/display_server_ios.mm
index d3a0f38463..b13561c511 100644
--- a/platform/ios/display_server_ios.mm
+++ b/platform/ios/display_server_ios.mm
@@ -50,7 +50,7 @@ DisplayServerIOS *DisplayServerIOS::get_singleton() {
return (DisplayServerIOS *)DisplayServer::get_singleton();
}
-DisplayServerIOS::DisplayServerIOS(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServerIOS::DisplayServerIOS(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
rendering_driver = p_rendering_driver;
// Init TTS
@@ -152,8 +152,8 @@ DisplayServerIOS::~DisplayServerIOS() {
#endif
}
-DisplayServer *DisplayServerIOS::create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- return memnew(DisplayServerIOS(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerIOS::create_func(const String &p_rendering_driver, WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
+ return memnew(DisplayServerIOS(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
}
Vector<String> DisplayServerIOS::get_rendering_drivers_func() {
@@ -235,6 +235,7 @@ void DisplayServerIOS::touch_press(int p_idx, int p_x, int p_y, bool p_pressed,
ev->set_index(p_idx);
ev->set_pressed(p_pressed);
ev->set_position(Vector2(p_x, p_y));
+ ev->set_double_tap(p_double_click);
perform_event(ev);
}
}
diff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cpp
index 74a57dc614..83b2012d3e 100644
--- a/platform/ios/export/export_plugin.cpp
+++ b/platform/ios/export/export_plugin.cpp
@@ -740,8 +740,7 @@ Error EditorExportPlatformIOS::_export_loading_screen_images(const Ref<EditorExp
img->resize(info.width, info.width / aspect_ratio);
}
}
- Ref<Image> new_img = memnew(Image);
- new_img->create(info.width, info.height, false, Image::FORMAT_RGBA8);
+ Ref<Image> new_img = Image::create_empty(info.width, info.height, false, Image::FORMAT_RGBA8);
new_img->fill(boot_bg_color);
_blend_and_rotate(new_img, img, false);
err = new_img->save_png(p_dest_dir + info.export_name);
@@ -755,8 +754,7 @@ Error EditorExportPlatformIOS::_export_loading_screen_images(const Ref<EditorExp
}
} else {
// Generate loading screen from the splash screen
- Ref<Image> img = memnew(Image);
- img->create(info.width, info.height, false, Image::FORMAT_RGBA8);
+ Ref<Image> img = Image::create_empty(info.width, info.height, false, Image::FORMAT_RGBA8);
img->fill(boot_bg_color);
Ref<Image> img_bs;
diff --git a/platform/ios/view_controller.mm b/platform/ios/view_controller.mm
index 43669d3f94..53c5d3d0b4 100644
--- a/platform/ios/view_controller.mm
+++ b/platform/ios/view_controller.mm
@@ -164,7 +164,11 @@
// MARK: Orientation
- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures {
- return UIRectEdgeAll;
+ if (GLOBAL_GET("display/window/ios/suppress_ui_gesture")) {
+ return UIRectEdgeAll;
+ } else {
+ return UIRectEdgeNone;
+ }
}
- (BOOL)shouldAutorotate {
@@ -206,7 +210,11 @@
}
- (BOOL)prefersStatusBarHidden {
- return YES;
+ if (GLOBAL_GET("display/window/ios/hide_status_bar")) {
+ return YES;
+ } else {
+ return NO;
+ }
}
- (BOOL)prefersHomeIndicatorAutoHidden {
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index 86ae1f2d9c..ac69f3806b 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -367,6 +367,7 @@ def configure(env: "Environment"):
# The default crash handler depends on glibc, so if the host uses
# a different libc (BSD libc, musl), fall back to libexecinfo.
print("Note: Using `execinfo=yes` for the crash handler as required on platforms where glibc is missing.")
+ env["execinfo"] = True
if env["execinfo"]:
env.Append(LIBS=["execinfo"])
diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp
index 5256d91a80..88c6500e10 100644
--- a/platform/linuxbsd/display_server_x11.cpp
+++ b/platform/linuxbsd/display_server_x11.cpp
@@ -126,7 +126,7 @@ bool DisplayServerX11::has_feature(Feature p_feature) const {
case FEATURE_WINDOW_TRANSPARENCY:
//case FEATURE_HIDPI:
case FEATURE_ICON:
- case FEATURE_NATIVE_ICON:
+ //case FEATURE_NATIVE_ICON:
case FEATURE_SWAP_BUFFERS:
#ifdef DBUS_ENABLED
case FEATURE_KEEP_SCREEN_ON:
@@ -1202,16 +1202,6 @@ float DisplayServerX11::screen_get_refresh_rate(int p_screen) const {
return SCREEN_REFRESH_RATE_FALLBACK;
}
-bool DisplayServerX11::screen_is_touchscreen(int p_screen) const {
- _THREAD_SAFE_METHOD_
-
-#ifndef _MSC_VER
-#warning Need to get from proper window
-#endif
-
- return DisplayServer::screen_is_touchscreen(p_screen);
-}
-
#ifdef DBUS_ENABLED
void DisplayServerX11::screen_set_keep_on(bool p_enable) {
if (screen_is_kept_on() == p_enable) {
@@ -1739,6 +1729,18 @@ void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) {
usleep(10000);
}
+
+ // Keep rendering context window size in sync
+#if defined(VULKAN_ENABLED)
+ if (context_vulkan) {
+ context_vulkan->window_resize(p_window, xwa.width, xwa.height);
+ }
+#endif
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ gl_manager->window_resize(p_window, xwa.width, xwa.height);
+ }
+#endif
}
Size2i DisplayServerX11::window_get_size(WindowID p_window) const {
@@ -4430,13 +4432,24 @@ Vector<String> DisplayServerX11::get_rendering_drivers_func() {
return drivers;
}
-DisplayServer *DisplayServerX11::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerX11::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
+ DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
if (r_error != OK) {
- OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.\n"
- "Please update your drivers or if you have a very old or integrated GPU, upgrade it.\n"
- "If you have updated your graphics drivers recently, try rebooting.",
- "Unable to initialize Video driver");
+ if (p_rendering_driver == "vulkan") {
+ String executable_name = OS::get_singleton()->get_executable_path().get_file();
+ OS::get_singleton()->alert("Your video card driver does not support the selected Vulkan version.\n"
+ "Please try updating your GPU driver or try using the OpenGL 3 driver.\n"
+ "You can enable the OpenGL 3 driver by starting the engine from the\n"
+ "command line with the command:\n'./" +
+ executable_name + " --rendering-driver opengl3'.\n "
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ } else {
+ OS::get_singleton()->alert("Your video card driver does not support the selected OpenGL version.\n"
+ "Please try updating your GPU driver.\n"
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ }
}
return ds;
}
@@ -4680,7 +4693,7 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, V
return id;
}
-DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
r_error = OK;
@@ -4907,6 +4920,11 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode
Point2i window_position(
(screen_get_size(0).width - p_resolution.width) / 2,
(screen_get_size(0).height - p_resolution.height) / 2);
+
+ if (p_position != nullptr) {
+ window_position = *p_position;
+ }
+
WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution));
if (main_window == INVALID_WINDOW_ID) {
r_error = ERR_CANT_CREATE;
diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h
index a5fa7613bc..9ef8f71c05 100644
--- a/platform/linuxbsd/display_server_x11.h
+++ b/platform/linuxbsd/display_server_x11.h
@@ -349,7 +349,6 @@ public:
virtual Rect2i screen_get_usable_rect(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual float screen_get_refresh_rate(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
- virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
#if defined(DBUS_ENABLED)
virtual void screen_set_keep_on(bool p_enable) override;
@@ -445,12 +444,12 @@ public:
virtual void set_native_icon(const String &p_filename) override;
virtual void set_icon(const Ref<Image> &p_icon) override;
- static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static Vector<String> get_rendering_drivers_func();
static void register_x11_driver();
- DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
~DisplayServerX11();
};
diff --git a/platform/linuxbsd/godot_linuxbsd.cpp b/platform/linuxbsd/godot_linuxbsd.cpp
index 91a260182e..fa5e20891c 100644
--- a/platform/linuxbsd/godot_linuxbsd.cpp
+++ b/platform/linuxbsd/godot_linuxbsd.cpp
@@ -69,6 +69,7 @@ int main(int argc, char *argv[]) {
}
if (Main::start()) {
+ os.set_exit_code(EXIT_SUCCESS);
os.run(); // it is actually the OS that decides how to run
}
Main::cleanup();
diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp
index 4cbd9722ad..11b667fcef 100644
--- a/platform/linuxbsd/os_linuxbsd.cpp
+++ b/platform/linuxbsd/os_linuxbsd.cpp
@@ -34,6 +34,11 @@
#include "main/main.h"
#include "servers/display_server.h"
+#include "modules/modules_enabled.gen.h" // For regex.
+#ifdef MODULE_REGEX_ENABLED
+#include "modules/regex/regex.h"
+#endif
+
#ifdef X11_ENABLED
#include "display_server_x11.h"
#endif
@@ -240,6 +245,204 @@ String OS_LinuxBSD::get_version() const {
return uts.version;
}
+Vector<String> OS_LinuxBSD::get_video_adapter_driver_info() const {
+ if (RenderingServer::get_singleton()->get_rendering_device() == nullptr) {
+ return Vector<String>();
+ }
+
+ const String rendering_device_name = RenderingServer::get_singleton()->get_rendering_device()->get_device_name(); // e.g. `NVIDIA GeForce GTX 970`
+ const String rendering_device_vendor = RenderingServer::get_singleton()->get_rendering_device()->get_device_vendor_name(); // e.g. `NVIDIA`
+ const String card_name = rendering_device_name.trim_prefix(rendering_device_vendor).strip_edges(); // -> `GeForce GTX 970`
+
+ String vendor_device_id_mappings;
+ List<String> lspci_args;
+ lspci_args.push_back("-n");
+ Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", lspci_args, &vendor_device_id_mappings);
+ if (err != OK || vendor_device_id_mappings.is_empty()) {
+ return Vector<String>();
+ }
+
+ // Usually found under "VGA", but for example NVIDIA mobile/laptop adapters are often listed under "3D" and some AMD adapters are under "Display".
+ const String dc_vga = "0300"; // VGA compatible controller
+ const String dc_display = "0302"; // Display controller
+ const String dc_3d = "0380"; // 3D controller
+
+ // splitting results by device class allows prioritizing, if multiple devices are found.
+ Vector<String> class_vga_device_candidates;
+ Vector<String> class_display_device_candidates;
+ Vector<String> class_3d_device_candidates;
+
+#ifdef MODULE_REGEX_ENABLED
+ RegEx regex_id_format = RegEx();
+ regex_id_format.compile("^[a-f0-9]{4}:[a-f0-9]{4}$"); // e.g. `10de:13c2`; IDs are always in hexadecimal
+#endif
+
+ Vector<String> value_lines = vendor_device_id_mappings.split("\n", false); // example: `02:00.0 0300: 10de:13c2 (rev a1)`
+ for (const String &line : value_lines) {
+ Vector<String> columns = line.split(" ", false);
+ if (columns.size() < 3) {
+ continue;
+ }
+ String device_class = columns[1].trim_suffix(":");
+ String vendor_device_id_mapping = columns[2];
+
+#ifdef MODULE_REGEX_ENABLED
+ if (regex_id_format.search(vendor_device_id_mapping).is_null()) {
+ continue;
+ }
+#endif
+
+ if (device_class == dc_vga) {
+ class_vga_device_candidates.push_back(vendor_device_id_mapping);
+ } else if (device_class == dc_display) {
+ class_display_device_candidates.push_back(vendor_device_id_mapping);
+ } else if (device_class == dc_3d) {
+ class_3d_device_candidates.push_back(vendor_device_id_mapping);
+ }
+ }
+
+ // Check results against currently used device (`card_name`), in case the user has multiple graphics cards.
+ const String device_lit = "Device"; // line of interest
+ class_vga_device_candidates = OS_LinuxBSD::lspci_device_filter(class_vga_device_candidates, dc_vga, device_lit, card_name);
+ class_display_device_candidates = OS_LinuxBSD::lspci_device_filter(class_display_device_candidates, dc_display, device_lit, card_name);
+ class_3d_device_candidates = OS_LinuxBSD::lspci_device_filter(class_3d_device_candidates, dc_3d, device_lit, card_name);
+
+ // Get driver names and filter out invalid ones, because some adapters are dummys used only for passthrough.
+ // And they have no indicator besides certain driver names.
+ const String kernel_lit = "Kernel driver in use"; // line of interest
+ const String dummys = "vfio"; // for e.g. pci passthrough dummy kernel driver `vfio-pci`
+ Vector<String> class_vga_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_vga_device_candidates, kernel_lit, dummys);
+ Vector<String> class_display_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_display_device_candidates, kernel_lit, dummys);
+ Vector<String> class_3d_device_drivers = OS_LinuxBSD::lspci_get_device_value(class_3d_device_candidates, kernel_lit, dummys);
+
+ static String driver_name;
+ static String driver_version;
+
+ // Use first valid value:
+ for (const String &driver : class_3d_device_drivers) {
+ driver_name = driver;
+ break;
+ }
+ if (driver_name.is_empty()) {
+ for (const String &driver : class_display_device_drivers) {
+ driver_name = driver;
+ break;
+ }
+ }
+ if (driver_name.is_empty()) {
+ for (const String &driver : class_vga_device_drivers) {
+ driver_name = driver;
+ break;
+ }
+ }
+
+ Vector<String> info;
+ info.push_back(driver_name);
+
+ String modinfo;
+ List<String> modinfo_args;
+ modinfo_args.push_back(driver_name);
+ err = const_cast<OS_LinuxBSD *>(this)->execute("modinfo", modinfo_args, &modinfo);
+ if (err != OK || modinfo.is_empty()) {
+ info.push_back(""); // So that this method always either returns an empty array, or an array of length 2.
+ return info;
+ }
+ Vector<String> lines = modinfo.split("\n", false);
+ for (const String &line : lines) {
+ Vector<String> columns = line.split(":", false, 1);
+ if (columns.size() < 2) {
+ continue;
+ }
+ if (columns[0].strip_edges() == "version") {
+ driver_version = columns[1].strip_edges(); // example value: `510.85.02` on Linux/BSD
+ break;
+ }
+ }
+
+ info.push_back(driver_version);
+
+ return info;
+}
+
+Vector<String> OS_LinuxBSD::lspci_device_filter(Vector<String> vendor_device_id_mapping, String class_suffix, String check_column, String whitelist) const {
+ // NOTE: whitelist can be changed to `Vector<String>`, if the need arises.
+ const String sep = ":";
+ Vector<String> devices;
+ for (const String &mapping : vendor_device_id_mapping) {
+ String device;
+ List<String> d_args;
+ d_args.push_back("-d");
+ d_args.push_back(mapping + sep + class_suffix);
+ d_args.push_back("-vmm");
+ Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2:0300 -vmm`
+ if (err != OK) {
+ return Vector<String>();
+ } else if (device.is_empty()) {
+ continue;
+ }
+
+ Vector<String> device_lines = device.split("\n", false);
+ for (const String &line : device_lines) {
+ Vector<String> columns = line.split(":", false, 1);
+ if (columns.size() < 2) {
+ continue;
+ }
+ if (columns[0].strip_edges() == check_column) {
+ // for `column[0] == "Device"` this may contain `GM204 [GeForce GTX 970]`
+ bool is_valid = true;
+ if (!whitelist.is_empty()) {
+ is_valid = columns[1].strip_edges().contains(whitelist);
+ }
+ if (is_valid) {
+ devices.push_back(mapping);
+ }
+ break;
+ }
+ }
+ }
+ return devices;
+}
+
+Vector<String> OS_LinuxBSD::lspci_get_device_value(Vector<String> vendor_device_id_mapping, String check_column, String blacklist) const {
+ // NOTE: blacklist can be changed to `Vector<String>`, if the need arises.
+ const String sep = ":";
+ Vector<String> values;
+ for (const String &mapping : vendor_device_id_mapping) {
+ String device;
+ List<String> d_args;
+ d_args.push_back("-d");
+ d_args.push_back(mapping);
+ d_args.push_back("-k");
+ Error err = const_cast<OS_LinuxBSD *>(this)->execute("lspci", d_args, &device); // e.g. `lspci -d 10de:13c2 -k`
+ if (err != OK) {
+ return Vector<String>();
+ } else if (device.is_empty()) {
+ continue;
+ }
+
+ Vector<String> device_lines = device.split("\n", false);
+ for (const String &line : device_lines) {
+ Vector<String> columns = line.split(":", false, 1);
+ if (columns.size() < 2) {
+ continue;
+ }
+ if (columns[0].strip_edges() == check_column) {
+ // for `column[0] == "Kernel driver in use"` this may contain `nvidia`
+ bool is_valid = true;
+ const String value = columns[1].strip_edges();
+ if (!blacklist.is_empty()) {
+ is_valid = !value.contains(blacklist);
+ }
+ if (is_valid) {
+ values.push_back(value);
+ }
+ break;
+ }
+ }
+ }
+ return values;
+}
+
Error OS_LinuxBSD::shell_open(String p_uri) {
Error ok;
int err_code;
diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h
index 722d83ba19..aea04c1363 100644
--- a/platform/linuxbsd/os_linuxbsd.h
+++ b/platform/linuxbsd/os_linuxbsd.h
@@ -69,6 +69,9 @@ class OS_LinuxBSD : public OS_Unix {
String get_systemd_os_release_info_value(const String &key) const;
+ Vector<String> lspci_device_filter(Vector<String> vendor_device_id_mapping, String class_suffix, String check_column, String whitelist) const;
+ Vector<String> lspci_get_device_value(Vector<String> vendor_device_id_mapping, String check_column, String blacklist) const;
+
protected:
virtual void initialize() override;
virtual void finalize() override;
@@ -82,6 +85,8 @@ public:
virtual String get_distribution_name() const override;
virtual String get_version() const override;
+ virtual Vector<String> get_video_adapter_driver_info() const override;
+
virtual MainLoop *get_main_loop() const override;
virtual uint64_t get_embedded_pck_offset() const override;
diff --git a/platform/macos/display_server_macos.h b/platform/macos/display_server_macos.h
index e72273a681..618da6b388 100644
--- a/platform/macos/display_server_macos.h
+++ b/platform/macos/display_server_macos.h
@@ -401,7 +401,7 @@ public:
virtual bool window_minimize_on_title_dbl_click() const override;
virtual void window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window = MAIN_WINDOW_ID) override;
- virtual Vector2i window_get_safe_title_margins(WindowID p_window = MAIN_WINDOW_ID) const override;
+ virtual Vector3i window_get_safe_title_margins(WindowID p_window = MAIN_WINDOW_ID) const override;
virtual Point2i ime_get_selection() const override;
virtual String ime_get_text() const override;
@@ -430,12 +430,12 @@ public:
virtual void set_native_icon(const String &p_filename) override;
virtual void set_icon(const Ref<Image> &p_icon) override;
- static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static Vector<String> get_rendering_drivers_func();
static void register_macos_driver();
- DisplayServerMacOS(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ DisplayServerMacOS(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
~DisplayServerMacOS();
};
diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm
index f980129081..49633e6efa 100644
--- a/platform/macos/display_server_macos.mm
+++ b/platform/macos/display_server_macos.mm
@@ -2655,25 +2655,33 @@ void DisplayServerMacOS::window_set_window_buttons_offset(const Vector2i &p_offs
ERR_FAIL_COND(!windows.has(p_window));
WindowData &wd = windows[p_window];
- wd.wb_offset = p_offset;
+ float scale = screen_get_max_scale();
+ wd.wb_offset = p_offset / scale;
+ wd.wb_offset.x = MAX(wd.wb_offset.x, 12);
+ wd.wb_offset.y = MAX(wd.wb_offset.y, 12);
+ if (wd.window_button_view) {
+ [wd.window_button_view setOffset:NSMakePoint(wd.wb_offset.x, wd.wb_offset.y)];
+ }
}
-Vector2i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const {
+Vector3i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const {
_THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Vector2i());
+ ERR_FAIL_COND_V(!windows.has(p_window), Vector3i());
const WindowData &wd = windows[p_window];
if (!wd.window_button_view) {
- return Vector2i();
+ return Vector3i();
}
- float max_x = wd.wb_offset.x + [wd.window_button_view frame].size.width;
+ float scale = screen_get_max_scale();
+ float max_x = [wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width;
+ float max_y = [wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height;
if ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft) {
- return Vector2i(0, max_x * screen_get_max_scale());
+ return Vector3i(0, max_x * scale, max_y * scale);
} else {
- return Vector2i(max_x * screen_get_max_scale(), 0);
+ return Vector3i(max_x * scale, 0, max_y * scale);
}
}
@@ -3397,10 +3405,29 @@ void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) {
[NSApp setApplicationIconImage:nsimg];
}
-DisplayServer *DisplayServerMacOS::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- DisplayServer *ds = memnew(DisplayServerMacOS(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerMacOS::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
+ DisplayServer *ds = memnew(DisplayServerMacOS(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
if (r_error != OK) {
- OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.", "Unable to initialize Video driver");
+ if (p_rendering_driver == "vulkan") {
+ String executable_command;
+ if (OS::get_singleton()->get_bundle_resource_dir() == OS::get_singleton()->get_executable_path().get_base_dir()) {
+ executable_command = vformat("%s --rendering-driver opengl3", OS::get_singleton()->get_executable_path());
+ } else {
+ executable_command = vformat("open %s --args --rendering-driver opengl3", OS::get_singleton()->get_bundle_resource_dir().path_join("../..").simplify_path());
+ }
+ OS::get_singleton()->alert("Your video card driver does not support the selected Vulkan version.\n"
+ "Please try updating your GPU driver or try using the OpenGL 3 driver.\n"
+ "You can enable the OpenGL 3 driver by starting the engine from the\n"
+ "command line with the command: '" +
+ executable_command + "'.\n"
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ } else {
+ OS::get_singleton()->alert("Your video card driver does not support the selected OpenGL version.\n"
+ "Please try updating your GPU driver.\n"
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ }
}
return ds;
}
@@ -3548,7 +3575,7 @@ bool DisplayServerMacOS::mouse_process_popups(bool p_close) {
return closed;
}
-DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
r_error = OK;
@@ -3657,6 +3684,11 @@ DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowM
Point2i window_position(
screen_get_position(0).x + (screen_get_size(0).width - p_resolution.width) / 2,
screen_get_position(0).y + (screen_get_size(0).height - p_resolution.height) / 2);
+
+ if (p_position != nullptr) {
+ window_position = *p_position;
+ }
+
WindowID main_window = _create_window(p_mode, p_vsync_mode, Rect2i(window_position, p_resolution));
ERR_FAIL_COND(main_window == INVALID_WINDOW_ID);
for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
diff --git a/platform/macos/export/export_plugin.cpp b/platform/macos/export/export_plugin.cpp
index 070830c486..f5f64f9663 100644
--- a/platform/macos/export/export_plugin.cpp
+++ b/platform/macos/export/export_plugin.cpp
@@ -31,6 +31,8 @@
#include "export_plugin.h"
#include "codesign.h"
+#include "lipo.h"
+#include "macho.h"
#include "core/string/translation.h"
#include "editor/editor_node.h"
@@ -754,6 +756,7 @@ Error EditorExportPlatformMacOS::_code_sign_directory(const Ref<EditorExportPres
if (extensions_to_sign.is_empty()) {
extensions_to_sign.push_back("dylib");
extensions_to_sign.push_back("framework");
+ extensions_to_sign.push_back("");
}
Error dir_access_error;
@@ -778,6 +781,10 @@ Error EditorExportPlatformMacOS::_code_sign_directory(const Ref<EditorExportPres
if (code_sign_error != OK) {
return code_sign_error;
}
+ if (is_executable(current_file_path)) {
+ // chmod with 0755 if the file is executable.
+ FileAccess::set_unix_permissions(current_file_path, 0755);
+ }
} else if (dir_access->current_is_dir()) {
Error code_sign_error{ _code_sign_directory(p_preset, current_file_path, p_ent_path, p_should_error_on_non_code) };
if (code_sign_error != OK) {
@@ -799,6 +806,14 @@ Error EditorExportPlatformMacOS::_copy_and_sign_files(Ref<DirAccess> &dir_access
const String &p_in_app_path, bool p_sign_enabled,
const Ref<EditorExportPreset> &p_preset, const String &p_ent_path,
bool p_should_error_on_non_code_sign) {
+ static Vector<String> extensions_to_sign;
+
+ if (extensions_to_sign.is_empty()) {
+ extensions_to_sign.push_back("dylib");
+ extensions_to_sign.push_back("framework");
+ extensions_to_sign.push_back("");
+ }
+
Error err{ OK };
if (dir_access->dir_exists(p_src_path)) {
#ifndef UNIX_ENABLED
@@ -818,7 +833,13 @@ Error EditorExportPlatformMacOS::_copy_and_sign_files(Ref<DirAccess> &dir_access
// If it is a directory, find and sign all dynamic libraries.
err = _code_sign_directory(p_preset, p_in_app_path, p_ent_path, p_should_error_on_non_code_sign);
} else {
- err = _code_sign(p_preset, p_in_app_path, p_ent_path, false);
+ if (extensions_to_sign.find(p_in_app_path.get_extension()) > -1) {
+ err = _code_sign(p_preset, p_in_app_path, p_ent_path, false);
+ }
+ if (is_executable(p_in_app_path)) {
+ // chmod with 0755 if the file is executable.
+ FileAccess::set_unix_permissions(p_in_app_path, 0755);
+ }
}
}
return err;
@@ -877,6 +898,17 @@ Error EditorExportPlatformMacOS::_create_dmg(const String &p_dmg_path, const Str
return OK;
}
+bool EditorExportPlatformMacOS::is_shbang(const String &p_path) const {
+ Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("Can't open file: \"%s\".", p_path));
+ uint16_t magic = fb->get_16();
+ return (magic == 0x2123);
+}
+
+bool EditorExportPlatformMacOS::is_executable(const String &p_path) const {
+ return MachO::is_macho(p_path) || LipO::is_lipo(p_path) || is_shbang(p_path);
+}
+
Error EditorExportPlatformMacOS::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) {
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
if (f.is_null()) {
@@ -1158,11 +1190,8 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
// Now process our template.
bool found_binary = false;
- Vector<String> dylibs_found;
while (ret == UNZ_OK && err == OK) {
- bool is_execute = false;
-
// Get filename.
unz_file_info info;
char fname[16384];
@@ -1219,7 +1248,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
continue; // skip
}
found_binary = true;
- is_execute = true;
file = "Contents/MacOS/" + pkg_name;
}
@@ -1251,25 +1279,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
}
if (data.size() > 0) {
- if (file.find("/data.mono.macos.release_debug." + architecture + "/") != -1) {
- if (!p_debug) {
- ret = unzGoToNextFile(src_pkg_zip);
- continue; // skip
- }
- file = file.replace("/data.mono.macos.release_debug." + architecture + "/", "/GodotSharp/");
- }
- if (file.find("/data.mono.macos.release." + architecture + "/") != -1) {
- if (p_debug) {
- ret = unzGoToNextFile(src_pkg_zip);
- continue; // skip
- }
- file = file.replace("/data.mono.macos.release." + architecture + "/", "/GodotSharp/");
- }
-
- if (file.ends_with(".dylib")) {
- dylibs_found.push_back(file);
- }
-
print_verbose("ADDING: " + file + " size: " + itos(data.size()));
// Write it into our application bundle.
@@ -1285,7 +1294,7 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
if (f.is_valid()) {
f->store_buffer(data.ptr(), data.size());
f.unref();
- if (is_execute) {
+ if (is_executable(file)) {
// chmod with 0755 if the file is executable.
FileAccess::set_unix_permissions(file, 0755);
}
@@ -1324,12 +1333,35 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
return ERR_SKIP;
}
+ // See if we can code sign our new package.
+ bool sign_enabled = (p_preset->get("codesign/codesign").operator int() > 0);
+ bool ad_hoc = false;
+ int codesign_tool = p_preset->get("codesign/codesign");
+ switch (codesign_tool) {
+ case 1: { // built-in ad-hoc
+ ad_hoc = true;
+ } break;
+ case 2: { // "rcodesign"
+ ad_hoc = p_preset->get("codesign/certificate_file").operator String().is_empty() || p_preset->get("codesign/certificate_password").operator String().is_empty();
+ } break;
+#ifdef MACOS_ENABLED
+ case 3: { // "codesign"
+ ad_hoc = (p_preset->get("codesign/identity") == "" || p_preset->get("codesign/identity") == "-");
+ } break;
+#endif
+ default: {
+ };
+ }
+
String pack_path = tmp_app_path_name + "/Contents/Resources/" + pkg_name + ".pck";
Vector<SharedObject> shared_objects;
err = save_pack(p_preset, p_debug, pack_path, &shared_objects);
- // See if we can code sign our new package.
- bool sign_enabled = (p_preset->get("codesign/codesign").operator int() > 0);
+ bool lib_validation = p_preset->get("codesign/entitlements/disable_library_validation");
+ if (!shared_objects.is_empty() && sign_enabled && ad_hoc && !lib_validation) {
+ add_message(EXPORT_MESSAGE_INFO, TTR("Entitlements Modified"), TTR("Ad-hoc signed applications require the 'Disable Library Validation' entitlement to load dynamic libraries."));
+ lib_validation = true;
+ }
String ent_path = p_preset->get("codesign/entitlements/custom_file");
String hlp_ent_path = EditorPaths::get_singleton()->get_cache_dir().path_join(pkg_name + "_helper.entitlements");
@@ -1365,7 +1397,7 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
}
}
- if ((bool)p_preset->get("codesign/entitlements/disable_library_validation")) {
+ if (lib_validation) {
ent_f->store_line("<key>com.apple.security.cs.disable-library-validation</key>");
ent_f->store_line("<true/>");
}
@@ -1495,32 +1527,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
}
}
- bool ad_hoc = false;
- int codesign_tool = p_preset->get("codesign/codesign");
- switch (codesign_tool) {
- case 1: { // built-in ad-hoc
- ad_hoc = true;
- } break;
- case 2: { // "rcodesign"
- ad_hoc = p_preset->get("codesign/certificate_file").operator String().is_empty() || p_preset->get("codesign/certificate_password").operator String().is_empty();
- } break;
-#ifdef MACOS_ENABLED
- case 3: { // "codesign"
- ad_hoc = (p_preset->get("codesign/identity") == "" || p_preset->get("codesign/identity") == "-");
- } break;
-#endif
- default: {
- };
- }
-
- if (err == OK) {
- bool lib_validation = p_preset->get("codesign/entitlements/disable_library_validation");
- if ((!dylibs_found.is_empty() || !shared_objects.is_empty()) && sign_enabled && ad_hoc && !lib_validation) {
- add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Ad-hoc signed applications require the 'Disable Library Validation' entitlement to load dynamic libraries."));
- err = ERR_CANT_CREATE;
- }
- }
-
if (err == OK) {
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
for (int i = 0; i < shared_objects.size(); i++) {
@@ -1529,8 +1535,9 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
String path_in_app = tmp_app_path_name + "/Contents/Frameworks/" + src_path.get_file();
err = _copy_and_sign_files(da, src_path, path_in_app, sign_enabled, p_preset, ent_path, true);
} else {
- String path_in_app = tmp_app_path_name.path_join(shared_objects[i].target).path_join(src_path.get_file());
- err = _copy_and_sign_files(da, src_path, path_in_app, sign_enabled, p_preset, ent_path, false);
+ String path_in_app = tmp_app_path_name.path_join(shared_objects[i].target);
+ tmp_app_dir->make_dir_recursive(path_in_app);
+ err = _copy_and_sign_files(da, src_path, path_in_app.path_join(src_path.get_file()), sign_enabled, p_preset, ent_path, false);
}
if (err != OK) {
break;
@@ -1546,14 +1553,6 @@ Error EditorExportPlatformMacOS::export_project(const Ref<EditorExportPreset> &p
}
}
- if (sign_enabled) {
- for (int i = 0; i < dylibs_found.size(); i++) {
- if (err == OK) {
- err = _code_sign(p_preset, tmp_app_path_name + "/" + dylibs_found[i], ent_path, false);
- }
- }
- }
-
if (err == OK && sign_enabled) {
if (ep.step(TTR("Code signing bundle"), 2)) {
return ERR_SKIP;
@@ -1683,8 +1682,6 @@ void EditorExportPlatformMacOS::_zip_folder_recursive(zipFile &p_zip, const Stri
} else if (da->current_is_dir()) {
_zip_folder_recursive(p_zip, p_root_path, p_folder.path_join(f), p_pkg_name);
} else {
- bool is_executable = (p_folder.ends_with("MacOS") && (f == p_pkg_name)) || p_folder.ends_with("Helpers") || f.ends_with(".command");
-
OS::DateTime dt = OS::get_singleton()->get_datetime();
zip_fileinfo zipfi;
@@ -1698,7 +1695,7 @@ void EditorExportPlatformMacOS::_zip_folder_recursive(zipFile &p_zip, const Stri
// 0100000: regular file type
// 0000755: permissions rwxr-xr-x
// 0000644: permissions rw-r--r--
- uint32_t _mode = (is_executable ? 0100755 : 0100644);
+ uint32_t _mode = (is_executable(dir.path_join(f)) ? 0100755 : 0100644);
zipfi.external_fa = (_mode << 16L) | !(_mode & 0200);
zipfi.internal_fa = 0;
diff --git a/platform/macos/export/export_plugin.h b/platform/macos/export/export_plugin.h
index 87790129d3..b6ad587caa 100644
--- a/platform/macos/export/export_plugin.h
+++ b/platform/macos/export/export_plugin.h
@@ -97,6 +97,7 @@ class EditorExportPlatformMacOS : public EditorExportPlatform {
return true;
}
+ bool is_shbang(const String &p_path) const;
protected:
virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const override;
@@ -108,6 +109,7 @@ public:
virtual String get_os_name() const override { return "macOS"; }
virtual Ref<Texture2D> get_logo() const override { return logo; }
+ virtual bool is_executable(const String &p_path) const override;
virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override {
List<String> list;
if (use_dmg()) {
diff --git a/platform/macos/export/lipo.cpp b/platform/macos/export/lipo.cpp
index 82baf18c52..76d4eee418 100644
--- a/platform/macos/export/lipo.cpp
+++ b/platform/macos/export/lipo.cpp
@@ -28,12 +28,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "modules/modules_enabled.gen.h" // For regex.
-
#include "lipo.h"
-#ifdef MODULE_REGEX_ENABLED
-
bool LipO::is_lipo(const String &p_path) {
Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("LipO: Can't open file: \"%s\".", p_path));
@@ -232,5 +228,3 @@ void LipO::close() {
LipO::~LipO() {
close();
}
-
-#endif // MODULE_REGEX_ENABLED
diff --git a/platform/macos/export/lipo.h b/platform/macos/export/lipo.h
index 6378f9899c..bd8b7f6f2c 100644
--- a/platform/macos/export/lipo.h
+++ b/platform/macos/export/lipo.h
@@ -35,12 +35,9 @@
#include "core/io/file_access.h"
#include "core/object/ref_counted.h"
-#include "modules/modules_enabled.gen.h" // For regex.
#include "macho.h"
-#ifdef MODULE_REGEX_ENABLED
-
class LipO : public RefCounted {
struct FatArch {
uint32_t cputype;
@@ -71,6 +68,4 @@ public:
~LipO();
};
-#endif // MODULE_REGEX_ENABLED
-
#endif // MACOS_LIPO_H
diff --git a/platform/macos/export/macho.cpp b/platform/macos/export/macho.cpp
index 97289e408d..642d99e098 100644
--- a/platform/macos/export/macho.cpp
+++ b/platform/macos/export/macho.cpp
@@ -28,12 +28,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "modules/modules_enabled.gen.h" // For regex.
-
#include "macho.h"
-#ifdef MODULE_REGEX_ENABLED
-
uint32_t MachO::seg_align(uint64_t p_vmaddr, uint32_t p_min, uint32_t p_max) {
uint32_t salign = p_max;
if (p_vmaddr != 0) {
@@ -544,5 +540,3 @@ bool MachO::set_signature_size(uint64_t p_size) {
}
return true;
}
-
-#endif // MODULE_REGEX_ENABLED
diff --git a/platform/macos/export/macho.h b/platform/macos/export/macho.h
index 0d42a7013f..0c954e66b1 100644
--- a/platform/macos/export/macho.h
+++ b/platform/macos/export/macho.h
@@ -37,9 +37,6 @@
#include "core/crypto/crypto_core.h"
#include "core/io/file_access.h"
#include "core/object/ref_counted.h"
-#include "modules/modules_enabled.gen.h" // For regex.
-
-#ifdef MODULE_REGEX_ENABLED
class MachO : public RefCounted {
struct MachHeader {
@@ -210,6 +207,4 @@ public:
bool set_signature_size(uint64_t p_size);
};
-#endif // MODULE_REGEX_ENABLED
-
#endif // MACOS_MACHO_H
diff --git a/platform/macos/export/plist.cpp b/platform/macos/export/plist.cpp
index 36de9dd34b..cad014e65b 100644
--- a/platform/macos/export/plist.cpp
+++ b/platform/macos/export/plist.cpp
@@ -28,12 +28,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "modules/modules_enabled.gen.h" // For regex.
-
#include "plist.h"
-#ifdef MODULE_REGEX_ENABLED
-
Ref<PListNode> PListNode::new_array() {
Ref<PListNode> node = memnew(PListNode());
ERR_FAIL_COND_V(node.is_null(), Ref<PListNode>());
@@ -566,5 +562,3 @@ String PList::save_text() const {
Ref<PListNode> PList::get_root() {
return root;
}
-
-#endif // MODULE_REGEX_ENABLED
diff --git a/platform/macos/export/plist.h b/platform/macos/export/plist.h
index b3c51a9635..97331a3629 100644
--- a/platform/macos/export/plist.h
+++ b/platform/macos/export/plist.h
@@ -35,9 +35,6 @@
#include "core/crypto/crypto_core.h"
#include "core/io/file_access.h"
-#include "modules/modules_enabled.gen.h" // For regex.
-
-#ifdef MODULE_REGEX_ENABLED
class PListNode;
@@ -111,6 +108,4 @@ public:
~PListNode() {}
};
-#endif // MODULE_REGEX_ENABLED
-
#endif // MACOS_PLIST_H
diff --git a/platform/macos/godot_button_view.h b/platform/macos/godot_button_view.h
index e7627a9e9b..ef1d5fe412 100644
--- a/platform/macos/godot_button_view.h
+++ b/platform/macos/godot_button_view.h
@@ -42,10 +42,15 @@
CGFloat spacing;
bool mouse_in_group;
bool rtl;
+ NSButton *close_button;
+ NSButton *miniaturize_button;
+ NSButton *zoom_button;
}
- (void)initButtons:(CGFloat)button_spacing offset:(NSPoint)button_offset rtl:(bool)is_rtl;
- (void)displayButtons;
+- (void)setOffset:(NSPoint)button_offset;
+- (NSPoint)getOffset;
@end
diff --git a/platform/macos/godot_button_view.mm b/platform/macos/godot_button_view.mm
index 9106f0b0db..7d380cbe11 100644
--- a/platform/macos/godot_button_view.mm
+++ b/platform/macos/godot_button_view.mm
@@ -40,6 +40,9 @@
spacing = 20;
mouse_in_group = false;
rtl = false;
+ close_button = nullptr;
+ miniaturize_button = nullptr;
+ zoom_button = nullptr;
return self;
}
@@ -48,15 +51,15 @@
spacing = button_spacing;
rtl = is_rtl;
- NSButton *close_button = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:NSWindowStyleMaskTitled];
+ close_button = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:NSWindowStyleMaskTitled];
[close_button setFrameOrigin:NSMakePoint(rtl ? spacing * 2 : 0, 0)];
[self addSubview:close_button];
- NSButton *miniaturize_button = [NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:NSWindowStyleMaskTitled];
+ miniaturize_button = [NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:NSWindowStyleMaskTitled];
[miniaturize_button setFrameOrigin:NSMakePoint(spacing, 0)];
[self addSubview:miniaturize_button];
- NSButton *zoom_button = [NSWindow standardWindowButton:NSWindowZoomButton forStyleMask:NSWindowStyleMaskTitled];
+ zoom_button = [NSWindow standardWindowButton:NSWindowZoomButton forStyleMask:NSWindowStyleMaskTitled];
[zoom_button setFrameOrigin:NSMakePoint(rtl ? 0 : spacing * 2, 0)];
[self addSubview:zoom_button];
@@ -71,6 +74,19 @@
[self displayButtons];
}
+- (void)setOffset:(NSPoint)button_offset {
+ if (zoom_button) {
+ offset.y = button_offset.y - zoom_button.frame.size.height / 2;
+ offset.x = button_offset.x - zoom_button.frame.size.width / 2;
+
+ [self viewDidMoveToWindow];
+ }
+}
+
+- (NSPoint)getOffset {
+ return offset;
+}
+
- (void)viewDidMoveToWindow {
if (!self.window) {
return;
diff --git a/platform/macos/joypad_macos.h b/platform/macos/joypad_macos.h
index 4b14fed6d5..8743fc91a9 100644
--- a/platform/macos/joypad_macos.h
+++ b/platform/macos/joypad_macos.h
@@ -31,14 +31,10 @@
#ifndef JOYPAD_MACOS_H
#define JOYPAD_MACOS_H
-#ifdef MACOS_10_0_4
-#import <IOKit/hidsystem/IOHIDUsageTables.h>
-#else
-#import <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
-#endif
#import <ForceFeedback/ForceFeedback.h>
#import <ForceFeedback/ForceFeedbackConstants.h>
#import <IOKit/hid/IOHIDLib.h>
+#import <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
#include "core/input/input.h"
diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm
index ae8534f6ab..8ffb0abfdb 100644
--- a/platform/macos/os_macos.mm
+++ b/platform/macos/os_macos.mm
@@ -148,9 +148,11 @@ void OS_MacOS::alert(const String &p_alert, const String &p_title) {
NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
+ NSTextField *text_field = [NSTextField labelWithString:ns_alert];
+ [text_field setAlignment:NSTextAlignmentCenter];
[window addButtonWithTitle:@"OK"];
[window setMessageText:ns_title];
- [window setInformativeText:ns_alert];
+ [window setAccessoryView:text_field];
[window setAlertStyle:NSAlertStyleWarning];
id key_window = [[NSApplication sharedApplication] keyWindow];
diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp
index 8050d299f0..141c28c713 100644
--- a/platform/uwp/os_uwp.cpp
+++ b/platform/uwp/os_uwp.cpp
@@ -159,7 +159,7 @@ Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_a
outside = true;
// FIXME: Hardcoded for now, add Vulkan support.
- p_video_driver = VIDEO_DRIVER_OPENGL;
+ p_video_driver = RENDERING_DRIVER_OPENGL3;
ContextEGL_UWP::Driver opengl_api_type = ContextEGL_UWP::GLES_2_0;
bool gl_initialization_error = false;
@@ -826,10 +826,6 @@ OS_UWP::OS_UWP() {
pressrc = 0;
old_invalid = true;
mouse_mode = MOUSE_MODE_VISIBLE;
-#ifdef STDOUT_FILE
- stdo = fopen("stdout.txt", "wb");
-#endif
-
gl_context = nullptr;
display_request = ref new Windows::System::Display::DisplayRequest();
@@ -847,7 +843,4 @@ OS_UWP::OS_UWP() {
}
OS_UWP::~OS_UWP() {
-#ifdef STDOUT_FILE
- fclose(stdo);
-#endif
}
diff --git a/platform/web/.eslintrc.html.js b/platform/web/.eslintrc.html.js
new file mode 100644
index 0000000000..5cb8de360a
--- /dev/null
+++ b/platform/web/.eslintrc.html.js
@@ -0,0 +1,19 @@
+module.exports = {
+ "plugins": [
+ "html",
+ "@html-eslint",
+ ],
+ "parser": "@html-eslint/parser",
+ "extends": ["plugin:@html-eslint/recommended", "./.eslintrc.js"],
+ "rules": {
+ "no-alert": "off",
+ "no-console": "off",
+ "@html-eslint/require-closing-tags": ["error", { "selfClosing": "never" }],
+ "@html-eslint/indent": ["error", "tab"],
+ },
+ "globals": {
+ "Godot": true,
+ "Engine": true,
+ "$GODOT_CONFIG": true,
+ },
+};
diff --git a/platform/web/SCsub b/platform/web/SCsub
index 013b734be2..077024507a 100644
--- a/platform/web/SCsub
+++ b/platform/web/SCsub
@@ -2,6 +2,20 @@
Import("env")
+# The HTTP server "targets". Run with "scons p=web serve", or "scons p=web run"
+if "serve" in COMMAND_LINE_TARGETS or "run" in COMMAND_LINE_TARGETS:
+ from serve import serve
+ import os
+
+ port = os.environ.get("GODOT_WEB_TEST_PORT", 8060)
+ try:
+ port = int(port)
+ except Exception:
+ print("GODOT_WEB_TEST_PORT must be a valid integer")
+ sys.exit(255)
+ serve(env.Dir("#bin/.web_zip").abspath, port, "run" in COMMAND_LINE_TARGETS)
+ sys.exit(0)
+
web_files = [
"audio_driver_web.cpp",
"display_server_web.cpp",
@@ -21,6 +35,7 @@ sys_env.AddJSLibraries(
"js/libs/library_godot_os.js",
"js/libs/library_godot_runtime.js",
"js/libs/library_godot_input.js",
+ "js/libs/library_godot_webgl2.js",
]
)
diff --git a/platform/web/display_server_web.cpp b/platform/web/display_server_web.cpp
index f6a61b18e4..10ed8b8343 100644
--- a/platform/web/display_server_web.cpp
+++ b/platform/web/display_server_web.cpp
@@ -738,11 +738,11 @@ void DisplayServerWeb::_dispatch_input_event(const Ref<InputEvent> &p_event) {
}
}
-DisplayServer *DisplayServerWeb::create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Size2i &p_resolution, Error &r_error) {
- return memnew(DisplayServerWeb(p_rendering_driver, p_window_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerWeb::create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Point2i *p_position, const Size2i &p_resolution, Error &r_error) {
+ return memnew(DisplayServerWeb(p_rendering_driver, p_window_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
}
-DisplayServerWeb::DisplayServerWeb(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Size2i &p_resolution, Error &r_error) {
+DisplayServerWeb::DisplayServerWeb(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Point2i *p_position, const Size2i &p_resolution, Error &r_error) {
r_error = OK; // Always succeeds for now.
// Ensure the canvas ID.
@@ -773,6 +773,9 @@ DisplayServerWeb::DisplayServerWeb(const String &p_rendering_driver, WindowMode
if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
webgl2_init_failed = true;
} else {
+ if (!emscripten_webgl_enable_extension(webgl_ctx, "OVR_multiview2")) {
+ // @todo Should we log this?
+ }
RasterizerGLES3::make_current();
}
}
diff --git a/platform/web/display_server_web.h b/platform/web/display_server_web.h
index 85076b906f..3222e2483e 100644
--- a/platform/web/display_server_web.h
+++ b/platform/web/display_server_web.h
@@ -96,7 +96,7 @@ private:
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);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static void _dispatch_input_event(const Ref<InputEvent> &p_event);
@@ -221,7 +221,7 @@ public:
virtual void swap_buffers() override;
static void register_web_driver();
- DisplayServerWeb(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Size2i &p_resolution, Error &r_error);
+ DisplayServerWeb(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Point2i *p_position, const Size2i &p_resolution, Error &r_error);
~DisplayServerWeb();
};
diff --git a/platform/web/export/export_plugin.cpp b/platform/web/export/export_plugin.cpp
index 1c327fe4b2..f59ac54f20 100644
--- a/platform/web/export/export_plugin.cpp
+++ b/platform/web/export/export_plugin.cpp
@@ -485,6 +485,7 @@ Error EditorExportPlatformWeb::export_project(const Ref<EditorExportPreset> &p_p
}
html.resize(f->get_length());
f->get_buffer(html.ptrw(), html.size());
+ f.unref(); // close file.
// Generate HTML file with replaced strings.
_fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
diff --git a/platform/web/godot_webgl2.h b/platform/web/godot_webgl2.h
index 968b70f84b..ae6b23ae18 100644
--- a/platform/web/godot_webgl2.h
+++ b/platform/web/godot_webgl2.h
@@ -34,4 +34,21 @@
#include "GLES3/gl3.h"
#include "webgl/webgl2.h"
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632
+#define GL_MAX_VIEWS_OVR 0x9631
+#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void godot_webgl2_glFramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews);
+
+#define glFramebufferTextureMultiviewOVR godot_webgl2_glFramebufferTextureMultiviewOVR
+
+#ifdef __cplusplus
+}
+#endif
+
#endif // GODOT_WEBGL2_H
diff --git a/platform/web/js/libs/library_godot_javascript_singleton.js b/platform/web/js/libs/library_godot_javascript_singleton.js
index 692f27676a..c86cbbae45 100644
--- a/platform/web/js/libs/library_godot_javascript_singleton.js
+++ b/platform/web/js/libs/library_godot_javascript_singleton.js
@@ -88,7 +88,7 @@ const GodotJSWrapper = {
return GodotRuntime.getHeapValue(val, 'double');
case 4:
return GodotRuntime.parseString(GodotRuntime.getHeapValue(val, '*'));
- case 21: // OBJECT
+ case 24: // OBJECT
return GodotJSWrapper.get_proxied_value(GodotRuntime.getHeapValue(val, 'i64'));
default:
return undefined;
@@ -117,7 +117,7 @@ const GodotJSWrapper = {
}
const id = GodotJSWrapper.get_proxied(p_val);
GodotRuntime.setHeapValue(p_exchange, id, 'i64');
- return 21;
+ return 24; // OBJECT
},
},
diff --git a/platform/web/js/libs/library_godot_webgl2.js b/platform/web/js/libs/library_godot_webgl2.js
new file mode 100644
index 0000000000..365f712be7
--- /dev/null
+++ b/platform/web/js/libs/library_godot_webgl2.js
@@ -0,0 +1,52 @@
+/*************************************************************************/
+/* library_godot_webgl2.js */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 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. */
+/*************************************************************************/
+const GodotWebGL2 = {
+ $GodotWebGL2__deps: ['$GL', '$GodotRuntime'],
+ $GodotWebGL2: {},
+
+ godot_webgl2_glFramebufferTextureMultiviewOVR__deps: ['emscripten_webgl_get_current_context'],
+ godot_webgl2_glFramebufferTextureMultiviewOVR__proxy: 'sync',
+ godot_webgl2_glFramebufferTextureMultiviewOVR__sig: 'viiiiii',
+ godot_webgl2_glFramebufferTextureMultiviewOVR: function (target, attachment, texture, level, base_view_index, num_views) {
+ const context = GL.currentContext;
+ if (typeof context.multiviewExt === 'undefined') {
+ const ext = context.GLctx.getExtension('OVR_multiview2');
+ if (!ext) {
+ console.error('Trying to call glFramebufferTextureMultiviewOVR() without the OVR_multiview2 extension');
+ return;
+ }
+ context.multiviewExt = ext;
+ }
+ context.multiviewExt.framebufferTextureMultiviewOVR(target, attachment, GL.textures[texture], level, base_view_index, num_views);
+ },
+};
+
+autoAddDeps(GodotWebGL2, '$GodotWebGL2');
+mergeInto(LibraryManager.library, GodotWebGL2);
diff --git a/platform/web/os_web.cpp b/platform/web/os_web.cpp
index c263ee094b..07c53e51d0 100644
--- a/platform/web/os_web.cpp
+++ b/platform/web/os_web.cpp
@@ -37,9 +37,6 @@
#include "platform/web/display_server_web.h"
#include "modules/modules_enabled.gen.h" // For websocket.
-#ifdef MODULE_WEBSOCKET_ENABLED
-#include "modules/websocket/remote_debugger_peer_websocket.h"
-#endif
#include <dlfcn.h>
#include <emscripten.h>
@@ -56,11 +53,6 @@ void OS_Web::alert(const String &p_alert, const String &p_title) {
void OS_Web::initialize() {
OS_Unix::initialize_core();
DisplayServerWeb::register_web_driver();
-
-#ifdef MODULE_WEBSOCKET_ENABLED
- EngineDebugger::register_uri_handler("ws://", RemoteDebuggerPeerWebSocket::create);
- EngineDebugger::register_uri_handler("wss://", RemoteDebuggerPeerWebSocket::create);
-#endif
}
void OS_Web::resume_audio() {
diff --git a/platform/web/package-lock.json b/platform/web/package-lock.json
index 9a7d871c64..4c12c8602d 100644
--- a/platform/web/package-lock.json
+++ b/platform/web/package-lock.json
@@ -8,8 +8,13 @@
"name": "godot",
"version": "1.0.0",
"license": "MIT",
+ "dependencies": {
+ "eslint-plugin-html": "^7.1.0"
+ },
"devDependencies": {
- "eslint": "^7.28.0",
+ "@html-eslint/eslint-plugin": "^0.15.0",
+ "@html-eslint/parser": "^0.15.0",
+ "eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-plugin-import": "^2.23.4",
"jsdoc": "^3.6.7"
@@ -83,9 +88,9 @@
}
},
"node_modules/@eslint/eslintrc": {
- "version": "0.4.2",
- "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.2.tgz",
- "integrity": "sha512-8nmGq/4ycLpIwzvhI4tNDmQztZ8sp+hI7cyG8i1nQDhkAbRzHpXPidRAHlNvCZQpJTKw5ItIpMw9RSToGF00mg==",
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz",
+ "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==",
"dev": true,
"dependencies": {
"ajv": "^6.12.4",
@@ -102,6 +107,47 @@
"node": "^10.12.0 || >=12.0.0"
}
},
+ "node_modules/@html-eslint/eslint-plugin": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@html-eslint/eslint-plugin/-/eslint-plugin-0.15.0.tgz",
+ "integrity": "sha512-6DUb2ZN1PUlzlNzNj4aBhoObBp3Kl/+YbZ6CnkgFAsQSW0tSFAu7p8WwESkz9RZLZZN9gCUlcaYKJnQjTkmnDA==",
+ "dev": true,
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/@html-eslint/parser": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@html-eslint/parser/-/parser-0.15.0.tgz",
+ "integrity": "sha512-fA+HQtWnODhOIK6j1p4XWqltINx7hM0WNNTM2RvlH/2glzeRDCcYq3vEmeQhnytvGocidu4ofTzNk80cLnnyiw==",
+ "dev": true,
+ "dependencies": {
+ "es-html-parser": "^0.0.8"
+ },
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/@humanwhocodes/config-array": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz",
+ "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==",
+ "dev": true,
+ "dependencies": {
+ "@humanwhocodes/object-schema": "^1.2.0",
+ "debug": "^4.1.1",
+ "minimatch": "^3.0.4"
+ },
+ "engines": {
+ "node": ">=10.10.0"
+ }
+ },
+ "node_modules/@humanwhocodes/object-schema": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz",
+ "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==",
+ "dev": true
+ },
"node_modules/@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
@@ -143,9 +189,9 @@
}
},
"node_modules/acorn-jsx": {
- "version": "5.3.1",
- "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.1.tgz",
- "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==",
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
"dev": true,
"peerDependencies": {
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
@@ -419,9 +465,9 @@
}
},
"node_modules/debug": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
- "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
+ "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dev": true,
"dependencies": {
"ms": "2.1.2"
@@ -465,6 +511,68 @@
"node": ">=6.0.0"
}
},
+ "node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/dom-serializer/node_modules/entities": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz",
+ "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ]
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.0.1.tgz",
+ "integrity": "sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
@@ -531,6 +639,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/es-html-parser": {
+ "version": "0.0.8",
+ "resolved": "https://registry.npmjs.org/es-html-parser/-/es-html-parser-0.0.8.tgz",
+ "integrity": "sha512-kjMH23xhvTBw/7Ve1Dtb/7yZdFajfvwOpdsgRHmnyt8yvTsDJnkFjUgEEaMZFW+e1OhN/eoZrvF9wehq+waTGg==",
+ "dev": true
+ },
"node_modules/es-to-primitive": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
@@ -561,13 +675,14 @@
}
},
"node_modules/eslint": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.28.0.tgz",
- "integrity": "sha512-UMfH0VSjP0G4p3EWirscJEQ/cHqnT/iuH6oNZOB94nBjWbMnhGEPxsZm1eyIW0C/9jLI0Fow4W5DXLjEI7mn1g==",
+ "version": "7.32.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz",
+ "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==",
"dev": true,
"dependencies": {
"@babel/code-frame": "7.12.11",
- "@eslint/eslintrc": "^0.4.2",
+ "@eslint/eslintrc": "^0.4.3",
+ "@humanwhocodes/config-array": "^0.5.0",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
"cross-spawn": "^7.0.2",
@@ -681,6 +796,14 @@
"ms": "^2.1.1"
}
},
+ "node_modules/eslint-plugin-html": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-7.1.0.tgz",
+ "integrity": "sha512-fNLRraV/e6j8e3XYOC9xgND4j+U7b1Rq+OygMlLcMg+wI/IpVbF+ubQa3R78EjKB9njT6TQOlcK5rFKBVVtdfg==",
+ "dependencies": {
+ "htmlparser2": "^8.0.1"
+ }
+ },
"node_modules/eslint-plugin-import": {
"version": "2.23.4",
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.23.4.tgz",
@@ -1005,9 +1128,9 @@
}
},
"node_modules/globals": {
- "version": "13.9.0",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.9.0.tgz",
- "integrity": "sha512-74/FduwI/JaIrr1H8e71UbDE+5x7pIPs1C2rrwC52SszOo043CsWOZEMW7o2Y58xwm9b+0RBKDxY5n2sUpEFxA==",
+ "version": "13.17.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.17.0.tgz",
+ "integrity": "sha512-1C+6nQRb1GwGMKm2dH/E7enFAMxGTmGI7/dEdhy/DNelv85w9B72t3uc5frtMNXIbzrarJJ/lTCjcaZwbLJmyw==",
"dev": true,
"dependencies": {
"type-fest": "^0.20.2"
@@ -1073,6 +1196,35 @@
"integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==",
"dev": true
},
+ "node_modules/htmlparser2": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz",
+ "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==",
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "entities": "^4.3.0"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/entities": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz",
+ "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/ignore": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz",
@@ -2067,7 +2219,7 @@
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
- "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"dev": true
},
"node_modules/string-width": {
@@ -2406,9 +2558,9 @@
"dev": true
},
"@eslint/eslintrc": {
- "version": "0.4.2",
- "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.2.tgz",
- "integrity": "sha512-8nmGq/4ycLpIwzvhI4tNDmQztZ8sp+hI7cyG8i1nQDhkAbRzHpXPidRAHlNvCZQpJTKw5ItIpMw9RSToGF00mg==",
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz",
+ "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==",
"dev": true,
"requires": {
"ajv": "^6.12.4",
@@ -2422,6 +2574,38 @@
"strip-json-comments": "^3.1.1"
}
},
+ "@html-eslint/eslint-plugin": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@html-eslint/eslint-plugin/-/eslint-plugin-0.15.0.tgz",
+ "integrity": "sha512-6DUb2ZN1PUlzlNzNj4aBhoObBp3Kl/+YbZ6CnkgFAsQSW0tSFAu7p8WwESkz9RZLZZN9gCUlcaYKJnQjTkmnDA==",
+ "dev": true
+ },
+ "@html-eslint/parser": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@html-eslint/parser/-/parser-0.15.0.tgz",
+ "integrity": "sha512-fA+HQtWnODhOIK6j1p4XWqltINx7hM0WNNTM2RvlH/2glzeRDCcYq3vEmeQhnytvGocidu4ofTzNk80cLnnyiw==",
+ "dev": true,
+ "requires": {
+ "es-html-parser": "^0.0.8"
+ }
+ },
+ "@humanwhocodes/config-array": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz",
+ "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==",
+ "dev": true,
+ "requires": {
+ "@humanwhocodes/object-schema": "^1.2.0",
+ "debug": "^4.1.1",
+ "minimatch": "^3.0.4"
+ }
+ },
+ "@humanwhocodes/object-schema": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz",
+ "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==",
+ "dev": true
+ },
"@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
@@ -2457,9 +2641,9 @@
"dev": true
},
"acorn-jsx": {
- "version": "5.3.1",
- "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.1.tgz",
- "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==",
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
"dev": true,
"requires": {}
},
@@ -2672,9 +2856,9 @@
}
},
"debug": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
- "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
+ "version": "4.3.4",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
+ "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dev": true,
"requires": {
"ms": "2.1.2"
@@ -2704,6 +2888,46 @@
"esutils": "^2.0.2"
}
},
+ "dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "requires": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "dependencies": {
+ "entities": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz",
+ "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA=="
+ }
+ }
+ },
+ "domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="
+ },
+ "domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "requires": {
+ "domelementtype": "^2.3.0"
+ }
+ },
+ "domutils": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.0.1.tgz",
+ "integrity": "sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==",
+ "requires": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.1"
+ }
+ },
"emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
@@ -2758,6 +2982,12 @@
"unbox-primitive": "^1.0.1"
}
},
+ "es-html-parser": {
+ "version": "0.0.8",
+ "resolved": "https://registry.npmjs.org/es-html-parser/-/es-html-parser-0.0.8.tgz",
+ "integrity": "sha512-kjMH23xhvTBw/7Ve1Dtb/7yZdFajfvwOpdsgRHmnyt8yvTsDJnkFjUgEEaMZFW+e1OhN/eoZrvF9wehq+waTGg==",
+ "dev": true
+ },
"es-to-primitive": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
@@ -2776,13 +3006,14 @@
"dev": true
},
"eslint": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.28.0.tgz",
- "integrity": "sha512-UMfH0VSjP0G4p3EWirscJEQ/cHqnT/iuH6oNZOB94nBjWbMnhGEPxsZm1eyIW0C/9jLI0Fow4W5DXLjEI7mn1g==",
+ "version": "7.32.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz",
+ "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==",
"dev": true,
"requires": {
"@babel/code-frame": "7.12.11",
- "@eslint/eslintrc": "^0.4.2",
+ "@eslint/eslintrc": "^0.4.3",
+ "@humanwhocodes/config-array": "^0.5.0",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
"cross-spawn": "^7.0.2",
@@ -2881,6 +3112,14 @@
}
}
},
+ "eslint-plugin-html": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-7.1.0.tgz",
+ "integrity": "sha512-fNLRraV/e6j8e3XYOC9xgND4j+U7b1Rq+OygMlLcMg+wI/IpVbF+ubQa3R78EjKB9njT6TQOlcK5rFKBVVtdfg==",
+ "requires": {
+ "htmlparser2": "^8.0.1"
+ }
+ },
"eslint-plugin-import": {
"version": "2.23.4",
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.23.4.tgz",
@@ -3139,9 +3378,9 @@
}
},
"globals": {
- "version": "13.9.0",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.9.0.tgz",
- "integrity": "sha512-74/FduwI/JaIrr1H8e71UbDE+5x7pIPs1C2rrwC52SszOo043CsWOZEMW7o2Y58xwm9b+0RBKDxY5n2sUpEFxA==",
+ "version": "13.17.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.17.0.tgz",
+ "integrity": "sha512-1C+6nQRb1GwGMKm2dH/E7enFAMxGTmGI7/dEdhy/DNelv85w9B72t3uc5frtMNXIbzrarJJ/lTCjcaZwbLJmyw==",
"dev": true,
"requires": {
"type-fest": "^0.20.2"
@@ -3186,6 +3425,24 @@
"integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==",
"dev": true
},
+ "htmlparser2": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz",
+ "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==",
+ "requires": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "entities": "^4.3.0"
+ },
+ "dependencies": {
+ "entities": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz",
+ "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA=="
+ }
+ }
+ },
"ignore": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz",
@@ -3936,7 +4193,7 @@
"sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
- "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"dev": true
},
"string-width": {
diff --git a/platform/web/package.json b/platform/web/package.json
index 8d4983663b..e1dd7b1a22 100644
--- a/platform/web/package.json
+++ b/platform/web/package.json
@@ -5,23 +5,30 @@
"description": "Development and linting setup for Godot's Web platform code",
"scripts": {
"docs": "jsdoc --template js/jsdoc2rst/ js/engine/engine.js js/engine/config.js js/engine/features.js --destination ''",
- "lint": "npm run lint:engine && npm run lint:libs && npm run lint:modules && npm run lint:tools",
+ "lint": "npm run lint:engine && npm run lint:libs && npm run lint:modules && npm run lint:tools && npm run lint:html",
"lint:engine": "eslint \"js/engine/*.js\" --no-eslintrc -c .eslintrc.engine.js",
"lint:libs": "eslint \"js/libs/*.js\" --no-eslintrc -c .eslintrc.libs.js",
"lint:modules": "eslint \"../../modules/**/*.js\" --no-eslintrc -c .eslintrc.libs.js",
"lint:tools": "eslint \"js/jsdoc2rst/**/*.js\" --no-eslintrc -c .eslintrc.engine.js",
- "format": "npm run format:engine && npm run format:libs && npm run format:modules && npm run format:tools",
+ "lint:html": "eslint \"../../misc/dist/html/*.html\" --no-eslintrc -c .eslintrc.html.js",
+ "format": "npm run format:engine && npm run format:libs && npm run format:modules && npm run format:tools && npm run format:html",
"format:engine": "npm run lint:engine -- --fix",
"format:libs": "npm run lint:libs -- --fix",
"format:modules": "npm run lint:modules -- --fix",
- "format:tools": "npm run lint:tools -- --fix"
+ "format:tools": "npm run lint:tools -- --fix",
+ "format:html": "npm run lint:html -- --fix"
},
"author": "Godot Engine contributors",
"license": "MIT",
"devDependencies": {
- "eslint": "^7.28.0",
+ "@html-eslint/eslint-plugin": "^0.15.0",
+ "@html-eslint/parser": "^0.15.0",
+ "eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-plugin-import": "^2.23.4",
"jsdoc": "^3.6.7"
+ },
+ "dependencies": {
+ "eslint-plugin-html": "^7.1.0"
}
}
diff --git a/platform/web/serve.py b/platform/web/serve.py
index 14e87e9ea1..6a3efcc463 100755
--- a/platform/web/serve.py
+++ b/platform/web/serve.py
@@ -24,6 +24,17 @@ def shell_open(url):
subprocess.call([opener, url])
+def serve(root, port, run_browser):
+ os.chdir(root)
+
+ if run_browser:
+ # Open the served page in the user's default browser.
+ print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).")
+ shell_open(f"http://127.0.0.1:{port}")
+
+ test(CORSRequestHandler, HTTPServer, port=port)
+
+
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int)
@@ -41,12 +52,4 @@ if __name__ == "__main__":
# so that the script can be run from any location.
os.chdir(Path(__file__).resolve().parent)
- if args.root:
- os.chdir(args.root)
-
- if args.browser:
- # Open the served page in the user's default browser.
- print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).")
- shell_open(f"http://127.0.0.1:{args.port}")
-
- test(CORSRequestHandler, HTTPServer, port=args.port)
+ serve(args.root, args.port, args.browser)
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index a5d8d0344b..74868fc6a2 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -401,6 +401,7 @@ def configure_msvc(env, vcvars_msvc_config):
"Avrt",
"dwmapi",
"dwrite",
+ "wbemuuid",
]
if env["vulkan"]:
@@ -577,6 +578,7 @@ def configure_mingw(env):
"uuid",
"dwmapi",
"dwrite",
+ "wbemuuid",
]
)
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index 16853a0be7..d99670243e 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -561,20 +561,6 @@ float DisplayServerWindows::screen_get_refresh_rate(int p_screen) const {
return data.rate;
}
-bool DisplayServerWindows::screen_is_touchscreen(int p_screen) const {
-#ifndef _MSC_VER
-#warning touchscreen not working
-#endif
- return DisplayServer::screen_is_touchscreen(p_screen);
-}
-
-void DisplayServerWindows::screen_set_orientation(ScreenOrientation p_orientation, int p_screen) {
-}
-
-DisplayServer::ScreenOrientation DisplayServerWindows::screen_get_orientation(int p_screen) const {
- return SCREEN_LANDSCAPE;
-}
-
void DisplayServerWindows::screen_set_keep_on(bool p_enable) {
if (keep_screen_on == p_enable) {
return;
@@ -2458,10 +2444,12 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
return 0; // Jump back.
}
case WM_MOUSELEAVE: {
- old_invalid = true;
- windows[window_id].mouse_outside = true;
+ if (window_mouseover_id == window_id) {
+ old_invalid = true;
+ window_mouseover_id = INVALID_WINDOW_ID;
- _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
+ _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
+ }
} break;
case WM_INPUT: {
@@ -2692,17 +2680,21 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
- if (windows[window_id].mouse_outside) {
+ if (window_mouseover_id != window_id) {
// Mouse enter.
if (mouse_mode != MOUSE_MODE_CAPTURED) {
+ if (window_mouseover_id != INVALID_WINDOW_ID) {
+ // Leave previous window.
+ _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
+ }
_send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
}
CursorShape c = cursor_shape;
cursor_shape = CURSOR_MAX;
cursor_set_shape(c);
- windows[window_id].mouse_outside = false;
+ window_mouseover_id = window_id;
// Once-off notification, must call again.
track_mouse_leave_event(hWnd);
@@ -2793,17 +2785,29 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
- if (windows[window_id].mouse_outside) {
+ DisplayServer::WindowID over_id = get_window_at_screen_position(mouse_get_position());
+ if (!Rect2(window_get_position(over_id), Point2(windows[over_id].width, windows[over_id].height)).has_point(mouse_get_position())) {
+ // Don't consider the windowborder as part of the window.
+ over_id = INVALID_WINDOW_ID;
+ }
+ if (window_mouseover_id != over_id) {
// Mouse enter.
if (mouse_mode != MOUSE_MODE_CAPTURED) {
- _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
+ if (window_mouseover_id != INVALID_WINDOW_ID) {
+ // Leave previous window.
+ _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
+ }
+
+ if (over_id != INVALID_WINDOW_ID) {
+ _send_window_event(windows[over_id], WINDOW_EVENT_MOUSE_ENTER);
+ }
}
CursorShape c = cursor_shape;
cursor_shape = CURSOR_MAX;
cursor_set_shape(c);
- windows[window_id].mouse_outside = false;
+ window_mouseover_id = over_id;
// Once-off notification, must call again.
track_mouse_leave_event(hWnd);
@@ -2814,9 +2818,13 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
break;
}
+ DisplayServer::WindowID receiving_window_id = _get_focused_window_or_popup();
+ if (receiving_window_id == INVALID_WINDOW_ID) {
+ receiving_window_id = window_id;
+ }
Ref<InputEventMouseMotion> mm;
mm.instantiate();
- mm->set_window_id(window_id);
+ mm->set_window_id(receiving_window_id);
mm->set_ctrl_pressed((wParam & MK_CONTROL) != 0);
mm->set_shift_pressed((wParam & MK_SHIFT) != 0);
mm->set_alt_pressed(alt_mem);
@@ -2873,9 +2881,8 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
old_x = mm->get_position().x;
old_y = mm->get_position().y;
- if (windows[window_id].window_has_focus || window_get_active_popup() == window_id) {
- Input::get_singleton()->parse_input_event(mm);
- }
+
+ Input::get_singleton()->parse_input_event(mm);
} break;
case WM_LBUTTONDOWN:
@@ -3101,7 +3108,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
rect_changed = true;
}
#if defined(VULKAN_ENABLED)
- if (context_vulkan && window_created) {
+ if (context_vulkan && window.context_created) {
// Note: Trigger resize event to update swapchains when window is minimized/restored, even if size is not changed.
context_vulkan->window_resize(window_id, window.width, window.height);
}
@@ -3561,6 +3568,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
windows.erase(id);
ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Vulkan Window.");
}
+ wd.context_created = true;
}
#endif
@@ -3717,7 +3725,7 @@ void DisplayServerWindows::tablet_set_current_driver(const String &p_driver) {
}
}
-DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
drop_events = false;
key_event_pos = 0;
@@ -3869,6 +3877,10 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
(screen_get_size(0).width - p_resolution.width) / 2,
(screen_get_size(0).height - p_resolution.height) / 2);
+ if (p_position != nullptr) {
+ window_position = *p_position;
+ }
+
WindowID main_window = _create_window(p_mode, p_vsync_mode, 0, Rect2i(window_position, p_resolution));
ERR_FAIL_COND_MSG(main_window == INVALID_WINDOW_ID, "Failed to create main window.");
@@ -3932,12 +3944,24 @@ Vector<String> DisplayServerWindows::get_rendering_drivers_func() {
return drivers;
}
-DisplayServer *DisplayServerWindows::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
- DisplayServer *ds = memnew(DisplayServerWindows(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
+DisplayServer *DisplayServerWindows::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
+ DisplayServer *ds = memnew(DisplayServerWindows(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
if (r_error != OK) {
- OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.\n"
- "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
- "Unable to initialize Video driver");
+ if (p_rendering_driver == "vulkan") {
+ String executable_name = OS::get_singleton()->get_executable_path().get_file();
+ OS::get_singleton()->alert("Your video card driver does not support the selected Vulkan version.\n"
+ "Please try updating your GPU driver or try using the OpenGL 3 driver.\n"
+ "You can enable the OpenGL 3 driver by starting the engine from the\n"
+ "command line with the command:\n'./" +
+ executable_name + " --rendering-driver opengl3'.\n "
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ } else {
+ OS::get_singleton()->alert("Your video card driver does not support the selected OpenGL version.\n"
+ "Please try updating your GPU driver.\n"
+ "If you have updated your graphics drivers recently, try rebooting.",
+ "Unable to initialize Video driver");
+ }
}
return ds;
}
diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h
index 3523e8b3d1..8ac0086d69 100644
--- a/platform/windows/display_server_windows.h
+++ b/platform/windows/display_server_windows.h
@@ -323,6 +323,8 @@ class DisplayServerWindows : public DisplayServer {
LPARAM lParam;
};
+ WindowID window_mouseover_id = INVALID_WINDOW_ID;
+
KeyEvent key_event_buffer[KEY_EVENT_BUFFER_SIZE];
int key_event_pos;
@@ -369,6 +371,7 @@ class DisplayServerWindows : public DisplayServer {
bool no_focus = false;
bool window_has_focus = false;
bool exclusive = false;
+ bool context_created = false;
// Used to transfer data between events using timer.
WPARAM saved_wparam;
@@ -397,7 +400,6 @@ class DisplayServerWindows : public DisplayServer {
Size2 window_rect;
Point2 last_pos;
- bool mouse_outside = true;
ObjectID instance_id;
@@ -516,10 +518,6 @@ public:
virtual Rect2i screen_get_usable_rect(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual float screen_get_refresh_rate(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
- virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
-
- virtual void screen_set_orientation(ScreenOrientation p_orientation, int p_screen = SCREEN_OF_MAIN_WINDOW) override;
- virtual ScreenOrientation screen_get_orientation(int p_screen = SCREEN_OF_MAIN_WINDOW) const override;
virtual void screen_set_keep_on(bool p_enable) override; //disable screensaver
virtual bool screen_is_kept_on() const override;
@@ -626,11 +624,11 @@ public:
virtual void set_context(Context p_context) override;
- static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
static Vector<String> get_rendering_drivers_func();
static void register_windows_driver();
- DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
~DisplayServerWindows();
};
diff --git a/platform/windows/joypad_windows.h b/platform/windows/joypad_windows.h
index d239471a5c..56a9f3e9c9 100644
--- a/platform/windows/joypad_windows.h
+++ b/platform/windows/joypad_windows.h
@@ -85,6 +85,8 @@ private:
last_pad = -1;
attached = false;
confirmed = false;
+ di_joy = nullptr;
+ guid = {};
for (int i = 0; i < MAX_JOY_BUTTONS; i++) {
last_buttons[i] = false;
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index 241e0b382e..a8911788fe 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -53,6 +53,7 @@
#include <process.h>
#include <regstr.h>
#include <shlobj.h>
+#include <wbemcli.h>
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 1;
@@ -309,6 +310,103 @@ String OS_Windows::get_version() const {
return "";
}
+Vector<String> OS_Windows::get_video_adapter_driver_info() const {
+ if (RenderingServer::get_singleton()->get_rendering_device() == nullptr) {
+ return Vector<String>();
+ }
+
+ REFCLSID clsid = CLSID_WbemLocator; // Unmarshaler CLSID
+ REFIID uuid = IID_IWbemLocator; // Interface UUID
+ IWbemLocator *wbemLocator = NULL; // to get the services
+ IWbemServices *wbemServices = NULL; // to get the class
+ IEnumWbemClassObject *iter = NULL;
+ IWbemClassObject *pnpSDriverObject[1]; // contains driver name, version, etc.
+ static String driver_name;
+ static String driver_version;
+
+ const String device_name = RenderingServer::get_singleton()->get_rendering_device()->get_device_name();
+ if (device_name.is_empty()) {
+ return Vector<String>();
+ }
+
+ CoInitialize(nullptr);
+
+ HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, uuid, (LPVOID *)&wbemLocator);
+ if (hr != S_OK) {
+ return Vector<String>();
+ }
+ BSTR resource_name = SysAllocString(L"root\\CIMV2");
+ hr = wbemLocator->ConnectServer(resource_name, NULL, NULL, NULL, 0, NULL, NULL, &wbemServices);
+ SysFreeString(resource_name);
+
+ SAFE_RELEASE(wbemLocator) // from now on, use `wbemServices`
+ if (hr != S_OK) {
+ SAFE_RELEASE(wbemServices)
+ return Vector<String>();
+ }
+
+ const String gpu_device_class_query = vformat("SELECT * FROM Win32_PnPSignedDriver WHERE DeviceName = \"%s\"", device_name);
+ BSTR query = SysAllocString((const WCHAR *)gpu_device_class_query.utf16().get_data());
+ BSTR query_lang = SysAllocString(L"WQL");
+ hr = wbemServices->ExecQuery(query_lang, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, NULL, &iter);
+ SysFreeString(query_lang);
+ SysFreeString(query);
+ if (hr == S_OK) {
+ ULONG resultCount;
+ hr = iter->Next(5000, 1, pnpSDriverObject, &resultCount); // Get exactly 1. Wait max 5 seconds.
+
+ if (hr == S_OK && resultCount > 0) {
+ VARIANT dn;
+ VariantInit(&dn);
+
+ BSTR object_name = SysAllocString(L"DriverName");
+ hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
+ SysFreeString(object_name);
+ if (hr == S_OK) {
+ String d_name = String(V_BSTR(&dn));
+ if (d_name.is_empty()) {
+ object_name = SysAllocString(L"DriverProviderName");
+ hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
+ SysFreeString(object_name);
+ if (hr == S_OK) {
+ driver_name = String(V_BSTR(&dn));
+ }
+ } else {
+ driver_name = d_name;
+ }
+ } else {
+ object_name = SysAllocString(L"DriverProviderName");
+ hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
+ SysFreeString(object_name);
+ if (hr == S_OK) {
+ driver_name = String(V_BSTR(&dn));
+ }
+ }
+
+ VARIANT dv;
+ VariantInit(&dv);
+ object_name = SysAllocString(L"DriverVersion");
+ hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, NULL, NULL);
+ SysFreeString(object_name);
+ if (hr == S_OK) {
+ driver_version = String(V_BSTR(&dv));
+ }
+ for (ULONG i = 0; i < resultCount; i++) {
+ SAFE_RELEASE(pnpSDriverObject[i])
+ }
+ }
+ }
+
+ SAFE_RELEASE(wbemServices)
+ SAFE_RELEASE(iter)
+
+ Vector<String> info;
+ info.push_back(driver_name);
+ info.push_back(driver_version);
+
+ return info;
+}
+
OS::DateTime OS_Windows::get_datetime(bool p_utc) const {
SYSTEMTIME systemtime;
if (p_utc) {
@@ -1123,15 +1221,7 @@ Error OS_Windows::move_to_trash(const String &p_path) {
}
OS_Windows::OS_Windows(HINSTANCE _hInstance) {
- ticks_per_second = 0;
- ticks_start = 0;
- main_loop = nullptr;
- process_map = nullptr;
-
hInstance = _hInstance;
-#ifdef STDOUT_FILE
- stdo = fopen("stdout.txt", "wb");
-#endif
#ifdef WASAPI_ENABLED
AudioDriverManager::add_driver(&driver_wasapi);
@@ -1147,11 +1237,8 @@ OS_Windows::OS_Windows(HINSTANCE _hInstance) {
//
// NOTE: The engine does not use ANSI escape codes to color error/warning messages; it uses Windows API calls instead.
// Therefore, error/warning messages are still colored on Windows versions older than 10.
- HANDLE stdoutHandle;
- stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- DWORD outMode = 0;
- outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
-
+ HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
+ DWORD outMode = ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(stdoutHandle, outMode)) {
// Windows 8.1 or below, or Windows 10 prior to Anniversary Update.
print_verbose("Can't set the ENABLE_VIRTUAL_TERMINAL_PROCESSING Windows console mode. `print_rich()` will not work as expected.");
@@ -1163,7 +1250,4 @@ OS_Windows::OS_Windows(HINSTANCE _hInstance) {
}
OS_Windows::~OS_Windows() {
-#ifdef STDOUT_FILE
- fclose(stdo);
-#endif
}
diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h
index b792f6fa44..bf934bce64 100644
--- a/platform/windows/os_windows.h
+++ b/platform/windows/os_windows.h
@@ -84,13 +84,10 @@ public:
};
class JoypadWindows;
-class OS_Windows : public OS {
-#ifdef STDOUT_FILE
- FILE *stdo = nullptr;
-#endif
- uint64_t ticks_start;
- uint64_t ticks_per_second;
+class OS_Windows : public OS {
+ uint64_t ticks_start = 0;
+ uint64_t ticks_per_second = 0;
HINSTANCE hInstance;
MainLoop *main_loop = nullptr;
@@ -130,7 +127,7 @@ protected:
STARTUPINFO si;
PROCESS_INFORMATION pi;
};
- HashMap<ProcessID, ProcessInfo> *process_map;
+ HashMap<ProcessID, ProcessInfo> *process_map = nullptr;
public:
virtual void alert(const String &p_alert, const String &p_title = "ALERT!") override;
@@ -147,6 +144,8 @@ public:
virtual String get_distribution_name() const override;
virtual String get_version() const override;
+ virtual Vector<String> get_video_adapter_driver_info() const override;
+
virtual void initialize_joypads() override {}
virtual DateTime get_datetime(bool p_utc) const override;
diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp
index aeaaaf3aec..aa7df4ea9c 100644
--- a/scene/2d/camera_2d.cpp
+++ b/scene/2d/camera_2d.cpp
@@ -155,11 +155,11 @@ Transform2D Camera2D::get_camera_transform() {
}
}
- if (smoothing_enabled && !Engine::get_singleton()->is_editor_hint()) {
- real_t c = smoothing * (process_callback == CAMERA2D_PROCESS_PHYSICS ? get_physics_process_delta_time() : get_process_delta_time());
+ if (follow_smoothing_enabled && !Engine::get_singleton()->is_editor_hint()) {
+ real_t c = position_smoothing_speed * (process_callback == CAMERA2D_PROCESS_PHYSICS ? get_physics_process_delta_time() : get_process_delta_time());
smoothed_camera_pos = ((camera_pos - smoothed_camera_pos) * c) + smoothed_camera_pos;
ret_camera_pos = smoothed_camera_pos;
- //camera_pos=camera_pos*(1.0-smoothing)+new_camera_pos*smoothing;
+ //camera_pos=camera_pos*(1.0-position_smoothing_speed)+new_camera_pos*position_smoothing_speed;
} else {
ret_camera_pos = smoothed_camera_pos = camera_pos;
}
@@ -183,7 +183,7 @@ Transform2D Camera2D::get_camera_transform() {
Rect2 screen_rect(-screen_offset + ret_camera_pos, screen_size * zoom_scale);
- if (!smoothing_enabled || !limit_smoothing_enabled) {
+ if (!follow_smoothing_enabled || !limit_smoothing_enabled) {
if (screen_rect.position.x < limit[SIDE_LEFT]) {
screen_rect.position.x = limit[SIDE_LEFT];
}
@@ -428,7 +428,7 @@ void Camera2D::set_current(bool p_current) {
void Camera2D::_update_process_internal_for_smoothing() {
bool is_not_in_scene_or_editor = !(is_inside_tree() && Engine::get_singleton()->is_editor_hint());
- bool is_any_smoothing_valid = smoothing > 0 || rotation_smoothing_speed > 0;
+ bool is_any_smoothing_valid = position_smoothing_speed > 0 || rotation_smoothing_speed > 0;
bool enabled = is_any_smoothing_valid && is_not_in_scene_or_editor;
set_process_internal(enabled);
@@ -525,13 +525,13 @@ void Camera2D::align() {
_update_scroll();
}
-void Camera2D::set_follow_smoothing(real_t p_speed) {
- smoothing = p_speed;
+void Camera2D::set_position_smoothing_speed(real_t p_speed) {
+ position_smoothing_speed = p_speed;
_update_process_internal_for_smoothing();
}
-real_t Camera2D::get_follow_smoothing() const {
- return smoothing;
+real_t Camera2D::get_position_smoothing_speed() const {
+ return position_smoothing_speed;
}
void Camera2D::set_rotation_smoothing_speed(real_t p_speed) {
@@ -607,18 +607,18 @@ real_t Camera2D::get_drag_horizontal_offset() const {
void Camera2D::_set_old_smoothing(real_t p_enable) {
//compatibility
if (p_enable > 0) {
- smoothing_enabled = true;
- set_follow_smoothing(p_enable);
+ follow_smoothing_enabled = true;
+ set_position_smoothing_speed(p_enable);
}
}
-void Camera2D::set_enable_follow_smoothing(bool p_enabled) {
- smoothing_enabled = p_enabled;
+void Camera2D::set_position_smoothing_enabled(bool p_enabled) {
+ follow_smoothing_enabled = p_enabled;
notify_property_list_changed();
}
-bool Camera2D::is_follow_smoothing_enabled() const {
- return smoothing_enabled;
+bool Camera2D::is_position_smoothing_enabled() const {
+ return follow_smoothing_enabled;
}
void Camera2D::set_custom_viewport(Node *p_viewport) {
@@ -689,7 +689,7 @@ bool Camera2D::is_margin_drawing_enabled() const {
}
void Camera2D::_validate_property(PropertyInfo &p_property) const {
- if (!smoothing_enabled && p_property.name == "smoothing_speed") {
+ if (!follow_smoothing_enabled && p_property.name == "smoothing_speed") {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
if (!rotation_smoothing_enabled && p_property.name == "rotation_smoothing_speed") {
@@ -746,11 +746,11 @@ void Camera2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_custom_viewport", "viewport"), &Camera2D::set_custom_viewport);
ClassDB::bind_method(D_METHOD("get_custom_viewport"), &Camera2D::get_custom_viewport);
- ClassDB::bind_method(D_METHOD("set_follow_smoothing", "follow_smoothing"), &Camera2D::set_follow_smoothing);
- ClassDB::bind_method(D_METHOD("get_follow_smoothing"), &Camera2D::get_follow_smoothing);
+ ClassDB::bind_method(D_METHOD("set_position_smoothing_speed", "position_smoothing_speed"), &Camera2D::set_position_smoothing_speed);
+ ClassDB::bind_method(D_METHOD("get_position_smoothing_speed"), &Camera2D::get_position_smoothing_speed);
- ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing", "follow_smoothing"), &Camera2D::set_enable_follow_smoothing);
- ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"), &Camera2D::is_follow_smoothing_enabled);
+ ClassDB::bind_method(D_METHOD("set_position_smoothing_enabled", "position_smoothing_speed"), &Camera2D::set_position_smoothing_enabled);
+ ClassDB::bind_method(D_METHOD("is_position_smoothing_enabled"), &Camera2D::is_position_smoothing_enabled);
ClassDB::bind_method(D_METHOD("set_rotation_smoothing_enabled", "enabled"), &Camera2D::set_rotation_smoothing_enabled);
ClassDB::bind_method(D_METHOD("is_rotation_smoothing_enabled"), &Camera2D::is_rotation_smoothing_enabled);
@@ -788,9 +788,9 @@ void Camera2D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_bottom", PROPERTY_HINT_NONE, "suffix:px"), "set_limit", "get_limit", SIDE_BOTTOM);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "limit_smoothed"), "set_limit_smoothing_enabled", "is_limit_smoothing_enabled");
- ADD_GROUP("Smoothing", "smoothing_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smoothing_enabled"), "set_enable_follow_smoothing", "is_follow_smoothing_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "smoothing_speed", PROPERTY_HINT_NONE, "suffix:px/s"), "set_follow_smoothing", "get_follow_smoothing");
+ ADD_GROUP("Follow Smoothing", "follow_smoothing_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "position_smoothing_enabled"), "set_position_smoothing_enabled", "is_position_smoothing_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "position_smoothing_speed", PROPERTY_HINT_NONE, "suffix:px/s"), "set_position_smoothing_speed", "get_position_smoothing_speed");
ADD_GROUP("Rotation Smoothing", "rotation_smoothing_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rotation_smoothing_enabled"), "set_rotation_smoothing_enabled", "is_rotation_smoothing_enabled");
diff --git a/scene/2d/camera_2d.h b/scene/2d/camera_2d.h
index 1411175af2..ae172f47b1 100644
--- a/scene/2d/camera_2d.h
+++ b/scene/2d/camera_2d.h
@@ -65,8 +65,8 @@ protected:
AnchorMode anchor_mode = ANCHOR_MODE_DRAG_CENTER;
bool ignore_rotation = true;
bool current = false;
- real_t smoothing = 5.0;
- bool smoothing_enabled = false;
+ real_t position_smoothing_speed = 5.0;
+ bool follow_smoothing_enabled = false;
real_t camera_angle = 0.0;
real_t rotation_smoothing_speed = 5.0;
@@ -140,11 +140,11 @@ public:
void set_drag_vertical_offset(real_t p_offset);
real_t get_drag_vertical_offset() const;
- void set_enable_follow_smoothing(bool p_enabled);
- bool is_follow_smoothing_enabled() const;
+ void set_position_smoothing_enabled(bool p_enabled);
+ bool is_position_smoothing_enabled() const;
- void set_follow_smoothing(real_t p_speed);
- real_t get_follow_smoothing() const;
+ void set_position_smoothing_speed(real_t p_speed);
+ real_t get_position_smoothing_speed() const;
void set_rotation_smoothing_speed(real_t p_speed);
real_t get_rotation_smoothing_speed() const;
diff --git a/scene/2d/light_2d.cpp b/scene/2d/light_2d.cpp
index 90402260ed..78b5199358 100644
--- a/scene/2d/light_2d.cpp
+++ b/scene/2d/light_2d.cpp
@@ -172,6 +172,7 @@ void Light2D::set_shadow_filter(ShadowFilter p_filter) {
ERR_FAIL_INDEX(p_filter, SHADOW_FILTER_MAX);
shadow_filter = p_filter;
RS::get_singleton()->canvas_light_set_shadow_filter(canvas_light, RS::CanvasLightShadowFilter(p_filter));
+ notify_property_list_changed();
}
Light2D::ShadowFilter Light2D::get_shadow_filter() const {
@@ -231,6 +232,10 @@ void Light2D::_validate_property(PropertyInfo &p_property) const {
if (!shadow && (p_property.name == "shadow_color" || p_property.name == "shadow_filter" || p_property.name == "shadow_filter_smooth" || p_property.name == "shadow_item_cull_mask")) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
+
+ if (shadow && p_property.name == "shadow_filter_smooth" && shadow_filter == SHADOW_FILTER_NONE) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
}
void Light2D::_bind_methods() {
@@ -454,7 +459,7 @@ void DirectionalLight2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_max_distance", "pixels"), &DirectionalLight2D::set_max_distance);
ClassDB::bind_method(D_METHOD("get_max_distance"), &DirectionalLight2D::get_max_distance);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "height", PROPERTY_HINT_RANGE, "0,1,0.01,suffix:px"), "set_height", "get_height");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "height", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_height", "get_height");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "0,16384.0,1.0,or_greater,suffix:px"), "set_max_distance", "get_max_distance");
}
diff --git a/scene/2d/navigation_agent_2d.cpp b/scene/2d/navigation_agent_2d.cpp
index f077f7f5e6..748fbbe2d1 100644
--- a/scene/2d/navigation_agent_2d.cpp
+++ b/scene/2d/navigation_agent_2d.cpp
@@ -104,7 +104,7 @@ void NavigationAgent2D::_bind_methods() {
ADD_SIGNAL(MethodInfo("path_changed"));
ADD_SIGNAL(MethodInfo("target_reached"));
ADD_SIGNAL(MethodInfo("navigation_finished"));
- ADD_SIGNAL(MethodInfo("velocity_computed", PropertyInfo(Variant::VECTOR3, "safe_velocity")));
+ ADD_SIGNAL(MethodInfo("velocity_computed", PropertyInfo(Variant::VECTOR2, "safe_velocity")));
}
void NavigationAgent2D::_notification(int p_what) {
@@ -478,8 +478,8 @@ void NavigationAgent2D::_request_repath() {
void NavigationAgent2D::_check_distance_to_target() {
if (!target_reached) {
if (distance_to_target() < target_desired_distance) {
- emit_signal(SNAME("target_reached"));
target_reached = true;
+ emit_signal(SNAME("target_reached"));
}
}
}
diff --git a/scene/2d/skeleton_2d.cpp b/scene/2d/skeleton_2d.cpp
index dd016d5e92..f80b2a07c9 100644
--- a/scene/2d/skeleton_2d.cpp
+++ b/scene/2d/skeleton_2d.cpp
@@ -192,10 +192,8 @@ void Bone2D::_notification(int p_what) {
cache_transform = tmp_trans;
} break;
- // Bone2D Editor gizmo drawing:
-#ifndef _MSC_VER
-#warning TODO Bone2D gizmo drawing needs to be moved to an editor plugin
-#endif
+ // Bone2D Editor gizmo drawing.
+ // TODO: Bone2D gizmo drawing needs to be moved to an editor plugin.
case NOTIFICATION_DRAW: {
// Only draw the gizmo in the editor!
if (Engine::get_singleton()->is_editor_hint() == false) {
diff --git a/scene/2d/sprite_2d.cpp b/scene/2d/sprite_2d.cpp
index 0ecf8333a0..0784318442 100644
--- a/scene/2d/sprite_2d.cpp
+++ b/scene/2d/sprite_2d.cpp
@@ -309,9 +309,7 @@ bool Sprite2D::is_pixel_opaque(const Point2 &p_point) const {
q.y = 1.0f - q.y;
}
q = q * src_rect.size + src_rect.position;
-#ifndef _MSC_VER
-#warning this need to be obtained from CanvasItem new repeat mode (but it needs to guess it from hierarchy, need to add a function for that)
-#endif
+ // TODO: This need to be obtained from CanvasItem new repeat mode (but it needs to guess it from hierarchy, need to add a function for that).
bool is_repeat = false;
bool is_mirrored_repeat = false;
if (is_repeat) {
@@ -446,7 +444,7 @@ void Sprite2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes");
ADD_PROPERTY(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "frame_coords", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_EDITOR), "set_frame_coords", "get_frame_coords");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "frame_coords", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_frame_coords", "get_frame_coords");
ADD_GROUP("Region", "region_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "region_enabled"), "set_region_enabled", "is_region_enabled");
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index 26627a4fca..e865806a7f 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -1097,8 +1097,8 @@ void TileMap::_rendering_update_layer(int p_layer) {
rs->canvas_item_set_sort_children_by_y(ci, layers[p_layer].y_sort_enabled);
rs->canvas_item_set_use_parent_material(ci, get_use_parent_material() || get_material().is_valid());
rs->canvas_item_set_z_index(ci, layers[p_layer].z_index);
- rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter()));
- rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat()));
+ rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
+ rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
rs->canvas_item_set_light_mask(ci, get_light_mask());
}
@@ -1208,8 +1208,8 @@ void TileMap::_rendering_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
rs->canvas_item_set_z_as_relative_to_parent(ci, true);
rs->canvas_item_set_z_index(ci, tile_z_index);
- rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter()));
- rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat()));
+ rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
+ rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
q.canvas_items.push_back(ci);
@@ -2206,11 +2206,10 @@ void TileMap::set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPat
}
}
-TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints) {
+TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints, TileSet::TerrainsPattern p_current_pattern) {
if (!tile_set.is_valid()) {
return TileSet::TerrainsPattern();
}
-
// Returns all tiles compatible with the given constraints.
RBMap<TileSet::TerrainsPattern, int> terrain_pattern_score;
RBSet<TileSet::TerrainsPattern> pattern_set = tile_set->get_terrains_pattern_set(p_terrain_set);
@@ -2221,28 +2220,41 @@ TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int
// Check the center bit constraint
TerrainConstraint terrain_constraint = TerrainConstraint(this, p_position, terrain_pattern.get_terrain());
RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
- if (in_set_constraint_element && in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
- score += in_set_constraint_element->get().get_priority();
+ if (in_set_constraint_element) {
+ if (in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
+ score += in_set_constraint_element->get().get_priority();
+ }
+ } else if (p_current_pattern.get_terrain() != terrain_pattern.get_terrain()) {
+ continue; // Ignore a pattern that cannot keep bits without constraints unmodified.
}
// Check the surrounding bits
+ bool invalid_pattern = false;
for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
// Check if the bit is compatible with the constraints.
TerrainConstraint terrain_bit_constraint = TerrainConstraint(this, p_position, bit, terrain_pattern.get_terrain_peering_bit(bit));
in_set_constraint_element = p_constraints.find(terrain_bit_constraint);
- if (in_set_constraint_element && in_set_constraint_element->get().get_terrain() != terrain_bit_constraint.get_terrain()) {
- score += in_set_constraint_element->get().get_priority();
+ if (in_set_constraint_element) {
+ if (in_set_constraint_element->get().get_terrain() != terrain_bit_constraint.get_terrain()) {
+ score += in_set_constraint_element->get().get_priority();
+ }
+ } else if (p_current_pattern.get_terrain_peering_bit(bit) != terrain_pattern.get_terrain_peering_bit(bit)) {
+ invalid_pattern = true; // Ignore a pattern that cannot keep bits without constraints unmodified.
+ break;
}
}
}
+ if (invalid_pattern) {
+ continue;
+ }
terrain_pattern_score[terrain_pattern] = score;
}
// Compute the minimum score
- TileSet::TerrainsPattern min_score_pattern;
+ TileSet::TerrainsPattern min_score_pattern = p_current_pattern;
int min_score = INT32_MAX;
for (KeyValue<TileSet::TerrainsPattern, int> E : terrain_pattern_score) {
if (E.value < min_score) {
@@ -2274,7 +2286,7 @@ RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_added_p
return output;
}
-RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_cells_list(int p_layer, const RBSet<Vector2i> &p_cell_list, int p_terrain_set, bool p_ignore_empty_terrains) const {
+RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_painted_cells_list(int p_layer, const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const {
if (!tile_set.is_valid()) {
return RBSet<TerrainConstraint>();
}
@@ -2284,8 +2296,8 @@ RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_cells_l
// Build a set of dummy constraints to get the constrained points.
RBSet<TerrainConstraint> dummy_constraints;
- for (const Vector2i &E : p_cell_list) {
- for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) { // Iterates over sides.
+ for (const Vector2i &E : p_painted) {
+ for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) { // Iterates over neighbor bits.
TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
dummy_constraints.insert(TerrainConstraint(this, E, bit, -1));
@@ -2342,7 +2354,7 @@ RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_cells_l
}
// Add the centers as constraints
- for (Vector2i E_coords : p_cell_list) {
+ for (Vector2i E_coords : p_painted) {
TileData *tile_data = nullptr;
TileMapCell cell = get_cell(p_layer, E_coords);
if (cell.source_id != TileSet::INVALID_SOURCE) {
@@ -2362,7 +2374,7 @@ RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_cells_l
return constraints;
}
-HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_constraints(const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints) {
+HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints) {
if (!tile_set.is_valid()) {
return HashMap<Vector2i, TileSet::TerrainsPattern>();
}
@@ -2378,7 +2390,20 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_constraints(co
const Vector2i &coords = p_to_replace[i];
// Select the best pattern for the given constraints
- TileSet::TerrainsPattern pattern = _get_best_terrain_pattern_for_constraints(p_terrain_set, coords, constraints);
+ TileSet::TerrainsPattern current_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
+ TileMapCell cell = get_cell(p_layer, coords);
+ if (cell.source_id != TileSet::INVALID_SOURCE) {
+ TileSetSource *source = *tile_set->get_source(cell.source_id);
+ TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
+ if (atlas_source) {
+ // Get tile data.
+ TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
+ if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
+ current_pattern = tile_data->get_terrains_pattern();
+ }
+ }
+ }
+ TileSet::TerrainsPattern pattern = _get_best_terrain_pattern_for_constraints(p_terrain_set, coords, constraints, current_pattern);
// Update the constraint set with the new ones
RBSet<TerrainConstraint> new_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, pattern);
@@ -2492,12 +2517,12 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_connect(int p_
}
// Fills in the constraint list from existing tiles.
- for (TerrainConstraint c : _get_terrain_constraints_from_cells_list(p_layer, can_modify_set, p_terrain_set, p_ignore_empty_terrains)) {
+ for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(p_layer, painted_set, p_terrain_set, p_ignore_empty_terrains)) {
constraints.insert(c);
}
// Fill the terrains.
- output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
+ output = terrain_fill_constraints(p_layer, can_modify_list, p_terrain_set, constraints);
return output;
}
@@ -2527,10 +2552,12 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_path(int p_lay
// Build list and set of tiles that can be modified (painted and their surroundings)
Vector<Vector2i> can_modify_list;
RBSet<Vector2i> can_modify_set;
+ RBSet<Vector2i> painted_set;
for (int i = p_path.size() - 1; i >= 0; i--) {
const Vector2i &coords = p_path[i];
can_modify_list.push_back(coords);
can_modify_set.insert(coords);
+ painted_set.insert(coords);
}
for (Vector2i coords : p_path) {
// Find the adequate neighbor
@@ -2563,12 +2590,12 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_path(int p_lay
}
// Fills in the constraint list from existing tiles.
- for (TerrainConstraint c : _get_terrain_constraints_from_cells_list(p_layer, can_modify_set, p_terrain_set, p_ignore_empty_terrains)) {
+ for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(p_layer, painted_set, p_terrain_set, p_ignore_empty_terrains)) {
constraints.insert(c);
}
// Fill the terrains.
- output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
+ output = terrain_fill_constraints(p_layer, can_modify_list, p_terrain_set, constraints);
return output;
}
@@ -2580,10 +2607,12 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_pattern(int p_
// Build list and set of tiles that can be modified (painted and their surroundings).
Vector<Vector2i> can_modify_list;
RBSet<Vector2i> can_modify_set;
+ RBSet<Vector2i> painted_set;
for (int i = p_coords_array.size() - 1; i >= 0; i--) {
const Vector2i &coords = p_coords_array[i];
can_modify_list.push_back(coords);
can_modify_set.insert(coords);
+ painted_set.insert(coords);
}
for (Vector2i coords : p_coords_array) {
// Find the adequate neighbor
@@ -2613,12 +2642,12 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_pattern(int p_
}
// Fills in the constraint list from modified tiles border.
- for (TerrainConstraint c : _get_terrain_constraints_from_cells_list(p_layer, can_modify_set, p_terrain_set, p_ignore_empty_terrains)) {
+ for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(p_layer, painted_set, p_terrain_set, p_ignore_empty_terrains)) {
constraints.insert(c);
}
// Fill the terrains.
- output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
+ output = terrain_fill_constraints(p_layer, can_modify_list, p_terrain_set, constraints);
return output;
}
@@ -2627,14 +2656,38 @@ void TileMap::set_cells_terrain_connect(int p_layer, TypedArray<Vector2i> p_cell
ERR_FAIL_INDEX(p_layer, (int)layers.size());
ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
- Vector<Vector2i> vector_cells;
+ Vector<Vector2i> cells_vector;
+ HashSet<Vector2i> painted_set;
for (int i = 0; i < p_cells.size(); i++) {
- vector_cells.push_back(p_cells[i]);
- }
- HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_connect(p_layer, vector_cells, p_terrain_set, p_terrain, p_ignore_empty_terrains);
- for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &E : terrain_fill_output) {
- TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
- set_cell(p_layer, E.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ cells_vector.push_back(p_cells[i]);
+ painted_set.insert(p_cells[i]);
+ }
+ HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_connect(p_layer, cells_vector, p_terrain_set, p_terrain, p_ignore_empty_terrains);
+ for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
+ if (painted_set.has(kv.key)) {
+ // Paint a random tile with the correct terrain for the painted path.
+ TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
+ set_cell(p_layer, kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ } else {
+ // Avoids updating the painted path from the output if the new pattern is the same as before.
+ TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
+ TileMapCell cell = get_cell(p_layer, kv.key);
+ if (cell.source_id != TileSet::INVALID_SOURCE) {
+ TileSetSource *source = *tile_set->get_source(cell.source_id);
+ TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
+ if (atlas_source) {
+ // Get tile data.
+ TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
+ if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
+ in_map_terrain_pattern = tile_data->get_terrains_pattern();
+ }
+ }
+ }
+ if (in_map_terrain_pattern != kv.value) {
+ TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
+ set_cell(p_layer, kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ }
+ }
}
}
@@ -2644,13 +2697,38 @@ void TileMap::set_cells_terrain_path(int p_layer, TypedArray<Vector2i> p_path, i
ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
Vector<Vector2i> vector_path;
+ HashSet<Vector2i> painted_set;
for (int i = 0; i < p_path.size(); i++) {
vector_path.push_back(p_path[i]);
+ painted_set.insert(p_path[i]);
}
+
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_path(p_layer, vector_path, p_terrain_set, p_terrain, p_ignore_empty_terrains);
- for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &E : terrain_fill_output) {
- TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, E.value);
- set_cell(p_layer, E.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
+ if (painted_set.has(kv.key)) {
+ // Paint a random tile with the correct terrain for the painted path.
+ TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
+ set_cell(p_layer, kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ } else {
+ // Avoids updating the painted path from the output if the new pattern is the same as before.
+ TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
+ TileMapCell cell = get_cell(p_layer, kv.key);
+ if (cell.source_id != TileSet::INVALID_SOURCE) {
+ TileSetSource *source = *tile_set->get_source(cell.source_id);
+ TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
+ if (atlas_source) {
+ // Get tile data.
+ TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
+ if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
+ in_map_terrain_pattern = tile_data->get_terrains_pattern();
+ }
+ }
+ }
+ if (in_map_terrain_pattern != kv.value) {
+ TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
+ set_cell(p_layer, kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
+ }
+ }
}
}
@@ -3717,13 +3795,14 @@ void TileMap::set_use_parent_material(bool p_use_parent_material) {
}
void TileMap::set_texture_filter(TextureFilter p_texture_filter) {
- // Set a default texture filter for the whole tilemap
+ // Set a default texture filter for the whole tilemap.
CanvasItem::set_texture_filter(p_texture_filter);
+ TextureFilter target_filter = get_texture_filter_in_tree();
for (unsigned int layer = 0; layer < layers.size(); layer++) {
for (HashMap<Vector2i, TileMapQuadrant>::Iterator F = layers[layer].quadrant_map.begin(); F; ++F) {
TileMapQuadrant &q = F->value;
for (const RID &ci : q.canvas_items) {
- RenderingServer::get_singleton()->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(p_texture_filter));
+ RenderingServer::get_singleton()->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(target_filter));
_make_quadrant_dirty(F);
}
}
@@ -3732,13 +3811,14 @@ void TileMap::set_texture_filter(TextureFilter p_texture_filter) {
}
void TileMap::set_texture_repeat(CanvasItem::TextureRepeat p_texture_repeat) {
- // Set a default texture repeat for the whole tilemap
+ // Set a default texture repeat for the whole tilemap.
CanvasItem::set_texture_repeat(p_texture_repeat);
+ TextureRepeat target_repeat = get_texture_repeat_in_tree();
for (unsigned int layer = 0; layer < layers.size(); layer++) {
for (HashMap<Vector2i, TileMapQuadrant>::Iterator F = layers[layer].quadrant_map.begin(); F; ++F) {
TileMapQuadrant &q = F->value;
for (const RID &ci : q.canvas_items) {
- RenderingServer::get_singleton()->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(p_texture_repeat));
+ RenderingServer::get_singleton()->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(target_repeat));
_make_quadrant_dirty(F);
}
}
diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h
index d468675e91..7f3e241871 100644
--- a/scene/2d/tile_map.h
+++ b/scene/2d/tile_map.h
@@ -266,9 +266,9 @@ private:
void _scenes_draw_quadrant_debug(TileMapQuadrant *p_quadrant);
// Terrains.
- TileSet::TerrainsPattern _get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints);
+ TileSet::TerrainsPattern _get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints, TileSet::TerrainsPattern p_current_pattern);
RBSet<TerrainConstraint> _get_terrain_constraints_from_added_pattern(Vector2i p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const;
- RBSet<TerrainConstraint> _get_terrain_constraints_from_cells_list(int p_layer, const RBSet<Vector2i> &p_on_map, int p_terrain_set, bool p_ignore_empty_terrains) const;
+ RBSet<TerrainConstraint> _get_terrain_constraints_from_painted_cells_list(int p_layer, const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const;
// Set and get tiles from data arrays.
void _set_tile_data(int p_layer, const Vector<int> &p_data);
@@ -352,7 +352,7 @@ public:
void set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPattern> p_pattern);
// Terrains.
- HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_constraints(const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints); // Not exposed.
+ HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_connect(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains = true); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_path(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains = true); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_pattern(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern, bool p_ignore_empty_terrains = true); // Not exposed.
diff --git a/scene/3d/area_3d.cpp b/scene/3d/area_3d.cpp
index cefa9eceff..c6433e773d 100644
--- a/scene/3d/area_3d.cpp
+++ b/scene/3d/area_3d.cpp
@@ -578,11 +578,11 @@ bool Area3D::is_using_reverb_bus() const {
return use_reverb_bus;
}
-void Area3D::set_reverb_bus(const StringName &p_audio_bus) {
+void Area3D::set_reverb_bus_name(const StringName &p_audio_bus) {
reverb_bus = p_audio_bus;
}
-StringName Area3D::get_reverb_bus() const {
+StringName Area3D::get_reverb_bus_name() const {
for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
if (AudioServer::get_singleton()->get_bus_name(i) == reverb_bus) {
return reverb_bus;
@@ -711,8 +711,8 @@ void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_use_reverb_bus", "enable"), &Area3D::set_use_reverb_bus);
ClassDB::bind_method(D_METHOD("is_using_reverb_bus"), &Area3D::is_using_reverb_bus);
- ClassDB::bind_method(D_METHOD("set_reverb_bus", "name"), &Area3D::set_reverb_bus);
- ClassDB::bind_method(D_METHOD("get_reverb_bus"), &Area3D::get_reverb_bus);
+ ClassDB::bind_method(D_METHOD("set_reverb_bus_name", "name"), &Area3D::set_reverb_bus_name);
+ ClassDB::bind_method(D_METHOD("get_reverb_bus_name"), &Area3D::get_reverb_bus_name);
ClassDB::bind_method(D_METHOD("set_reverb_amount", "amount"), &Area3D::set_reverb_amount);
ClassDB::bind_method(D_METHOD("get_reverb_amount"), &Area3D::get_reverb_amount);
@@ -760,8 +760,8 @@ void Area3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "audio_bus_name", PROPERTY_HINT_ENUM, ""), "set_audio_bus_name", "get_audio_bus_name");
ADD_GROUP("Reverb Bus", "reverb_bus_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reverb_bus_enable"), "set_use_reverb_bus", "is_using_reverb_bus");
- ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "reverb_bus_name", PROPERTY_HINT_ENUM, ""), "set_reverb_bus", "get_reverb_bus");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reverb_bus_enabled"), "set_use_reverb_bus", "is_using_reverb_bus");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "reverb_bus_name", PROPERTY_HINT_ENUM, ""), "set_reverb_bus_name", "get_reverb_bus_name");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "reverb_bus_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_reverb_amount", "get_reverb_amount");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "reverb_bus_uniformity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_reverb_uniformity", "get_reverb_uniformity");
diff --git a/scene/3d/area_3d.h b/scene/3d/area_3d.h
index 2125c35f67..195f9f0d9e 100644
--- a/scene/3d/area_3d.h
+++ b/scene/3d/area_3d.h
@@ -215,8 +215,8 @@ public:
void set_use_reverb_bus(bool p_enable);
bool is_using_reverb_bus() const;
- void set_reverb_bus(const StringName &p_audio_bus);
- StringName get_reverb_bus() const;
+ void set_reverb_bus_name(const StringName &p_audio_bus);
+ StringName get_reverb_bus_name() const;
void set_reverb_amount(float p_amount);
float get_reverb_amount() const;
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index 76cf0d2fd0..40afbdf2ed 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -485,7 +485,7 @@ Vector<AudioFrame> AudioStreamPlayer3D::_update_panning() {
}
if (area->is_using_reverb_bus()) {
- StringName reverb_bus_name = area->get_reverb_bus();
+ StringName reverb_bus_name = area->get_reverb_bus_name();
Vector<AudioFrame> reverb_vol;
_calc_reverb_vol(area, listener_area_pos, output_volume_vector, reverb_vol);
bus_volumes[reverb_bus_name] = reverb_vol;
diff --git a/scene/3d/gpu_particles_collision_3d.cpp b/scene/3d/gpu_particles_collision_3d.cpp
index b3437c4810..2c5df48b75 100644
--- a/scene/3d/gpu_particles_collision_3d.cpp
+++ b/scene/3d/gpu_particles_collision_3d.cpp
@@ -490,9 +490,7 @@ Ref<Image> GPUParticlesCollisionSDF3D::bake() {
params.thickness = th;
_compute_sdf(&params);
- Ref<Image> ret;
- ret.instantiate();
- ret->create(sdf_size.x, sdf_size.y * sdf_size.z, false, Image::FORMAT_RF, cells_data);
+ Ref<Image> ret = Image::create_from_data(sdf_size.x, sdf_size.y * sdf_size.z, false, Image::FORMAT_RF, cells_data);
ret->convert(Image::FORMAT_RH); //convert to half, save space
ret->set_meta("depth", sdf_size.z); //hack, make sure to add to the docs of this function
@@ -532,7 +530,7 @@ void GPUParticlesCollisionSDF3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bake_mask_value", "layer_number"), &GPUParticlesCollisionSDF3D::get_bake_mask_value);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "16,32,64,128,256,512,suffix:px"), "set_resolution", "get_resolution");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "16,32,64,128,256,512"), "set_resolution", "get_resolution");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "thickness", PROPERTY_HINT_RANGE, "0.0,2.0,0.01,suffix:m"), "set_thickness", "get_thickness");
ADD_PROPERTY(PropertyInfo(Variant::INT, "bake_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_bake_mask", "get_bake_mask");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture3D"), "set_texture", "get_texture");
diff --git a/scene/3d/light_3d.cpp b/scene/3d/light_3d.cpp
index 23fd091be6..198dba7811 100644
--- a/scene/3d/light_3d.cpp
+++ b/scene/3d/light_3d.cpp
@@ -165,6 +165,16 @@ AABB Light3D::get_aabb() const {
return AABB();
}
+PackedStringArray Light3D::get_configuration_warnings() const {
+ PackedStringArray warnings = VisualInstance3D::get_configuration_warnings();
+
+ if (!get_scale().is_equal_approx(Vector3(1, 1, 1))) {
+ warnings.push_back(RTR("A light's scale does not affect the visual size of the light."));
+ }
+
+ return warnings;
+}
+
void Light3D::set_bake_mode(BakeMode p_mode) {
bake_mode = p_mode;
RS::get_singleton()->light_set_bake_mode(light, RS::LightBakeMode(p_mode));
@@ -579,7 +589,7 @@ OmniLight3D::ShadowMode OmniLight3D::get_shadow_mode() const {
}
PackedStringArray OmniLight3D::get_configuration_warnings() const {
- PackedStringArray warnings = Node::get_configuration_warnings();
+ PackedStringArray warnings = Light3D::get_configuration_warnings();
if (!has_shadow() && get_projector().is_valid()) {
warnings.push_back(RTR("Projector texture only works with shadows active."));
@@ -609,7 +619,7 @@ OmniLight3D::OmniLight3D() :
}
PackedStringArray SpotLight3D::get_configuration_warnings() const {
- PackedStringArray warnings = Node::get_configuration_warnings();
+ PackedStringArray warnings = Light3D::get_configuration_warnings();
if (has_shadow() && get_param(PARAM_SPOT_ANGLE) >= 90.0) {
warnings.push_back(RTR("A SpotLight3D with an angle wider than 90 degrees cannot cast shadows."));
diff --git a/scene/3d/light_3d.h b/scene/3d/light_3d.h
index 8da45bee79..84d214030b 100644
--- a/scene/3d/light_3d.h
+++ b/scene/3d/light_3d.h
@@ -147,6 +147,7 @@ public:
Color get_correlated_color() const;
virtual AABB get_aabb() const override;
+ virtual PackedStringArray get_configuration_warnings() const override;
Light3D();
~Light3D();
diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp
index 3ea1de57cd..1b5427c80d 100644
--- a/scene/3d/lightmap_gi.cpp
+++ b/scene/3d/lightmap_gi.cpp
@@ -145,10 +145,7 @@ Array LightmapGIData::_get_light_textures_data() const {
for (int i = 0; i < texture_count; i++) {
int texture_slice_count = (i == texture_count - 1 && last_count != 0) ? last_count : slices_per_texture;
- Ref<Image> texture_image;
- texture_image.instantiate();
-
- texture_image->create(slice_width, slice_height * texture_slice_count, false, images[0]->get_format());
+ Ref<Image> texture_image = Image::create_empty(slice_width, slice_height * texture_slice_count, false, images[0]->get_format());
for (int j = 0; j < texture_slice_count; j++) {
texture_image->blit_rect(images[i * slices_per_texture + j], Rect2i(0, 0, slice_width, slice_height), Point2i(0, slice_height * j));
@@ -818,7 +815,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa
}
md.albedo_on_uv2.instantiate();
- md.albedo_on_uv2->create(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
+ md.albedo_on_uv2->set_data(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
}
md.emission_on_uv2 = images[RS::BAKE_CHANNEL_EMISSION];
@@ -1054,7 +1051,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa
} break;
case ENVIRONMENT_MODE_CUSTOM_COLOR: {
environment_image.instantiate();
- environment_image->create(128, 64, false, Image::FORMAT_RGBAF);
+ environment_image->initialize_data(128, 64, false, Image::FORMAT_RGBAF);
Color c = environment_custom_color;
c.r *= environment_custom_energy;
c.g *= environment_custom_energy;
diff --git a/scene/3d/navigation_agent_3d.cpp b/scene/3d/navigation_agent_3d.cpp
index 39068fe83c..f64cabb75c 100644
--- a/scene/3d/navigation_agent_3d.cpp
+++ b/scene/3d/navigation_agent_3d.cpp
@@ -495,8 +495,8 @@ void NavigationAgent3D::_request_repath() {
void NavigationAgent3D::_check_distance_to_target() {
if (!target_reached) {
if (distance_to_target() < target_desired_distance) {
- emit_signal(SNAME("target_reached"));
target_reached = true;
+ emit_signal(SNAME("target_reached"));
}
}
}
diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp
index 5f515acead..1743fa1838 100644
--- a/scene/3d/node_3d.cpp
+++ b/scene/3d/node_3d.cpp
@@ -253,9 +253,7 @@ Vector3 Node3D::get_global_rotation() const {
void Node3D::set_global_rotation(const Vector3 &p_euler_rad) {
Transform3D transform = get_global_transform();
- Basis new_basis = transform.get_basis();
- new_basis.set_euler(p_euler_rad);
- transform.set_basis(new_basis);
+ transform.basis = Basis::from_euler(p_euler_rad);
set_global_transform(transform);
}
diff --git a/scene/3d/node_3d.h b/scene/3d/node_3d.h
index 90c7bc89ef..457f634c34 100644
--- a/scene/3d/node_3d.h
+++ b/scene/3d/node_3d.h
@@ -71,8 +71,8 @@ public:
};
private:
- // For the sake of ease of use, Node3D can operate with Transforms (Basis+Origin), Quaterinon/Scale and Euler Rotation/Scale.
- // Transform and Quaterinon are stored in data.local_transform Basis (so quaternion is not really stored, but converted back/forth from 3x3 matrix on demand).
+ // For the sake of ease of use, Node3D can operate with Transforms (Basis+Origin), Quaternion/Scale and Euler Rotation/Scale.
+ // Transform and Quaternion are stored in data.local_transform Basis (so quaternion is not really stored, but converted back/forth from 3x3 matrix on demand).
// Euler needs to be kept separate because converting to Basis and back may result in a different vector (which is troublesome for users
// editing in the inspector, not only because of the numerical precision loss but because they expect these rotations to be consistent, or support
// "redundant" rotations for animation interpolation, like going from 0 to 720 degrees).
@@ -96,6 +96,7 @@ private:
mutable SelfList<Node> xform_change;
+ // This Data struct is to avoid namespace pollution in derived classes.
struct Data {
mutable Transform3D global_transform;
mutable Transform3D local_transform;
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index cc69a1cc51..be6eab2178 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -810,7 +810,7 @@ void Sprite3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes");
ADD_PROPERTY(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frame_coords", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_EDITOR), "set_frame_coords", "get_frame_coords");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frame_coords", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_frame_coords", "get_frame_coords");
ADD_GROUP("Region", "region_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "region_enabled"), "set_region_enabled", "is_region_enabled");
ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region_rect", PROPERTY_HINT_NONE, "suffix:px"), "set_region_rect", "get_region_rect");
diff --git a/scene/3d/visible_on_screen_notifier_3d.cpp b/scene/3d/visible_on_screen_notifier_3d.cpp
index 2013a93e26..6d4c18a69e 100644
--- a/scene/3d/visible_on_screen_notifier_3d.cpp
+++ b/scene/3d/visible_on_screen_notifier_3d.cpp
@@ -189,7 +189,7 @@ void VisibleOnScreenEnabler3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_enable_node_path"), &VisibleOnScreenEnabler3D::get_enable_node_path);
ADD_GROUP("Enabling", "enable_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "enable_mode", PROPERTY_HINT_ENUM, "Inherit,Always,WhenPaused"), "set_enable_mode", "get_enable_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "enable_mode", PROPERTY_HINT_ENUM, "Inherit,Always,When Paused"), "set_enable_mode", "get_enable_mode");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "enable_node_path"), "set_enable_node_path", "get_enable_node_path");
BIND_ENUM_CONSTANT(ENABLE_MODE_INHERIT);
diff --git a/scene/3d/visual_instance_3d.cpp b/scene/3d/visual_instance_3d.cpp
index e93ad5ecbf..3868d1e42e 100644
--- a/scene/3d/visual_instance_3d.cpp
+++ b/scene/3d/visual_instance_3d.cpp
@@ -40,10 +40,6 @@ AABB VisualInstance3D::get_aabb() const {
return AABB();
}
-AABB VisualInstance3D::get_transformed_aabb() const {
- return get_global_transform().xform(get_aabb());
-}
-
void VisualInstance3D::_update_visibility() {
if (!is_inside_tree()) {
return;
@@ -121,8 +117,6 @@ void VisualInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_layer_mask_value", "layer_number", "value"), &VisualInstance3D::set_layer_mask_value);
ClassDB::bind_method(D_METHOD("get_layer_mask_value", "layer_number"), &VisualInstance3D::get_layer_mask_value);
- ClassDB::bind_method(D_METHOD("get_transformed_aabb"), &VisualInstance3D::get_transformed_aabb);
-
GDVIRTUAL_BIND(_get_aabb);
ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask");
}
diff --git a/scene/3d/visual_instance_3d.h b/scene/3d/visual_instance_3d.h
index 4755545516..06a8c05faa 100644
--- a/scene/3d/visual_instance_3d.h
+++ b/scene/3d/visual_instance_3d.h
@@ -60,8 +60,6 @@ public:
RID get_instance() const;
virtual AABB get_aabb() const;
- virtual AABB get_transformed_aabb() const; // helper
-
void set_base(const RID &p_base);
RID get_base() const;
diff --git a/scene/3d/voxel_gi.cpp b/scene/3d/voxel_gi.cpp
index 3dba0221bb..7caf2f4874 100644
--- a/scene/3d/voxel_gi.cpp
+++ b/scene/3d/voxel_gi.cpp
@@ -77,9 +77,7 @@ Dictionary VoxelGIData::_get_data() const {
d["octree_cells"] = get_octree_cells();
d["octree_data"] = get_data_cells();
if (otsize != Vector3i()) {
- Ref<Image> img;
- img.instantiate();
- img->create(otsize.x * otsize.y, otsize.z, false, Image::FORMAT_L8, get_distance_field());
+ Ref<Image> img = Image::create_from_data(otsize.x * otsize.y, otsize.z, false, Image::FORMAT_L8, get_distance_field());
Vector<uint8_t> df_png = img->save_png_to_buffer();
ERR_FAIL_COND_V(df_png.size() == 0, Dictionary());
d["octree_df_png"] = df_png;
diff --git a/scene/3d/xr_nodes.cpp b/scene/3d/xr_nodes.cpp
index 4401d22f30..f5d30c584f 100644
--- a/scene/3d/xr_nodes.cpp
+++ b/scene/3d/xr_nodes.cpp
@@ -36,49 +36,37 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
-void XRCamera3D::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_ENTER_TREE: {
- // need to find our XROrigin3D parent and let it know we're its camera!
- XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
- if (origin != nullptr) {
- origin->set_tracked_camera(this);
- }
- } break;
+void XRCamera3D::_bind_tracker() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
- case NOTIFICATION_EXIT_TREE: {
- // need to find our XROrigin3D parent and let it know we're no longer its camera!
- XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
- if (origin != nullptr && origin->get_tracked_camera() == this) {
- origin->set_tracked_camera(nullptr);
- }
- } break;
+ tracker = xr_server->get_tracker(tracker_name);
+ if (tracker.is_valid()) {
+ tracker->connect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
+
+ Ref<XRPose> pose = tracker->get_pose(pose_name);
+ if (pose.is_valid()) {
+ set_transform(pose->get_adjusted_transform());
+ }
}
}
+void XRCamera3D::_unbind_tracker() {
+ if (tracker.is_valid()) {
+ tracker->disconnect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
+ }
+ tracker.unref();
+}
+
void XRCamera3D::_changed_tracker(const StringName p_tracker_name, int p_tracker_type) {
if (p_tracker_name == tracker_name) {
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL(xr_server);
-
- tracker = xr_server->get_tracker(p_tracker_name);
- if (tracker.is_valid()) {
- tracker->connect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
-
- Ref<XRPose> pose = tracker->get_pose(pose_name);
- if (pose.is_valid()) {
- set_transform(pose->get_adjusted_transform());
- }
- }
+ _bind_tracker();
}
}
void XRCamera3D::_removed_tracker(const StringName p_tracker_name, int p_tracker_type) {
if (p_tracker_name == tracker_name) {
- if (tracker.is_valid()) {
- tracker->disconnect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
- }
- tracker.unref();
+ _unbind_tracker();
}
}
@@ -213,6 +201,9 @@ XRCamera3D::XRCamera3D() {
xr_server->connect("tracker_added", callable_mp(this, &XRCamera3D::_changed_tracker));
xr_server->connect("tracker_updated", callable_mp(this, &XRCamera3D::_changed_tracker));
xr_server->connect("tracker_removed", callable_mp(this, &XRCamera3D::_removed_tracker));
+
+ // check if our tracker already exists and if so, bind it...
+ _bind_tracker();
}
XRCamera3D::~XRCamera3D() {
@@ -372,7 +363,7 @@ void XRNode3D::_unbind_tracker() {
}
void XRNode3D::_changed_tracker(const StringName p_tracker_name, int p_tracker_type) {
- if (p_tracker_name == p_tracker_name) {
+ if (tracker_name == p_tracker_name) {
// just in case unref our current tracker
_unbind_tracker();
@@ -382,7 +373,7 @@ void XRNode3D::_changed_tracker(const StringName p_tracker_name, int p_tracker_t
}
void XRNode3D::_removed_tracker(const StringName p_tracker_name, int p_tracker_type) {
- if (p_tracker_name == p_tracker_name) {
+ if (tracker_name == p_tracker_name) {
// unref our tracker, it's no longer available
_unbind_tracker();
}
@@ -582,11 +573,22 @@ Plane XRAnchor3D::get_plane() const {
////////////////////////////////////////////////////////////////////////////////////////////////////
+Vector<XROrigin3D *> XROrigin3D::origin_nodes;
+
PackedStringArray XROrigin3D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
if (is_visible() && is_inside_tree()) {
- if (tracked_camera == nullptr) {
+ bool has_camera = false;
+ for (int i = 0; !has_camera && i < get_child_count(); i++) {
+ XRCamera3D *camera = Object::cast_to<XRCamera3D>(get_child(i));
+ if (camera) {
+ // found it!
+ has_camera = true;
+ }
+ }
+
+ if (!has_camera) {
warnings.push_back(RTR("XROrigin3D requires an XRCamera3D child node."));
}
}
@@ -603,14 +605,10 @@ void XROrigin3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_world_scale", "world_scale"), &XROrigin3D::set_world_scale);
ClassDB::bind_method(D_METHOD("get_world_scale"), &XROrigin3D::get_world_scale);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "world_scale"), "set_world_scale", "get_world_scale");
-}
-void XROrigin3D::set_tracked_camera(XRCamera3D *p_tracked_camera) {
- tracked_camera = p_tracked_camera;
-}
-
-XRCamera3D *XROrigin3D::get_tracked_camera() const {
- return tracked_camera;
+ ClassDB::bind_method(D_METHOD("set_current", "enabled"), &XROrigin3D::set_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &XROrigin3D::is_current);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "set_current", "is_current");
}
real_t XROrigin3D::get_world_scale() const {
@@ -629,6 +627,44 @@ void XROrigin3D::set_world_scale(real_t p_world_scale) {
xr_server->set_world_scale(p_world_scale);
}
+void XROrigin3D::set_current(bool p_enabled) {
+ current = p_enabled;
+
+ if (!is_inside_tree() || Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+
+ // Notify us of any transform changes
+ set_notify_local_transform(current);
+ set_notify_transform(current);
+
+ if (current) {
+ for (int i = 0; i < origin_nodes.size(); i++) {
+ if (origin_nodes[i] != this) {
+ origin_nodes[i]->set_current(false);
+ }
+ }
+ } else {
+ bool found = false;
+ // We no longer have a current origin so find the first one we can make current
+ for (int i = 0; !found && i < origin_nodes.size(); i++) {
+ if (origin_nodes[i] != this) {
+ origin_nodes[i]->set_current(true);
+ found = true;
+ }
+ }
+ }
+}
+
+bool XROrigin3D::is_current() const {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ // return as is
+ return current;
+ } else {
+ return current && is_inside_tree();
+ }
+}
+
void XROrigin3D::_notification(int p_what) {
// get our XRServer
XRServer *xr_server = XRServer::get_singleton();
@@ -636,34 +672,47 @@ void XROrigin3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- set_process_internal(true);
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ if (origin_nodes.is_empty()) {
+ // first entry always becomes current
+ current = true;
+ }
+
+ origin_nodes.push_back(this);
+
+ if (current) {
+ // set this again so we do whatever setup is needed.
+ set_current(true);
+ }
+ }
} break;
case NOTIFICATION_EXIT_TREE: {
- set_process_internal(false);
- } break;
-
- case NOTIFICATION_INTERNAL_PROCESS: {
- // set our world origin to our node transform
- xr_server->set_world_origin(get_global_transform());
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ origin_nodes.erase(this);
- // check if we have a primary interface
- Ref<XRInterface> xr_interface = xr_server->get_primary_interface();
- if (xr_interface.is_valid() && tracked_camera != nullptr) {
- // get our positioning transform for our headset
- Transform3D t = xr_interface->get_camera_transform();
+ if (current) {
+ // We are no longer current
+ set_current(false);
+ }
+ }
+ } break;
- // now apply this to our camera
- tracked_camera->set_transform(t);
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED:
+ case NOTIFICATION_TRANSFORM_CHANGED: {
+ if (current && !Engine::get_singleton()->is_editor_hint()) {
+ xr_server->set_world_origin(get_global_transform());
}
} break;
}
- // send our notification to all active XE interfaces, they may need to react to it also
- for (int i = 0; i < xr_server->get_interface_count(); i++) {
- Ref<XRInterface> interface = xr_server->get_interface(i);
- if (interface.is_valid() && interface->is_initialized()) {
- interface->notification(p_what);
+ if (current) {
+ // send our notification to all active XE interfaces, they may need to react to it also
+ for (int i = 0; i < xr_server->get_interface_count(); i++) {
+ Ref<XRInterface> interface = xr_server->get_interface(i);
+ if (interface.is_valid() && interface->is_initialized()) {
+ interface->notification(p_what);
+ }
}
}
}
diff --git a/scene/3d/xr_nodes.h b/scene/3d/xr_nodes.h
index ef846cc3a3..990fb61983 100644
--- a/scene/3d/xr_nodes.h
+++ b/scene/3d/xr_nodes.h
@@ -48,8 +48,8 @@ protected:
StringName pose_name = "default";
Ref<XRPositionalTracker> tracker;
- void _notification(int p_what);
-
+ void _bind_tracker();
+ void _unbind_tracker();
void _changed_tracker(const StringName p_tracker_name, int p_tracker_type);
void _removed_tracker(const StringName p_tracker_name, int p_tracker_type);
void _pose_changed(const Ref<XRPose> &p_pose);
@@ -180,7 +180,8 @@ class XROrigin3D : public Node3D {
GDCLASS(XROrigin3D, Node3D);
private:
- XRCamera3D *tracked_camera = nullptr;
+ bool current = false;
+ static Vector<XROrigin3D *> origin_nodes; // all origin nodes in tree
protected:
void _notification(int p_what);
@@ -189,12 +190,12 @@ protected:
public:
PackedStringArray get_configuration_warnings() const override;
- void set_tracked_camera(XRCamera3D *p_tracked_camera);
- XRCamera3D *get_tracked_camera() const;
-
real_t get_world_scale() const;
void set_world_scale(real_t p_world_scale);
+ void set_current(bool p_enabled);
+ bool is_current() const;
+
XROrigin3D() {}
~XROrigin3D() {}
};
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index fe67c0886f..e306d00a51 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -109,7 +109,7 @@ bool AnimationPlayer::_set(const StringName &p_name, const Variant &p_value) {
Ref<AnimationLibrary> lib = d[lib_name];
add_animation_library(lib_name, lib);
}
-
+ emit_signal("animation_libraries_updated");
} else if (name.begins_with("next/")) {
String which = name.get_slicec('/', 1);
animation_set_next(which, p_value);
@@ -1274,6 +1274,23 @@ void AnimationPlayer::_animation_set_cache_update() {
}
void AnimationPlayer::_animation_added(const StringName &p_name, const StringName &p_library) {
+ {
+ int at_pos = -1;
+
+ for (uint32_t i = 0; i < animation_libraries.size(); i++) {
+ if (animation_libraries[i].name == p_library) {
+ at_pos = i;
+ break;
+ }
+ }
+
+ ERR_FAIL_COND(at_pos == -1);
+
+ ERR_FAIL_COND(!animation_libraries[at_pos].library->animations.has(p_name));
+
+ _ref_anim(animation_libraries[at_pos].library->animations[p_name]);
+ }
+
_animation_set_cache_update();
}
@@ -1283,6 +1300,12 @@ void AnimationPlayer::_animation_removed(const StringName &p_name, const StringN
if (!animation_set.has(name)) {
return; // No need to update because not the one from the library being used.
}
+
+ AnimationData animation_data = animation_set[name];
+ if (animation_data.animation_library == p_library) {
+ _unref_anim(animation_data.animation);
+ }
+
_animation_set_cache_update();
// Erase blends if needed
@@ -1376,9 +1399,13 @@ Error AnimationPlayer::add_animation_library(const StringName &p_name, const Ref
animation_libraries.insert(insert_pos, ald);
ald.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_name));
- ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_name));
+ ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed).bind(p_name));
ald.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed).bind(p_name));
+ for (const KeyValue<StringName, Ref<Animation>> &K : ald.library->animations) {
+ _ref_anim(K.value);
+ }
+
_animation_set_cache_update();
notify_property_list_changed();
@@ -1399,7 +1426,7 @@ void AnimationPlayer::remove_animation_library(const StringName &p_name) {
ERR_FAIL_COND(at_pos == -1);
animation_libraries[at_pos].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added));
- animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added));
+ animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed));
animation_libraries[at_pos].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed));
stop();
@@ -1438,11 +1465,11 @@ void AnimationPlayer::rename_animation_library(const StringName &p_name, const S
animation_libraries[i].name = p_new_name;
// rename connections
animation_libraries[i].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added));
- animation_libraries[i].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added));
+ animation_libraries[i].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed));
animation_libraries[i].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed));
animation_libraries[i].library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_new_name));
- animation_libraries[i].library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_new_name));
+ animation_libraries[i].library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed).bind(p_new_name));
animation_libraries[i].library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed).bind(p_new_name));
for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) {
@@ -2151,6 +2178,7 @@ void AnimationPlayer::_bind_methods() {
ADD_SIGNAL(MethodInfo("animation_changed", PropertyInfo(Variant::STRING_NAME, "old_name"), PropertyInfo(Variant::STRING_NAME, "new_name")));
ADD_SIGNAL(MethodInfo("animation_started", PropertyInfo(Variant::STRING_NAME, "anim_name")));
ADD_SIGNAL(MethodInfo("animation_list_changed"));
+ ADD_SIGNAL(MethodInfo("animation_libraries_updated"));
ADD_SIGNAL(MethodInfo("caches_cleared"));
BIND_ENUM_CONSTANT(ANIMATION_PROCESS_PHYSICS);
diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp
index af6a99ca62..552345e4fe 100644
--- a/scene/gui/base_button.cpp
+++ b/scene/gui/base_button.cpp
@@ -60,7 +60,7 @@ void BaseButton::gui_input(const Ref<InputEvent> &p_event) {
}
Ref<InputEventMouseButton> mouse_button = p_event;
- bool ui_accept = p_event->is_action("ui_accept") && !p_event->is_echo();
+ bool ui_accept = p_event->is_action("ui_accept", true) && !p_event->is_echo();
bool button_masked = mouse_button.is_valid() && (mouse_button_to_mask(mouse_button->get_button_index()) & button_mask) != MouseButton::NONE;
if (button_masked || ui_accept) {
@@ -349,10 +349,6 @@ Ref<Shortcut> BaseButton::get_shortcut() const {
void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
- if (!_is_focus_owner_in_shortcut_context()) {
- return;
- }
-
if (!is_disabled() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) {
on_action_event(p_event);
accept_event();
@@ -389,34 +385,6 @@ Ref<ButtonGroup> BaseButton::get_button_group() const {
return button_group;
}
-void BaseButton::set_shortcut_context(Node *p_node) {
- if (p_node != nullptr) {
- shortcut_context = p_node->get_instance_id();
- } else {
- shortcut_context = ObjectID();
- }
-}
-
-Node *BaseButton::get_shortcut_context() const {
- Object *ctx_obj = ObjectDB::get_instance(shortcut_context);
- Node *ctx_node = Object::cast_to<Node>(ctx_obj);
-
- return ctx_node;
-}
-
-bool BaseButton::_is_focus_owner_in_shortcut_context() const {
- if (shortcut_context == ObjectID()) {
- // No context, therefore global - always "in" context.
- return true;
- }
-
- Node *ctx_node = get_shortcut_context();
- Control *vp_focus = get_viewport() ? get_viewport()->gui_get_focus_owner() : nullptr;
-
- // If the context is valid and the viewport focus is valid, check if the context is the focus or is a parent of it.
- return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
-}
-
bool BaseButton::_was_pressed_by_mouse() const {
return was_mouse_pressed;
}
@@ -446,9 +414,6 @@ void BaseButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group);
ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group);
- ClassDB::bind_method(D_METHOD("set_shortcut_context", "node"), &BaseButton::set_shortcut_context);
- ClassDB::bind_method(D_METHOD("get_shortcut_context"), &BaseButton::get_shortcut_context);
-
GDVIRTUAL_BIND(_pressed);
GDVIRTUAL_BIND(_toggled, "button_pressed");
@@ -466,7 +431,6 @@ void BaseButton::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "keep_pressed_outside"), "set_keep_pressed_outside", "is_keep_pressed_outside");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut", PROPERTY_HINT_RESOURCE_TYPE, "Shortcut"), "set_shortcut", "get_shortcut");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "button_group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut_context", PROPERTY_HINT_NODE_TYPE, "Node"), "set_shortcut_context", "get_shortcut_context");
BIND_ENUM_CONSTANT(DRAW_NORMAL);
BIND_ENUM_CONSTANT(DRAW_PRESSED);
diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h
index c83b08aadf..7839239800 100644
--- a/scene/gui/base_button.h
+++ b/scene/gui/base_button.h
@@ -81,7 +81,6 @@ protected:
virtual void shortcut_input(const Ref<InputEvent> &p_event) override;
void _notification(int p_what);
- bool _is_focus_owner_in_shortcut_context() const;
bool _was_pressed_by_mouse() const;
GDVIRTUAL0(_pressed)
@@ -132,9 +131,6 @@ public:
void set_button_group(const Ref<ButtonGroup> &p_group);
Ref<ButtonGroup> get_button_group() const;
- void set_shortcut_context(Node *p_node);
- Node *get_shortcut_context() const;
-
BaseButton();
~BaseButton();
};
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index 70707dba11..8a5d04f49c 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -1248,37 +1248,41 @@ bool CodeEdit::is_drawing_executing_lines_gutter() const {
}
void CodeEdit::_main_gutter_draw_callback(int p_line, int p_gutter, const Rect2 &p_region) {
- bool shift_pressed = Input::get_singleton()->is_key_pressed(Key::SHIFT);
-
if (draw_breakpoints && breakpoint_icon.is_valid()) {
- bool hovering = p_region.has_point(get_local_mouse_pos());
bool breakpointed = is_line_breakpointed(p_line);
+ bool hovering = p_region.has_point(get_local_mouse_pos());
+ bool shift_pressed = Input::get_singleton()->is_key_pressed(Key::SHIFT);
if (breakpointed || (hovering && !is_dragging_cursor() && !shift_pressed)) {
int padding = p_region.size.x / 6;
+
+ Color use_color = breakpoint_color;
+ if (hovering && !shift_pressed) {
+ use_color = breakpointed ? use_color.lightened(0.3) : use_color.darkened(0.5);
+ }
Rect2 icon_region = p_region;
icon_region.position += Point2(padding, padding);
icon_region.size -= Point2(padding, padding) * 2;
-
- // Darken icon when hovering, shift not pressed & not yet breakpointed.
- Color use_color = hovering && !breakpointed && !shift_pressed ? breakpoint_color.darkened(0.4) : breakpoint_color;
breakpoint_icon->draw_rect(get_canvas_item(), icon_region, false, use_color);
}
}
if (draw_bookmarks && bookmark_icon.is_valid()) {
- bool hovering = p_region.has_point(get_local_mouse_pos());
bool bookmarked = is_line_bookmarked(p_line);
+ bool hovering = p_region.has_point(get_local_mouse_pos());
+ bool shift_pressed = Input::get_singleton()->is_key_pressed(Key::SHIFT);
if (bookmarked || (hovering && !is_dragging_cursor() && shift_pressed)) {
int horizontal_padding = p_region.size.x / 2;
int vertical_padding = p_region.size.y / 4;
+
+ Color use_color = bookmark_color;
+ if (hovering && shift_pressed) {
+ use_color = bookmarked ? use_color.lightened(0.3) : use_color.darkened(0.5);
+ }
Rect2 icon_region = p_region;
icon_region.position += Point2(horizontal_padding, 0);
icon_region.size -= Point2(horizontal_padding * 1.1, vertical_padding);
-
- // Darken icon when hovering, shift pressed & not yet bookmarked.
- Color use_color = hovering && !bookmarked && shift_pressed ? bookmark_color.darkened(0.4) : bookmark_color;
bookmark_icon->draw_rect(get_canvas_item(), icon_region, false, use_color);
}
}
@@ -1287,10 +1291,10 @@ void CodeEdit::_main_gutter_draw_callback(int p_line, int p_gutter, const Rect2
int horizontal_padding = p_region.size.x / 10;
int vertical_padding = p_region.size.y / 4;
- Rect2 executing_line_region = p_region;
- executing_line_region.position += Point2(horizontal_padding, vertical_padding);
- executing_line_region.size -= Point2(horizontal_padding, vertical_padding) * 2;
- executing_line_icon->draw_rect(get_canvas_item(), executing_line_region, false, executing_line_color);
+ Rect2 icon_region = p_region;
+ icon_region.position += Point2(horizontal_padding, vertical_padding);
+ icon_region.size -= Point2(horizontal_padding, vertical_padding) * 2;
+ executing_line_icon->draw_rect(get_canvas_item(), icon_region, false, executing_line_color);
}
}
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index f1e18640e6..929bf27be6 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -1367,7 +1367,7 @@ void ColorPicker::_screen_input(const Ref<InputEvent> &p_event) {
Ref<Image> img = r->get_texture()->get_image();
if (img.is_valid() && !img->is_empty()) {
- Vector2 ofs = mev->get_global_position() - r->get_visible_rect().get_position();
+ Vector2 ofs = mev->get_global_position();
Color c = img->get_pixel(ofs.x, ofs.y);
set_pick_color(c);
@@ -1403,9 +1403,7 @@ void ColorPicker::_screen_pick_pressed() {
screen->show();
}
screen->move_to_front();
-#ifndef _MSC_VER
-#warning show modal no longer works, needs to be converted to a popup
-#endif
+ // TODO: show modal no longer works, needs to be converted to a popup.
//screen->show_modal();
}
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index 2dcae2553c..2ec0a48278 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -1436,13 +1436,6 @@ Rect2 Control::get_screen_rect() const {
return r;
}
-Rect2 Control::get_window_rect() const {
- ERR_FAIL_COND_V(!is_inside_tree(), Rect2());
- Rect2 gr = get_global_rect();
- gr.position += get_viewport()->get_visible_rect().position;
- return gr;
-}
-
Rect2 Control::get_anchorable_rect() const {
return Rect2(Point2(), get_size());
}
@@ -1564,7 +1557,7 @@ Size2 Control::get_minimum_size() const {
return Vector2();
}
-void Control::set_custom_minimum_size(const Size2i &p_custom) {
+void Control::set_custom_minimum_size(const Size2 &p_custom) {
if (p_custom == data.custom_minimum_size) {
return;
}
@@ -1572,7 +1565,7 @@ void Control::set_custom_minimum_size(const Size2i &p_custom) {
update_minimum_size();
}
-Size2i Control::get_custom_minimum_size() const {
+Size2 Control::get_custom_minimum_size() const {
return data.custom_minimum_size;
}
@@ -1759,6 +1752,34 @@ void Control::warp_mouse(const Point2 &p_position) {
get_viewport()->warp_mouse(get_global_transform_with_canvas().xform(p_position));
}
+void Control::set_shortcut_context(const Node *p_node) {
+ if (p_node != nullptr) {
+ data.shortcut_context = p_node->get_instance_id();
+ } else {
+ data.shortcut_context = ObjectID();
+ }
+}
+
+Node *Control::get_shortcut_context() const {
+ Object *ctx_obj = ObjectDB::get_instance(data.shortcut_context);
+ Node *ctx_node = Object::cast_to<Node>(ctx_obj);
+
+ return ctx_node;
+}
+
+bool Control::is_focus_owner_in_shortcut_context() const {
+ if (data.shortcut_context == ObjectID()) {
+ // No context, therefore global - always "in" context.
+ return true;
+ }
+
+ const Node *ctx_node = get_shortcut_context();
+ const Control *vp_focus = get_viewport() ? get_viewport()->gui_get_focus_owner() : nullptr;
+
+ // If the context is valid and the viewport focus is valid, check if the context is the focus or is a parent of it.
+ return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
+}
+
// Drag and drop handling.
void Control::set_drag_forwarding(Object *p_target) {
@@ -2885,8 +2906,8 @@ void Control::_notification(int p_notification) {
if (data.parent_canvas_item) {
data.parent_canvas_item->disconnect("item_rect_changed", callable_mp(this, &Control::_size_changed));
data.parent_canvas_item = nullptr;
- } else if (!is_set_as_top_level()) {
- //disconnect viewport
+ } else {
+ // Disconnect viewport.
Viewport *viewport = get_viewport();
ERR_FAIL_COND(!viewport);
viewport->disconnect("size_changed", callable_mp(this, &Control::_size_changed));
@@ -3133,6 +3154,9 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Control::warp_mouse);
+ ClassDB::bind_method(D_METHOD("set_shortcut_context", "node"), &Control::set_shortcut_context);
+ ClassDB::bind_method(D_METHOD("get_shortcut_context"), &Control::get_shortcut_context);
+
ClassDB::bind_method(D_METHOD("update_minimum_size"), &Control::update_minimum_size);
ClassDB::bind_method(D_METHOD("set_layout_direction", "direction"), &Control::set_layout_direction);
@@ -3144,7 +3168,7 @@ void Control::_bind_methods() {
ADD_GROUP("Layout", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_contents"), "set_clip_contents", "is_clipping_contents");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "custom_minimum_size", PROPERTY_HINT_NONE, "suffix:px"), "set_custom_minimum_size", "get_custom_minimum_size");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "custom_minimum_size", PROPERTY_HINT_NONE, "suffix:px"), "set_custom_minimum_size", "get_custom_minimum_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "layout_direction", PROPERTY_HINT_ENUM, "Inherited,Locale,Left-to-Right,Right-to-Left"), "set_layout_direction", "get_layout_direction");
ADD_PROPERTY(PropertyInfo(Variant::INT, "layout_mode", PROPERTY_HINT_ENUM, "Position,Anchors,Container,Uncontrolled", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "_set_layout_mode", "_get_layout_mode");
ADD_PROPERTY_DEFAULT("layout_mode", LayoutMode::LAYOUT_MODE_POSITION);
@@ -3206,6 +3230,9 @@ void Control::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "mouse_force_pass_scroll_events"), "set_force_pass_scroll_events", "is_force_pass_scroll_events");
ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_default_cursor_shape", PROPERTY_HINT_ENUM, "Arrow,I-Beam,Pointing Hand,Cross,Wait,Busy,Drag,Can Drop,Forbidden,Vertical Resize,Horizontal Resize,Secondary Diagonal Resize,Main Diagonal Resize,Move,Vertical Split,Horizontal Split,Help"), "set_default_cursor_shape", "get_default_cursor_shape");
+ ADD_GROUP("Input", "");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut_context", PROPERTY_HINT_NODE_TYPE, "Node"), "set_shortcut_context", "get_shortcut_context");
+
ADD_GROUP("Theme", "theme_");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "Theme"), "set_theme", "get_theme");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "theme_type_variation", PROPERTY_HINT_ENUM_SUGGESTION), "set_theme_type_variation", "get_theme_type_variation");
diff --git a/scene/gui/control.h b/scene/gui/control.h
index ee6443c81c..72e870930d 100644
--- a/scene/gui/control.h
+++ b/scene/gui/control.h
@@ -159,6 +159,7 @@ private:
}
};
+ // This Data struct is to avoid namespace pollution in derived classes.
struct Data {
// Global relations.
@@ -200,7 +201,7 @@ private:
int h_size_flags = SIZE_FILL;
int v_size_flags = SIZE_FILL;
real_t expand = 1.0;
- Point2i custom_minimum_size;
+ Point2 custom_minimum_size;
// Input events and rendering.
@@ -218,6 +219,8 @@ private:
NodePath focus_next;
NodePath focus_prev;
+ ObjectID shortcut_context;
+
// Theming.
ThemeOwner *theme_owner = nullptr;
@@ -442,7 +445,6 @@ public:
Rect2 get_rect() const;
Rect2 get_global_rect() const;
Rect2 get_screen_rect() const;
- Rect2 get_window_rect() const; ///< use with care, as it blocks waiting for the rendering server
Rect2 get_anchorable_rect() const override;
void set_scale(const Vector2 &p_scale);
@@ -460,8 +462,8 @@ public:
virtual Size2 get_minimum_size() const;
virtual Size2 get_combined_minimum_size() const;
- void set_custom_minimum_size(const Size2i &p_custom);
- Size2i get_custom_minimum_size() const;
+ void set_custom_minimum_size(const Size2 &p_custom);
+ Size2 get_custom_minimum_size() const;
// Container sizing.
@@ -487,6 +489,10 @@ public:
void warp_mouse(const Point2 &p_position);
+ bool is_focus_owner_in_shortcut_context() const;
+ void set_shortcut_context(const Node *p_node);
+ Node *get_shortcut_context() const;
+
// Drag and drop handling.
virtual void set_drag_forwarding(Object *p_target);
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index 90552c32c2..caf8db4515 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -1385,16 +1385,16 @@ void GraphEdit::gui_input(const Ref<InputEvent> &p_ev) {
}
if (p_ev->is_pressed()) {
- if (p_ev->is_action("ui_graph_duplicate")) {
+ if (p_ev->is_action("ui_graph_duplicate", true)) {
emit_signal(SNAME("duplicate_nodes_request"));
accept_event();
- } else if (p_ev->is_action("ui_copy")) {
+ } else if (p_ev->is_action("ui_copy", true)) {
emit_signal(SNAME("copy_nodes_request"));
accept_event();
- } else if (p_ev->is_action("ui_paste")) {
+ } else if (p_ev->is_action("ui_paste", true)) {
emit_signal(SNAME("paste_nodes_request"));
accept_event();
- } else if (p_ev->is_action("ui_graph_delete")) {
+ } else if (p_ev->is_action("ui_graph_delete", true)) {
TypedArray<StringName> nodes;
for (int i = 0; i < get_child_count(); i++) {
diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp
index 0dc791f71d..223428906a 100644
--- a/scene/gui/item_list.cpp
+++ b/scene/gui/item_list.cpp
@@ -728,7 +728,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
}
if (p_event->is_pressed() && items.size() > 0) {
- if (p_event->is_action("ui_up")) {
+ if (p_event->is_action("ui_up", true)) {
if (!search_string.is_empty()) {
uint64_t now = OS::get_singleton()->get_ticks_msec();
uint64_t diff = now - search_time_msec;
@@ -766,7 +766,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
}
accept_event();
}
- } else if (p_event->is_action("ui_down")) {
+ } else if (p_event->is_action("ui_down", true)) {
if (!search_string.is_empty()) {
uint64_t now = OS::get_singleton()->get_ticks_msec();
uint64_t diff = now - search_time_msec;
@@ -803,7 +803,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
}
accept_event();
}
- } else if (p_event->is_action("ui_page_up")) {
+ } else if (p_event->is_action("ui_page_up", true)) {
search_string = ""; //any mousepress cancels
for (int i = 4; i > 0; i--) {
@@ -817,7 +817,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
break;
}
}
- } else if (p_event->is_action("ui_page_down")) {
+ } else if (p_event->is_action("ui_page_down", true)) {
search_string = ""; //any mousepress cancels
for (int i = 4; i > 0; i--) {
@@ -832,7 +832,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
break;
}
}
- } else if (p_event->is_action("ui_left")) {
+ } else if (p_event->is_action("ui_left", true)) {
search_string = ""; //any mousepress cancels
if (current % current_columns != 0) {
@@ -852,7 +852,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
}
accept_event();
}
- } else if (p_event->is_action("ui_right")) {
+ } else if (p_event->is_action("ui_right", true)) {
search_string = ""; //any mousepress cancels
if (current % current_columns != (current_columns - 1) && current + 1 < items.size()) {
@@ -872,9 +872,9 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
}
accept_event();
}
- } else if (p_event->is_action("ui_cancel")) {
+ } else if (p_event->is_action("ui_cancel", true)) {
search_string = "";
- } else if (p_event->is_action("ui_select") && select_mode == SELECT_MULTI) {
+ } else if (p_event->is_action("ui_select", true) && select_mode == SELECT_MULTI) {
if (current >= 0 && current < items.size()) {
if (items[current].selectable && !items[current].disabled && !items[current].selected) {
select(current, false);
@@ -884,7 +884,7 @@ void ItemList::gui_input(const Ref<InputEvent> &p_event) {
emit_signal(SNAME("multi_selected"), current, false);
}
}
- } else if (p_event->is_action("ui_accept")) {
+ } else if (p_event->is_action("ui_accept", true)) {
search_string = ""; //any mousepress cancels
if (current >= 0 && current < items.size()) {
diff --git a/scene/gui/label.cpp b/scene/gui/label.cpp
index 63401ca195..2203573bbc 100644
--- a/scene/gui/label.cpp
+++ b/scene/gui/label.cpp
@@ -288,6 +288,36 @@ void Label::_update_theme_item_cache() {
theme_cache.font_shadow_outline_size = get_theme_constant(SNAME("shadow_outline_size"));
}
+PackedStringArray Label::get_configuration_warnings() const {
+ PackedStringArray warnings = Control::get_configuration_warnings();
+
+ // Ensure that the font can render all of the required glyphs.
+ Ref<Font> font;
+ if (settings.is_valid()) {
+ font = settings->get_font();
+ }
+ if (font.is_null()) {
+ font = theme_cache.font;
+ }
+
+ if (font.is_valid()) {
+ if (dirty || font_dirty || lines_dirty) {
+ const_cast<Label *>(this)->_shape();
+ }
+
+ const Glyph *glyph = TS->shaped_text_get_glyphs(text_rid);
+ int64_t glyph_count = TS->shaped_text_get_glyph_count(text_rid);
+ for (int64_t i = 0; i < glyph_count; i++) {
+ if (glyph[i].font_rid == RID()) {
+ warnings.push_back(RTR("The current font does not support rendering one or more characters used in this Label's text."));
+ break;
+ }
+ }
+ }
+
+ return warnings;
+}
+
void Label::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_TRANSLATION_CHANGED: {
@@ -302,6 +332,7 @@ void Label::_notification(int p_what) {
dirty = true;
queue_redraw();
+ update_configuration_warnings();
} break;
case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: {
@@ -674,6 +705,7 @@ void Label::set_text(const String &p_string) {
}
queue_redraw();
update_minimum_size();
+ update_configuration_warnings();
}
void Label::_invalidate() {
diff --git a/scene/gui/label.h b/scene/gui/label.h
index b79c94a5ba..41d7049b22 100644
--- a/scene/gui/label.h
+++ b/scene/gui/label.h
@@ -93,6 +93,7 @@ protected:
public:
virtual Size2 get_minimum_size() const override;
+ virtual PackedStringArray get_configuration_warnings() const override;
void set_horizontal_alignment(HorizontalAlignment p_alignment);
HorizontalAlignment get_horizontal_alignment() const;
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index 36e85b5d02..65670b7786 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -2175,6 +2175,12 @@ void LineEdit::_emit_text_change() {
}
void LineEdit::_shape() {
+ const Ref<Font> &font = theme_cache.font;
+ int font_size = theme_cache.font_size;
+ if (font.is_null()) {
+ return;
+ }
+
Size2 old_size = TS->shaped_text_get_size(text_rid);
TS->shaped_text_clear(text_rid);
@@ -2197,9 +2203,6 @@ void LineEdit::_shape() {
}
TS->shaped_text_set_preserve_control(text_rid, draw_control_chars);
- const Ref<Font> &font = theme_cache.font;
- int font_size = theme_cache.font_size;
- ERR_FAIL_COND(font.is_null());
TS->shaped_text_add_string(text_rid, t, font->get_rids(), font_size, font->get_opentype_features(), language);
for (int i = 0; i < TextServer::SPACING_MAX; i++) {
TS->shaped_text_set_spacing(text_rid, TextServer::SpacingType(i), font->get_spacing(TextServer::SpacingType(i)));
diff --git a/scene/gui/menu_bar.cpp b/scene/gui/menu_bar.cpp
index 742042f65f..82ef53e317 100644
--- a/scene/gui/menu_bar.cpp
+++ b/scene/gui/menu_bar.cpp
@@ -41,7 +41,7 @@ void MenuBar::gui_input(const Ref<InputEvent> &p_event) {
}
MutexLock lock(mutex);
- if (p_event->is_action("ui_left") && p_event->is_pressed()) {
+ if (p_event->is_action("ui_left", true) && p_event->is_pressed()) {
int new_sel = selected_menu;
int old_sel = (selected_menu < 0) ? 0 : selected_menu;
do {
@@ -63,7 +63,7 @@ void MenuBar::gui_input(const Ref<InputEvent> &p_event) {
_open_popup(selected_menu, true);
}
return;
- } else if (p_event->is_action("ui_right") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_right", true) && p_event->is_pressed()) {
int new_sel = selected_menu;
int old_sel = (selected_menu < 0) ? menu_cache.size() - 1 : selected_menu;
do {
@@ -149,10 +149,6 @@ void MenuBar::_open_popup(int p_index, bool p_focus_item) {
void MenuBar::shortcut_input(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
- if (!_is_focus_owner_in_shortcut_context()) {
- return;
- }
-
if (disable_shortcuts) {
return;
}
@@ -175,34 +171,6 @@ void MenuBar::shortcut_input(const Ref<InputEvent> &p_event) {
}
}
-void MenuBar::set_shortcut_context(Node *p_node) {
- if (p_node != nullptr) {
- shortcut_context = p_node->get_instance_id();
- } else {
- shortcut_context = ObjectID();
- }
-}
-
-Node *MenuBar::get_shortcut_context() const {
- Object *ctx_obj = ObjectDB::get_instance(shortcut_context);
- Node *ctx_node = Object::cast_to<Node>(ctx_obj);
-
- return ctx_node;
-}
-
-bool MenuBar::_is_focus_owner_in_shortcut_context() const {
- if (shortcut_context == ObjectID()) {
- // No context, therefore global - always "in" context.
- return true;
- }
-
- Node *ctx_node = get_shortcut_context();
- Control *vp_focus = get_viewport() ? get_viewport()->gui_get_focus_owner() : nullptr;
-
- // If the context is valid and the viewport focus is valid, check if the context is the focus or is a parent of it.
- return ctx_node && vp_focus && (ctx_node == vp_focus || ctx_node->is_ancestor_of(vp_focus));
-}
-
void MenuBar::_popup_visibility_changed(bool p_visible) {
if (!p_visible) {
active_menu = -1;
@@ -694,16 +662,12 @@ void MenuBar::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_menu_hidden", "menu", "hidden"), &MenuBar::set_menu_hidden);
ClassDB::bind_method(D_METHOD("is_menu_hidden", "menu"), &MenuBar::is_menu_hidden);
- ClassDB::bind_method(D_METHOD("set_shortcut_context", "node"), &MenuBar::set_shortcut_context);
- ClassDB::bind_method(D_METHOD("get_shortcut_context"), &MenuBar::get_shortcut_context);
-
ClassDB::bind_method(D_METHOD("get_menu_popup", "menu"), &MenuBar::get_menu_popup);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "start_index"), "set_start_index", "get_start_index");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "switch_on_hover"), "set_switch_on_hover", "is_switch_on_hover");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "prefer_global_menu"), "set_prefer_global_menu", "is_prefer_global_menu");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut_context", PROPERTY_HINT_NODE_TYPE, "Node"), "set_shortcut_context", "get_shortcut_context");
ADD_GROUP("BiDi", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left,Inherited"), "set_text_direction", "get_text_direction");
diff --git a/scene/gui/menu_bar.h b/scene/gui/menu_bar.h
index f7ef19e98b..c057a7c96f 100644
--- a/scene/gui/menu_bar.h
+++ b/scene/gui/menu_bar.h
@@ -118,8 +118,6 @@ class MenuBar : public Control {
void _clear_menu();
void _update_menu();
- bool _is_focus_owner_in_shortcut_context() const;
-
protected:
virtual void shortcut_input(const Ref<InputEvent> &p_event) override;
@@ -170,9 +168,6 @@ public:
void set_menu_hidden(int p_menu, bool p_hidden);
bool is_menu_hidden(int p_menu) const;
- void set_shortcut_context(Node *p_node);
- Node *get_shortcut_context() const;
-
PopupMenu *get_menu_popup(int p_menu) const;
virtual void get_translatable_strings(List<String> *p_strings) const override;
diff --git a/scene/gui/menu_button.cpp b/scene/gui/menu_button.cpp
index 78aeab9457..786f23873e 100644
--- a/scene/gui/menu_button.cpp
+++ b/scene/gui/menu_button.cpp
@@ -36,10 +36,6 @@
void MenuButton::shortcut_input(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
- if (!_is_focus_owner_in_shortcut_context()) {
- return;
- }
-
if (disable_shortcuts) {
return;
}
diff --git a/scene/gui/popup.cpp b/scene/gui/popup.cpp
index a6915f9e61..434eb87e7a 100644
--- a/scene/gui/popup.cpp
+++ b/scene/gui/popup.cpp
@@ -77,28 +77,36 @@ void Popup::_update_theme_item_cache() {
void Popup::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_VISIBILITY_CHANGED: {
- if (is_visible()) {
- _initialize_visible_parents();
- } else {
- _deinitialize_visible_parents();
- emit_signal(SNAME("popup_hide"));
- popped_up = false;
+ if (!is_in_edited_scene_root()) {
+ if (is_visible()) {
+ _initialize_visible_parents();
+ } else {
+ _deinitialize_visible_parents();
+ emit_signal(SNAME("popup_hide"));
+ popped_up = false;
+ }
}
} break;
case NOTIFICATION_WM_WINDOW_FOCUS_IN: {
- if (has_focus()) {
- popped_up = true;
+ if (!is_in_edited_scene_root()) {
+ if (has_focus()) {
+ popped_up = true;
+ }
}
} break;
case NOTIFICATION_EXIT_TREE: {
- _deinitialize_visible_parents();
+ if (!is_in_edited_scene_root()) {
+ _deinitialize_visible_parents();
+ }
} break;
case NOTIFICATION_WM_CLOSE_REQUEST:
case NOTIFICATION_APPLICATION_FOCUS_OUT: {
- _close_pressed();
+ if (!is_in_edited_scene_root()) {
+ _close_pressed();
+ }
} break;
}
}
@@ -126,6 +134,16 @@ void Popup::_bind_methods() {
ADD_SIGNAL(MethodInfo("popup_hide"));
}
+void Popup::_validate_property(PropertyInfo &p_property) const {
+ if (
+ p_property.name == "transient" ||
+ p_property.name == "exclusive" ||
+ p_property.name == "popup_window" ||
+ p_property.name == "unfocusable") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+}
+
Rect2i Popup::_popup_adjust_rect() const {
ERR_FAIL_COND_V(!is_inside_tree(), Rect2());
Rect2i parent_rect = get_usable_parent_rect();
diff --git a/scene/gui/popup.h b/scene/gui/popup.h
index 0d6ca25c18..57b811cadb 100644
--- a/scene/gui/popup.h
+++ b/scene/gui/popup.h
@@ -59,6 +59,7 @@ protected:
virtual void _update_theme_item_cache() override;
void _notification(int p_what);
static void _bind_methods();
+ void _validate_property(PropertyInfo &p_property) const;
virtual void _parent_focused();
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 4cdde5902e..9a411ef7ed 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -273,7 +273,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
if (!items.is_empty()) {
- if (p_event->is_action("ui_down") && p_event->is_pressed()) {
+ if (p_event->is_action("ui_down", true) && p_event->is_pressed()) {
int search_from = mouse_over + 1;
if (search_from >= items.size()) {
search_from = 0;
@@ -305,7 +305,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
}
}
}
- } else if (p_event->is_action("ui_up") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_up", true) && p_event->is_pressed()) {
int search_from = mouse_over - 1;
if (search_from < 0) {
search_from = items.size() - 1;
@@ -337,7 +337,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
}
}
}
- } else if (p_event->is_action("ui_left") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_left", true) && p_event->is_pressed()) {
Node *n = get_parent();
if (n) {
if (Object::cast_to<PopupMenu>(n)) {
@@ -349,7 +349,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
return;
}
}
- } else if (p_event->is_action("ui_right") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_right", true) && p_event->is_pressed()) {
if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator && !items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) {
_activate_submenu(mouse_over, true);
set_input_as_handled();
@@ -361,7 +361,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
return;
}
}
- } else if (p_event->is_action("ui_accept") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_accept", true) && p_event->is_pressed()) {
if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator) {
if (!items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) {
_activate_submenu(mouse_over, true);
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index 5060bacba5..c96d3c763d 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -2019,36 +2019,36 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
if (k->is_pressed()) {
bool handled = false;
- if (k->is_action("ui_page_up") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_page_up", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(vscroll->get_value() - vscroll->get_page());
handled = true;
}
- if (k->is_action("ui_page_down") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_page_down", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(vscroll->get_value() + vscroll->get_page());
handled = true;
}
- if (k->is_action("ui_up") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_up", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(vscroll->get_value() - theme_cache.normal_font->get_height(theme_cache.normal_font_size));
handled = true;
}
- if (k->is_action("ui_down") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_down", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(vscroll->get_value() + theme_cache.normal_font->get_height(theme_cache.normal_font_size));
handled = true;
}
- if (k->is_action("ui_home") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_home", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(0);
handled = true;
}
- if (k->is_action("ui_end") && vscroll->is_visible_in_tree()) {
+ if (k->is_action("ui_end", true) && vscroll->is_visible_in_tree()) {
vscroll->set_value(vscroll->get_max());
handled = true;
}
if (is_shortcut_keys_enabled()) {
- if (k->is_action("ui_text_select_all")) {
+ if (k->is_action("ui_text_select_all", true)) {
select_all();
handled = true;
}
- if (k->is_action("ui_copy")) {
+ if (k->is_action("ui_copy", true)) {
selection_copy();
handled = true;
}
@@ -2956,7 +2956,7 @@ void RichTextLabel::_remove_item(Item *p_item, const int p_line, const int p_sub
memdelete(p_item);
}
-void RichTextLabel::add_image(const Ref<Texture2D> &p_image, const int p_width, const int p_height, const Color &p_color, InlineAlignment p_alignment) {
+void RichTextLabel::add_image(const Ref<Texture2D> &p_image, const int p_width, const int p_height, const Color &p_color, InlineAlignment p_alignment, const Rect2 &p_region) {
_stop_thread();
MutexLock data_lock(data_mutex);
@@ -2969,7 +2969,15 @@ void RichTextLabel::add_image(const Ref<Texture2D> &p_image, const int p_width,
ERR_FAIL_COND(p_image->get_height() == 0);
ItemImage *item = memnew(ItemImage);
- item->image = p_image;
+ if (p_region.has_area()) {
+ Ref<AtlasTexture> atlas_tex = memnew(AtlasTexture);
+ atlas_tex->set_atlas(p_image);
+ atlas_tex->set_region(p_region);
+ item->image = atlas_tex;
+ } else {
+ item->image = p_image;
+ }
+
item->color = p_color;
item->inline_align = p_alignment;
@@ -2981,17 +2989,30 @@ void RichTextLabel::add_image(const Ref<Texture2D> &p_image, const int p_width,
item->size.height = p_height;
} else {
// calculate height to keep aspect ratio
- item->size.height = p_image->get_height() * p_width / p_image->get_width();
+ if (p_region.has_area()) {
+ item->size.height = p_region.get_size().height * p_width / p_region.get_size().width;
+ } else {
+ item->size.height = p_image->get_height() * p_width / p_image->get_width();
+ }
}
} else {
if (p_height > 0) {
// custom height
item->size.height = p_height;
// calculate width to keep aspect ratio
- item->size.width = p_image->get_width() * p_height / p_image->get_height();
+ if (p_region.has_area()) {
+ item->size.width = p_region.get_size().width * p_height / p_region.get_size().height;
+ } else {
+ item->size.width = p_image->get_width() * p_height / p_image->get_height();
+ }
} else {
- // keep original width and height
- item->size = p_image->get_size();
+ if (p_region.has_area()) {
+ // if the image has a region, keep the region size
+ item->size = p_region.get_size();
+ } else {
+ // keep original width and height
+ item->size = p_image->get_size();
+ }
}
}
@@ -4126,6 +4147,18 @@ void RichTextLabel::append_text(const String &p_bbcode) {
Ref<Texture2D> texture = ResourceLoader::load(image, "Texture2D");
if (texture.is_valid()) {
+ Rect2 region;
+ OptionMap::Iterator region_option = bbcode_options.find("region");
+ if (region_option) {
+ Vector<String> region_values = region_option->value.split(",", false);
+ if (region_values.size() == 4) {
+ region.position.x = region_values[0].to_float();
+ region.position.y = region_values[1].to_float();
+ region.size.x = region_values[2].to_float();
+ region.size.y = region_values[3].to_float();
+ }
+ }
+
Color color = Color(1.0, 1.0, 1.0);
OptionMap::Iterator color_option = bbcode_options.find("color");
if (color_option) {
@@ -4154,7 +4187,7 @@ void RichTextLabel::append_text(const String &p_bbcode) {
}
}
- add_image(texture, width, height, color, (InlineAlignment)alignment);
+ add_image(texture, width, height, color, (InlineAlignment)alignment, region);
}
pos = end;
@@ -5209,7 +5242,7 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_parsed_text"), &RichTextLabel::get_parsed_text);
ClassDB::bind_method(D_METHOD("add_text", "text"), &RichTextLabel::add_text);
ClassDB::bind_method(D_METHOD("set_text", "text"), &RichTextLabel::set_text);
- ClassDB::bind_method(D_METHOD("add_image", "image", "width", "height", "color", "inline_align"), &RichTextLabel::add_image, DEFVAL(0), DEFVAL(0), DEFVAL(Color(1.0, 1.0, 1.0)), DEFVAL(INLINE_ALIGNMENT_CENTER));
+ ClassDB::bind_method(D_METHOD("add_image", "image", "width", "height", "color", "inline_align", "region"), &RichTextLabel::add_image, DEFVAL(0), DEFVAL(0), DEFVAL(Color(1.0, 1.0, 1.0)), DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(Rect2(0, 0, 0, 0)));
ClassDB::bind_method(D_METHOD("newline"), &RichTextLabel::add_newline);
ClassDB::bind_method(D_METHOD("remove_line", "line"), &RichTextLabel::remove_line);
ClassDB::bind_method(D_METHOD("push_font", "font", "font_size"), &RichTextLabel::push_font);
diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h
index 73b7676c22..04a682349d 100644
--- a/scene/gui/rich_text_label.h
+++ b/scene/gui/rich_text_label.h
@@ -569,7 +569,7 @@ private:
public:
String get_parsed_text() const;
void add_text(const String &p_text);
- void add_image(const Ref<Texture2D> &p_image, const int p_width = 0, const int p_height = 0, const Color &p_color = Color(1.0, 1.0, 1.0), InlineAlignment p_alignment = INLINE_ALIGNMENT_CENTER);
+ void add_image(const Ref<Texture2D> &p_image, const int p_width = 0, const int p_height = 0, const Color &p_color = Color(1.0, 1.0, 1.0), InlineAlignment p_alignment = INLINE_ALIGNMENT_CENTER, const Rect2 &p_region = Rect2(0, 0, 0, 0));
void add_newline();
bool remove_line(const int p_line);
void push_dropcap(const String &p_string, const Ref<Font> &p_font, int p_size, const Rect2 &p_dropcap_margins = Rect2(), const Color &p_color = Color(1, 1, 1), int p_ol_size = 0, const Color &p_ol_color = Color(0, 0, 0, 0));
diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index 6c05b171e3..6899178885 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -183,35 +183,35 @@ void ScrollBar::gui_input(const Ref<InputEvent> &p_event) {
}
if (p_event->is_pressed()) {
- if (p_event->is_action("ui_left")) {
+ if (p_event->is_action("ui_left", true)) {
if (orientation != HORIZONTAL) {
return;
}
set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
- } else if (p_event->is_action("ui_right")) {
+ } else if (p_event->is_action("ui_right", true)) {
if (orientation != HORIZONTAL) {
return;
}
set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
- } else if (p_event->is_action("ui_up")) {
+ } else if (p_event->is_action("ui_up", true)) {
if (orientation != VERTICAL) {
return;
}
set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
- } else if (p_event->is_action("ui_down")) {
+ } else if (p_event->is_action("ui_down", true)) {
if (orientation != VERTICAL) {
return;
}
set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
- } else if (p_event->is_action("ui_home")) {
+ } else if (p_event->is_action("ui_home", true)) {
set_value(get_min());
- } else if (p_event->is_action("ui_end")) {
+ } else if (p_event->is_action("ui_end", true)) {
set_value(get_max());
}
}
@@ -338,7 +338,7 @@ void ScrollBar::_notification(int p_what) {
if (scrolling) {
if (get_value() != target_scroll) {
double target = target_scroll - get_value();
- double dist = sqrt(target * target);
+ double dist = abs(target);
double vel = ((target / dist) * 500) * get_physics_process_delta_time();
if (Math::abs(vel) >= dist) {
diff --git a/scene/gui/slider.cpp b/scene/gui/slider.cpp
index a7d44c0f3c..6cbacf0dd3 100644
--- a/scene/gui/slider.cpp
+++ b/scene/gui/slider.cpp
@@ -138,10 +138,10 @@ void Slider::gui_input(const Ref<InputEvent> &p_event) {
}
set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
accept_event();
- } else if (p_event->is_action("ui_home") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_home", true) && p_event->is_pressed()) {
set_value(get_min());
accept_event();
- } else if (p_event->is_action("ui_end") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_end", true) && p_event->is_pressed()) {
set_value(get_max());
accept_event();
}
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index f8501f3570..48853cde9c 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -464,7 +464,7 @@ void TextEdit::_notification(int p_what) {
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (scrolling && get_v_scroll() != target_v_scroll) {
double target_y = target_v_scroll - get_v_scroll();
- double dist = sqrt(target_y * target_y);
+ double dist = abs(target_y);
// To ensure minimap is responsive override the speed setting.
double vel = ((target_y / dist) * ((minimap_clicked) ? 3000 : v_scroll_speed)) * get_physics_process_delta_time();
@@ -1692,7 +1692,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
continue;
}
- if (mpos.x > left_margin && mpos.x <= (left_margin + gutters[i].width) - 3) {
+ if (mpos.x >= left_margin && mpos.x <= left_margin + gutters[i].width) {
emit_signal(SNAME("gutter_clicked"), row, i);
return;
}
@@ -1933,7 +1933,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
continue;
}
- if (mpos.x > left_margin && mpos.x <= (left_margin + gutters[i].width) - 3) {
+ if (mpos.x >= left_margin && mpos.x < left_margin + gutters[i].width) {
// We are in this gutter i's horizontal area.
current_hovered_gutter = Vector2i(i, hovered_row);
break;
@@ -2051,7 +2051,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
}
if (is_shortcut_keys_enabled()) {
- // SELECT ALL, SELECT WORD UNDER CARET, CUT, COPY, PASTE.
+ // SELECT ALL, SELECT WORD UNDER CARET, ADD SELECTION FOR NEXT OCCURRENCE, CUT, COPY, PASTE.
if (k->is_action("ui_text_select_all", true)) {
select_all();
accept_event();
@@ -2062,6 +2062,11 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
accept_event();
return;
}
+ if (k->is_action("ui_text_add_selection_for_next_occurrence", true)) {
+ add_selection_for_next_occurrence();
+ accept_event();
+ return;
+ }
if (k->is_action("ui_cut", true)) {
cut();
accept_event();
@@ -2192,8 +2197,17 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
return;
}
- // Handle Unicode (if no modifiers active). Tab has a value of 0x09.
- if (allow_unicode_handling && editable && (k->get_unicode() >= 32 || k->get_keycode() == Key::TAB)) {
+ // Handle tab as it has no set unicode value.
+ if (k->is_action("ui_text_indent", true)) {
+ if (editable) {
+ insert_text_at_caret("\t");
+ }
+ accept_event();
+ return;
+ }
+
+ // Handle Unicode (if no modifiers active).
+ if (allow_unicode_handling && editable && k->get_unicode() >= 32) {
handle_unicode_input(k->get_unicode());
accept_event();
return;
@@ -2997,7 +3011,7 @@ Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const {
continue;
}
- if (p_pos.x > left_margin && p_pos.x <= (left_margin + gutters[i].width) - 3) {
+ if (p_pos.x >= left_margin && p_pos.x < left_margin + gutters[i].width) {
if (gutters[i].clickable || is_line_gutter_clickable(row, i)) {
return CURSOR_POINTING_HAND;
}
@@ -3854,7 +3868,7 @@ void TextEdit::undo() {
}
caret_pos_dirty = true;
}
- queue_redraw();
+ adjust_viewport_to_caret();
}
void TextEdit::redo() {
@@ -3906,7 +3920,7 @@ void TextEdit::redo() {
}
caret_pos_dirty = true;
}
- queue_redraw();
+ adjust_viewport_to_caret();
}
void TextEdit::clear_undo_history() {
@@ -4380,7 +4394,7 @@ int TextEdit::add_caret(int p_line, int p_col) {
}
void TextEdit::remove_caret(int p_caret) {
- ERR_FAIL_COND(carets.size() <= 0);
+ ERR_FAIL_COND_MSG(carets.size() <= 1, "The main caret should not be removed.");
ERR_FAIL_INDEX(p_caret, carets.size());
carets.remove_at(p_caret);
caret_index_edit_dirty = true;
@@ -4816,10 +4830,50 @@ void TextEdit::select_word_under_caret(int p_caret) {
continue;
}
- select(get_caret_line(c), begin, get_caret_column(c), end, c);
+ select(get_caret_line(c), begin, get_caret_line(c), end, c);
// Move the caret to the end of the word for easier editing.
set_caret_column(end, false, c);
}
+ merge_overlapping_carets();
+}
+
+void TextEdit::add_selection_for_next_occurrence() {
+ if (!selecting_enabled || !is_multiple_carets_enabled()) {
+ return;
+ }
+
+ if (text.size() == 1 && text[0].length() == 0) {
+ return;
+ }
+
+ // Always use the last caret, to correctly search for
+ // the next occurrence that comes after this caret.
+ int caret = get_caret_count() - 1;
+
+ if (!has_selection(caret)) {
+ select_word_under_caret(caret);
+ return;
+ }
+
+ const String &highlighted_text = get_selected_text(caret);
+ int column = get_selection_from_column(caret) + 1;
+ int line = get_caret_line(caret);
+
+ const Point2i next_occurrence = search(highlighted_text, SEARCH_MATCH_CASE, line, column);
+
+ if (next_occurrence.x == -1 || next_occurrence.y == -1) {
+ return;
+ }
+
+ int to_column = get_selection_to_column(caret) + 1;
+ int end = next_occurrence.x + (to_column - column);
+ int new_caret = add_caret(next_occurrence.y, end);
+
+ if (new_caret != -1) {
+ select(next_occurrence.y, next_occurrence.x, next_occurrence.y, end, new_caret);
+ adjust_viewport_to_caret(new_caret);
+ merge_overlapping_carets();
+ }
}
void TextEdit::select(int p_from_line, int p_from_column, int p_to_line, int p_to_column, int p_caret) {
@@ -5088,6 +5142,14 @@ bool TextEdit::is_scroll_past_end_of_file_enabled() const {
return scroll_past_end_of_file_enabled;
}
+VScrollBar *TextEdit::get_v_scroll_bar() const {
+ return v_scroll;
+}
+
+HScrollBar *TextEdit::get_h_scroll_bar() const {
+ return h_scroll;
+}
+
void TextEdit::set_v_scroll(double p_scroll) {
v_scroll->set_value(p_scroll);
int max_v_scroll = v_scroll->get_max() - v_scroll->get_page();
@@ -5982,6 +6044,7 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("select_all"), &TextEdit::select_all);
ClassDB::bind_method(D_METHOD("select_word_under_caret", "caret_index"), &TextEdit::select_word_under_caret, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("add_selection_for_next_occurrence"), &TextEdit::add_selection_for_next_occurrence);
ClassDB::bind_method(D_METHOD("select", "from_line", "from_column", "to_line", "to_column", "caret_index"), &TextEdit::select, DEFVAL(0));
ClassDB::bind_method(D_METHOD("has_selection", "caret_index"), &TextEdit::has_selection, DEFVAL(-1));
@@ -6020,6 +6083,9 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_smooth_scroll_enabled", "enable"), &TextEdit::set_smooth_scroll_enabled);
ClassDB::bind_method(D_METHOD("is_smooth_scroll_enabled"), &TextEdit::is_smooth_scroll_enabled);
+ ClassDB::bind_method(D_METHOD("get_v_scroll_bar"), &TextEdit::get_v_scroll_bar);
+ ClassDB::bind_method(D_METHOD("get_h_scroll_bar"), &TextEdit::get_h_scroll_bar);
+
ClassDB::bind_method(D_METHOD("set_v_scroll", "value"), &TextEdit::set_v_scroll);
ClassDB::bind_method(D_METHOD("get_v_scroll"), &TextEdit::get_v_scroll);
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index a8e087909e..86b838e387 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -851,6 +851,7 @@ public:
void select_all();
void select_word_under_caret(int p_caret = -1);
+ void add_selection_for_next_occurrence();
void select(int p_from_line, int p_from_column, int p_to_line, int p_to_column, int p_caret = 0);
bool has_selection(int p_caret = -1) const;
@@ -886,6 +887,9 @@ public:
void set_scroll_past_end_of_file_enabled(const bool p_enabled);
bool is_scroll_past_end_of_file_enabled() const;
+ VScrollBar *get_v_scroll_bar() const;
+ HScrollBar *get_h_scroll_bar() const;
+
void set_v_scroll(double p_scroll);
double get_v_scroll() const;
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index acf398305c..6f9a9a5141 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -1504,6 +1504,7 @@ void TreeItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_button", "column", "button_idx", "button"), &TreeItem::set_button);
ClassDB::bind_method(D_METHOD("erase_button", "column", "button_idx"), &TreeItem::erase_button);
ClassDB::bind_method(D_METHOD("set_button_disabled", "column", "button_idx", "disabled"), &TreeItem::set_button_disabled);
+ ClassDB::bind_method(D_METHOD("set_button_color", "column", "button_idx", "color"), &TreeItem::set_button_color);
ClassDB::bind_method(D_METHOD("is_button_disabled", "column", "button_idx"), &TreeItem::is_button_disabled);
ClassDB::bind_method(D_METHOD("set_tooltip_text", "column", "tooltip"), &TreeItem::set_tooltip_text);
@@ -3190,7 +3191,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
Ref<InputEventKey> k = p_event;
bool is_command = k.is_valid() && k->is_command_or_control_pressed();
- if (p_event->is_action("ui_right") && p_event->is_pressed()) {
+ if (p_event->is_action("ui_right", true) && p_event->is_pressed()) {
if (!cursor_can_exit_tree) {
accept_event();
}
@@ -3208,7 +3209,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
} else {
_go_right();
}
- } else if (p_event->is_action("ui_left") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_left", true) && p_event->is_pressed()) {
if (!cursor_can_exit_tree) {
accept_event();
}
@@ -3228,21 +3229,21 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
_go_left();
}
- } else if (p_event->is_action("ui_up") && p_event->is_pressed() && !is_command) {
+ } else if (p_event->is_action("ui_up", true) && p_event->is_pressed() && !is_command) {
if (!cursor_can_exit_tree) {
accept_event();
}
_go_up();
- } else if (p_event->is_action("ui_down") && p_event->is_pressed() && !is_command) {
+ } else if (p_event->is_action("ui_down", true) && p_event->is_pressed() && !is_command) {
if (!cursor_can_exit_tree) {
accept_event();
}
_go_down();
- } else if (p_event->is_action("ui_page_down") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_page_down", true) && p_event->is_pressed()) {
if (!cursor_can_exit_tree) {
accept_event();
}
@@ -3280,7 +3281,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
}
ensure_cursor_is_visible();
- } else if (p_event->is_action("ui_page_up") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_page_up", true) && p_event->is_pressed()) {
if (!cursor_can_exit_tree) {
accept_event();
}
@@ -3317,7 +3318,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
prev->select(selected_col);
}
ensure_cursor_is_visible();
- } else if (p_event->is_action("ui_accept") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_accept", true) && p_event->is_pressed()) {
if (selected_item) {
//bring up editor if possible
if (!edit_selected()) {
@@ -3326,7 +3327,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
}
}
accept_event();
- } else if (p_event->is_action("ui_select") && p_event->is_pressed()) {
+ } else if (p_event->is_action("ui_select", true) && p_event->is_pressed()) {
if (select_mode == SELECT_MULTI) {
if (!selected_item) {
return;
diff --git a/scene/gui/view_panner.cpp b/scene/gui/view_panner.cpp
index 3b7f499a07..e8e3e3e556 100644
--- a/scene/gui/view_panner.cpp
+++ b/scene/gui/view_panner.cpp
@@ -38,7 +38,9 @@ bool ViewPanner::gui_input(const Ref<InputEvent> &p_event, Rect2 p_canvas_rect)
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
Vector2 scroll_vec = Vector2((mb->get_button_index() == MouseButton::WHEEL_RIGHT) - (mb->get_button_index() == MouseButton::WHEEL_LEFT), (mb->get_button_index() == MouseButton::WHEEL_DOWN) - (mb->get_button_index() == MouseButton::WHEEL_UP));
- if (scroll_vec != Vector2()) {
+ // Moving the scroll wheel sends two events: one with pressed as true,
+ // and one with pressed as false. Make sure we only process one of them.
+ if (scroll_vec != Vector2() && mb->is_pressed()) {
if (control_scheme == SCROLL_PANS) {
if (mb->is_ctrl_pressed()) {
scroll_vec.y *= mb->get_factor();
diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp
index 05d86f77f2..840913d466 100644
--- a/scene/main/canvas_item.cpp
+++ b/scene/main/canvas_item.cpp
@@ -986,8 +986,8 @@ void CanvasItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture_repeat", "mode"), &CanvasItem::set_texture_repeat);
ClassDB::bind_method(D_METHOD("get_texture_repeat"), &CanvasItem::get_texture_repeat);
- ClassDB::bind_method(D_METHOD("set_clip_children", "enable"), &CanvasItem::set_clip_children);
- ClassDB::bind_method(D_METHOD("is_clipping_children"), &CanvasItem::is_clipping_children);
+ ClassDB::bind_method(D_METHOD("set_clip_children_mode", "mode"), &CanvasItem::set_clip_children_mode);
+ ClassDB::bind_method(D_METHOD("get_clip_children_mode"), &CanvasItem::get_clip_children_mode);
GDVIRTUAL_BIND(_draw);
@@ -997,7 +997,7 @@ void CanvasItem::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "self_modulate"), "set_self_modulate", "get_self_modulate");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_behind_parent"), "set_draw_behind_parent", "is_draw_behind_parent_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "top_level"), "set_as_top_level", "is_set_as_top_level");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_children"), "set_clip_children", "is_clipping_children");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "clip_children", PROPERTY_HINT_ENUM, "Disabled,Clip Only,Clip + Draw"), "set_clip_children_mode", "get_clip_children_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask");
ADD_GROUP("Texture", "texture_");
@@ -1035,6 +1035,11 @@ void CanvasItem::_bind_methods() {
BIND_ENUM_CONSTANT(TEXTURE_REPEAT_ENABLED);
BIND_ENUM_CONSTANT(TEXTURE_REPEAT_MIRROR);
BIND_ENUM_CONSTANT(TEXTURE_REPEAT_MAX);
+
+ BIND_ENUM_CONSTANT(CLIP_CHILDREN_DISABLED);
+ BIND_ENUM_CONSTANT(CLIP_CHILDREN_ONLY);
+ BIND_ENUM_CONSTANT(CLIP_CHILDREN_AND_DRAW);
+ BIND_ENUM_CONSTANT(CLIP_CHILDREN_MAX);
}
Transform2D CanvasItem::get_canvas_transform() const {
@@ -1092,7 +1097,7 @@ int CanvasItem::get_canvas_layer() const {
}
}
-void CanvasItem::_update_texture_filter_changed(bool p_propagate) {
+void CanvasItem::_refresh_texture_filter_cache() {
if (!is_inside_tree()) {
return;
}
@@ -1107,6 +1112,14 @@ void CanvasItem::_update_texture_filter_changed(bool p_propagate) {
} else {
texture_filter_cache = RS::CanvasItemTextureFilter(texture_filter);
}
+}
+
+void CanvasItem::_update_texture_filter_changed(bool p_propagate) {
+ if (!is_inside_tree()) {
+ return;
+ }
+ _refresh_texture_filter_cache();
+
RS::get_singleton()->canvas_item_set_default_texture_filter(get_canvas_item(), texture_filter_cache);
queue_redraw();
@@ -1133,7 +1146,7 @@ CanvasItem::TextureFilter CanvasItem::get_texture_filter() const {
return texture_filter;
}
-void CanvasItem::_update_texture_repeat_changed(bool p_propagate) {
+void CanvasItem::_refresh_texture_repeat_cache() {
if (!is_inside_tree()) {
return;
}
@@ -1148,6 +1161,14 @@ void CanvasItem::_update_texture_repeat_changed(bool p_propagate) {
} else {
texture_repeat_cache = RS::CanvasItemTextureRepeat(texture_repeat);
}
+}
+
+void CanvasItem::_update_texture_repeat_changed(bool p_propagate) {
+ if (!is_inside_tree()) {
+ return;
+ }
+ _refresh_texture_repeat_cache();
+
RS::get_singleton()->canvas_item_set_default_texture_repeat(get_canvas_item(), texture_repeat_cache);
queue_redraw();
if (p_propagate) {
@@ -1169,26 +1190,39 @@ void CanvasItem::set_texture_repeat(TextureRepeat p_texture_repeat) {
notify_property_list_changed();
}
-void CanvasItem::set_clip_children(bool p_enabled) {
- if (clip_children == p_enabled) {
+void CanvasItem::set_clip_children_mode(ClipChildrenMode p_clip_mode) {
+ ERR_FAIL_COND(p_clip_mode >= CLIP_CHILDREN_MAX);
+
+ if (clip_children_mode == p_clip_mode) {
return;
}
- clip_children = p_enabled;
+ clip_children_mode = p_clip_mode;
if (Object::cast_to<CanvasGroup>(this) != nullptr) {
//avoid accidental bugs, make this not work on CanvasGroup
return;
}
- RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), clip_children ? RS::CANVAS_GROUP_MODE_OPAQUE : RS::CANVAS_GROUP_MODE_DISABLED);
+
+ RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CanvasGroupMode(clip_children_mode));
}
-bool CanvasItem::is_clipping_children() const {
- return clip_children;
+CanvasItem::ClipChildrenMode CanvasItem::get_clip_children_mode() const {
+ return clip_children_mode;
}
CanvasItem::TextureRepeat CanvasItem::get_texture_repeat() const {
return texture_repeat;
}
+CanvasItem::TextureFilter CanvasItem::get_texture_filter_in_tree() {
+ _refresh_texture_filter_cache();
+ return (TextureFilter)texture_filter_cache;
+}
+
+CanvasItem::TextureRepeat CanvasItem::get_texture_repeat_in_tree() {
+ _refresh_texture_repeat_cache();
+ return (TextureRepeat)texture_repeat_cache;
+}
+
CanvasItem::CanvasItem() :
xform_change(this) {
canvas_item = RenderingServer::get_singleton()->canvas_item_create();
diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h
index b80289fdb4..565ea930ce 100644
--- a/scene/main/canvas_item.h
+++ b/scene/main/canvas_item.h
@@ -66,8 +66,16 @@ public:
TEXTURE_REPEAT_MAX,
};
+ enum ClipChildrenMode {
+ CLIP_CHILDREN_DISABLED,
+ CLIP_CHILDREN_ONLY,
+ CLIP_CHILDREN_AND_DRAW,
+ CLIP_CHILDREN_MAX,
+ };
+
private:
- mutable SelfList<Node> xform_change;
+ mutable SelfList<Node>
+ xform_change;
RID canvas_item;
StringName canvas_group;
@@ -85,7 +93,6 @@ private:
Window *window = nullptr;
bool visible = true;
bool parent_visible_in_tree = false;
- bool clip_children = false;
bool pending_update = false;
bool top_level = false;
bool drawing = false;
@@ -95,6 +102,8 @@ private:
bool notify_local_transform = false;
bool notify_transform = false;
+ ClipChildrenMode clip_children_mode = CLIP_CHILDREN_DISABLED;
+
RS::CanvasItemTextureFilter texture_filter_cache = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;
RS::CanvasItemTextureRepeat texture_repeat_cache = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;
TextureFilter texture_filter = TEXTURE_FILTER_PARENT_NODE;
@@ -121,7 +130,9 @@ private:
static CanvasItem *current_item_drawn;
friend class Viewport;
+ void _refresh_texture_repeat_cache();
void _update_texture_repeat_changed(bool p_propagate);
+ void _refresh_texture_filter_cache();
void _update_texture_filter_changed(bool p_propagate);
protected:
@@ -200,8 +211,8 @@ public:
void queue_redraw();
void move_to_front();
- void set_clip_children(bool p_enabled);
- bool is_clipping_children() const;
+ void set_clip_children_mode(ClipChildrenMode p_clip_mode);
+ ClipChildrenMode get_clip_children_mode() const;
virtual void set_light_mask(int p_light_mask);
int get_light_mask() const;
@@ -310,6 +321,9 @@ public:
virtual void set_texture_repeat(TextureRepeat p_texture_repeat);
TextureRepeat get_texture_repeat() const;
+ TextureFilter get_texture_filter_in_tree();
+ TextureRepeat get_texture_repeat_in_tree();
+
// Used by control nodes to retrieve the parent's anchorable area
virtual Rect2 get_anchorable_rect() const { return Rect2(0, 0, 0, 0); };
@@ -321,6 +335,7 @@ public:
VARIANT_ENUM_CAST(CanvasItem::TextureFilter)
VARIANT_ENUM_CAST(CanvasItem::TextureRepeat)
+VARIANT_ENUM_CAST(CanvasItem::ClipChildrenMode)
class CanvasTexture : public Texture2D {
GDCLASS(CanvasTexture, Texture2D);
diff --git a/scene/main/multiplayer_peer.cpp b/scene/main/multiplayer_peer.cpp
index 9b63118f7c..462dc1babb 100644
--- a/scene/main/multiplayer_peer.cpp
+++ b/scene/main/multiplayer_peer.cpp
@@ -78,6 +78,10 @@ bool MultiplayerPeer::is_refusing_new_connections() const {
return refuse_connections;
}
+bool MultiplayerPeer::is_server_relay_supported() const {
+ return false;
+}
+
void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &MultiplayerPeer::set_transfer_channel);
ClassDB::bind_method(D_METHOD("get_transfer_channel"), &MultiplayerPeer::get_transfer_channel);
@@ -86,6 +90,8 @@ void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &MultiplayerPeer::set_target_peer);
ClassDB::bind_method(D_METHOD("get_packet_peer"), &MultiplayerPeer::get_packet_peer);
+ ClassDB::bind_method(D_METHOD("get_packet_channel"), &MultiplayerPeer::get_packet_channel);
+ ClassDB::bind_method(D_METHOD("get_packet_mode"), &MultiplayerPeer::get_packet_mode);
ClassDB::bind_method(D_METHOD("poll"), &MultiplayerPeer::poll);
@@ -96,6 +102,8 @@ void MultiplayerPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &MultiplayerPeer::set_refuse_new_connections);
ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &MultiplayerPeer::is_refusing_new_connections);
+ ClassDB::bind_method(D_METHOD("is_server_relay_supported"), &MultiplayerPeer::is_server_relay_supported);
+
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_mode", PROPERTY_HINT_ENUM, "Unreliable,Unreliable Ordered,Reliable"), "set_transfer_mode", "get_transfer_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel", PROPERTY_HINT_RANGE, "0,255,1"), "set_transfer_channel", "get_transfer_channel");
@@ -177,6 +185,14 @@ bool MultiplayerPeerExtension::is_refusing_new_connections() const {
return MultiplayerPeer::is_refusing_new_connections();
}
+bool MultiplayerPeerExtension::is_server_relay_supported() const {
+ bool can_relay;
+ if (GDVIRTUAL_CALL(_is_server_relay_supported, can_relay)) {
+ return can_relay;
+ }
+ return MultiplayerPeer::is_server_relay_supported();
+}
+
void MultiplayerPeerExtension::_bind_methods() {
GDVIRTUAL_BIND(_get_packet, "r_buffer", "r_buffer_size");
GDVIRTUAL_BIND(_put_packet, "p_buffer", "p_buffer_size");
diff --git a/scene/main/multiplayer_peer.h b/scene/main/multiplayer_peer.h
index ab7483ece5..63ce66871e 100644
--- a/scene/main/multiplayer_peer.h
+++ b/scene/main/multiplayer_peer.h
@@ -74,10 +74,13 @@ public:
virtual TransferMode get_transfer_mode() const;
virtual void set_refuse_new_connections(bool p_enable);
virtual bool is_refusing_new_connections() const;
+ virtual bool is_server_relay_supported() const;
virtual void set_target_peer(int p_peer_id) = 0;
virtual int get_packet_peer() const = 0;
+ virtual TransferMode get_packet_mode() const = 0;
+ virtual int get_packet_channel() const = 0;
virtual bool is_server() const = 0;
@@ -123,12 +126,17 @@ public:
virtual bool is_refusing_new_connections() const override;
GDVIRTUAL0RC(bool, _is_refusing_new_connections); // Optional.
+ virtual bool is_server_relay_supported() const override;
+ GDVIRTUAL0RC(bool, _is_server_relay_supported); // Optional.
+
EXBIND1(set_transfer_channel, int);
EXBIND0RC(int, get_transfer_channel);
EXBIND1(set_transfer_mode, TransferMode);
EXBIND0RC(TransferMode, get_transfer_mode);
EXBIND1(set_target_peer, int);
EXBIND0RC(int, get_packet_peer);
+ EXBIND0RC(TransferMode, get_packet_mode);
+ EXBIND0RC(int, get_packet_channel);
EXBIND0RC(bool, is_server);
EXBIND0(poll);
EXBIND0RC(int, get_unique_id);
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 101a63db1b..2ea45df309 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -322,62 +322,62 @@ void Node::_propagate_exit_tree() {
data.depth = -1;
}
-void Node::move_child(Node *p_child, int p_pos) {
+void Node::move_child(Node *p_child, int p_index) {
ERR_FAIL_NULL(p_child);
ERR_FAIL_COND_MSG(p_child->data.parent != this, "Child is not a child of this node.");
// We need to check whether node is internal and move it only in the relevant node range.
if (p_child->_is_internal_front()) {
- if (p_pos < 0) {
- p_pos += data.internal_children_front;
+ if (p_index < 0) {
+ p_index += data.internal_children_front;
}
- ERR_FAIL_INDEX_MSG(p_pos, data.internal_children_front, vformat("Invalid new child position: %d. Child is internal.", p_pos));
- _move_child(p_child, p_pos);
+ ERR_FAIL_INDEX_MSG(p_index, data.internal_children_front, vformat("Invalid new child index: %d. Child is internal.", p_index));
+ _move_child(p_child, p_index);
} else if (p_child->_is_internal_back()) {
- if (p_pos < 0) {
- p_pos += data.internal_children_back;
+ if (p_index < 0) {
+ p_index += data.internal_children_back;
}
- ERR_FAIL_INDEX_MSG(p_pos, data.internal_children_back, vformat("Invalid new child position: %d. Child is internal.", p_pos));
- _move_child(p_child, data.children.size() - data.internal_children_back + p_pos);
+ ERR_FAIL_INDEX_MSG(p_index, data.internal_children_back, vformat("Invalid new child index: %d. Child is internal.", p_index));
+ _move_child(p_child, data.children.size() - data.internal_children_back + p_index);
} else {
- if (p_pos < 0) {
- p_pos += get_child_count(false);
+ if (p_index < 0) {
+ p_index += get_child_count(false);
}
- ERR_FAIL_INDEX_MSG(p_pos, data.children.size() + 1 - data.internal_children_front - data.internal_children_back, vformat("Invalid new child position: %d.", p_pos));
- _move_child(p_child, p_pos + data.internal_children_front);
+ ERR_FAIL_INDEX_MSG(p_index, data.children.size() + 1 - data.internal_children_front - data.internal_children_back, vformat("Invalid new child index: %d.", p_index));
+ _move_child(p_child, p_index + data.internal_children_front);
}
}
-void Node::_move_child(Node *p_child, int p_pos, bool p_ignore_end) {
+void Node::_move_child(Node *p_child, int p_index, bool p_ignore_end) {
ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, move_child() failed. Consider using call_deferred(\"move_child\") instead (or \"popup\" if this is from a popup).");
// Specifying one place beyond the end
- // means the same as moving to the last position
+ // means the same as moving to the last index
if (!p_ignore_end) { // p_ignore_end is a little hack to make back internal children work properly.
if (p_child->_is_internal_front()) {
- if (p_pos == data.internal_children_front) {
- p_pos--;
+ if (p_index == data.internal_children_front) {
+ p_index--;
}
} else if (p_child->_is_internal_back()) {
- if (p_pos == data.children.size()) {
- p_pos--;
+ if (p_index == data.children.size()) {
+ p_index--;
}
} else {
- if (p_pos == data.children.size() - data.internal_children_back) {
- p_pos--;
+ if (p_index == data.children.size() - data.internal_children_back) {
+ p_index--;
}
}
}
- if (p_child->data.pos == p_pos) {
+ if (p_child->data.index == p_index) {
return; //do nothing
}
- int motion_from = MIN(p_pos, p_child->data.pos);
- int motion_to = MAX(p_pos, p_child->data.pos);
+ int motion_from = MIN(p_index, p_child->data.index);
+ int motion_to = MAX(p_index, p_child->data.index);
- data.children.remove_at(p_child->data.pos);
- data.children.insert(p_pos, p_child);
+ data.children.remove_at(p_child->data.index);
+ data.children.insert(p_index, p_child);
if (data.tree) {
data.tree->tree_changed();
@@ -386,7 +386,7 @@ void Node::_move_child(Node *p_child, int p_pos, bool p_ignore_end) {
data.blocked++;
//new pos first
for (int i = motion_from; i <= motion_to; i++) {
- data.children[i]->data.pos = i;
+ data.children[i]->data.index = i;
}
// notification second
move_child_notify(p_child);
@@ -1024,11 +1024,9 @@ String increase_numeric_string(const String &s) {
void Node::_generate_serial_child_name(const Node *p_child, StringName &name) const {
if (name == StringName()) {
- //no name and a new name is needed, create one.
+ // No name and a new name is needed, create one.
name = p_child->get_class();
- // Adjust casing according to project setting.
- name = adjust_name_casing(name);
}
//quickly test if proposed name exists
@@ -1106,7 +1104,7 @@ void Node::_add_child_nocheck(Node *p_child, const StringName &p_name) {
//add a child node quickly, without name validation
p_child->data.name = p_name;
- p_child->data.pos = data.children.size();
+ p_child->data.index = data.children.size();
data.children.push_back(p_child);
p_child->data.parent = this;
@@ -1173,9 +1171,9 @@ void Node::remove_child(Node *p_child) {
Node **children = data.children.ptrw();
int idx = -1;
- if (p_child->data.pos >= 0 && p_child->data.pos < child_count) {
- if (children[p_child->data.pos] == p_child) {
- idx = p_child->data.pos;
+ if (p_child->data.index >= 0 && p_child->data.index < child_count) {
+ if (children[p_child->data.index] == p_child) {
+ idx = p_child->data.index;
}
}
@@ -1211,12 +1209,12 @@ void Node::remove_child(Node *p_child) {
children = data.children.ptrw();
for (int i = idx; i < child_count; i++) {
- children[i]->data.pos = i;
+ children[i]->data.index = i;
children[i]->notification(NOTIFICATION_MOVED_IN_PARENT);
}
p_child->data.parent = nullptr;
- p_child->data.pos = -1;
+ p_child->data.index = -1;
if (data.inside_tree) {
p_child->_propagate_after_exit_tree();
@@ -1475,7 +1473,7 @@ bool Node::is_greater_than(const Node *p_node) const {
int idx = data.depth - 1;
while (n) {
ERR_FAIL_INDEX_V(idx, data.depth, false);
- this_stack[idx--] = n->data.pos;
+ this_stack[idx--] = n->data.index;
n = n->data.parent;
}
ERR_FAIL_COND_V(idx != -1, false);
@@ -1483,7 +1481,7 @@ bool Node::is_greater_than(const Node *p_node) const {
idx = p_node->data.depth - 1;
while (n) {
ERR_FAIL_INDEX_V(idx, p_node->data.depth, false);
- that_stack[idx--] = n->data.pos;
+ that_stack[idx--] = n->data.index;
n = n->data.parent;
}
@@ -1894,9 +1892,9 @@ int Node::get_index(bool p_include_internal) const {
ERR_FAIL_COND_V_MSG(!p_include_internal && (_is_internal_front() || _is_internal_back()), -1, "Node is internal. Can't get index with 'include_internal' being false.");
if (data.parent && !p_include_internal) {
- return data.pos - data.parent->data.internal_children_front;
+ return data.index - data.parent->data.internal_children_front;
}
- return data.pos;
+ return data.index;
}
Ref<Tween> Node::create_tween() {
@@ -2391,12 +2389,12 @@ void Node::replace_by(Node *p_node, bool p_keep_groups) {
}
Node *parent = data.parent;
- int pos_in_parent = data.pos;
+ int index_in_parent = data.index;
if (data.parent) {
parent->remove_child(this);
parent->add_child(p_node);
- parent->move_child(p_node, pos_in_parent);
+ parent->move_child(p_node, index_in_parent);
}
while (get_child_count()) {
@@ -2759,7 +2757,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_to_group", "group", "persistent"), &Node::add_to_group, DEFVAL(false));
ClassDB::bind_method(D_METHOD("remove_from_group", "group"), &Node::remove_from_group);
ClassDB::bind_method(D_METHOD("is_in_group", "group"), &Node::is_in_group);
- ClassDB::bind_method(D_METHOD("move_child", "child_node", "to_position"), &Node::move_child);
+ ClassDB::bind_method(D_METHOD("move_child", "child_node", "to_index"), &Node::move_child);
ClassDB::bind_method(D_METHOD("get_groups"), &Node::_get_groups);
ClassDB::bind_method(D_METHOD("set_owner", "owner"), &Node::set_owner);
ClassDB::bind_method(D_METHOD("get_owner"), &Node::get_owner);
diff --git a/scene/main/node.h b/scene/main/node.h
index 4e6530cccd..c8c8c395ce 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -91,6 +91,7 @@ private:
SceneTree::Group *group = nullptr;
};
+ // This Data struct is to avoid namespace pollution in derived classes.
struct Data {
String scene_file_path;
Ref<SceneState> instance_state;
@@ -104,7 +105,7 @@ private:
int internal_children_front = 0;
int internal_children_back = 0;
- int pos = -1;
+ int index = -1;
int depth = -1;
int blocked = 0; // Safeguard that throws an error when attempting to modify the tree in a harmful way while being traversed.
StringName name;
@@ -186,8 +187,8 @@ private:
Error _rpc_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
Error _rpc_id_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- _FORCE_INLINE_ bool _is_internal_front() const { return data.parent && data.pos < data.parent->data.internal_children_front; }
- _FORCE_INLINE_ bool _is_internal_back() const { return data.parent && data.pos >= data.parent->data.children.size() - data.parent->data.internal_children_back; }
+ _FORCE_INLINE_ bool _is_internal_front() const { return data.parent && data.index < data.parent->data.internal_children_front; }
+ _FORCE_INLINE_ bool _is_internal_back() const { return data.parent && data.index >= data.parent->data.children.size() - data.parent->data.internal_children_back; }
friend class SceneTree;
@@ -346,8 +347,8 @@ public:
void get_groups(List<GroupInfo> *p_groups) const;
int get_persistent_group_count() const;
- void move_child(Node *p_child, int p_pos);
- void _move_child(Node *p_child, int p_pos, bool p_ignore_end = false);
+ void move_child(Node *p_child, int p_index);
+ void _move_child(Node *p_child, int p_index, bool p_ignore_end = false);
void set_owner(Node *p_owner);
Node *get_owner() const;
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index af481749d5..5ff9a29792 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -44,6 +44,7 @@
#include "node.h"
#include "scene/animation/tween.h"
#include "scene/debugger/scene_debugger.h"
+#include "scene/gui/control.h"
#include "scene/main/multiplayer_api.h"
#include "scene/main/viewport.h"
#include "scene/resources/environment.h"
@@ -895,6 +896,8 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal
call_lock++;
+ Vector<ObjectID> no_context_node_ids; // Nodes may be deleted due to this shortcut input.
+
for (int i = gr_node_count - 1; i >= 0; i--) {
if (p_viewport->is_input_handled()) {
break;
@@ -913,9 +916,22 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal
case CALL_INPUT_TYPE_INPUT:
n->_call_input(p_input);
break;
- case CALL_INPUT_TYPE_SHORTCUT_INPUT:
+ case CALL_INPUT_TYPE_SHORTCUT_INPUT: {
+ const Control *c = Object::cast_to<Control>(n);
+ if (c) {
+ // If calling shortcut input on a control, ensure it respects the shortcut context.
+ // Shortcut context (based on focus) only makes sense for controls (UI), so don't need to worry about it for nodes
+ if (c->get_shortcut_context() == nullptr) {
+ no_context_node_ids.append(n->get_instance_id());
+ continue;
+ }
+ if (!c->is_focus_owner_in_shortcut_context()) {
+ continue;
+ }
+ }
n->_call_shortcut_input(p_input);
break;
+ }
case CALL_INPUT_TYPE_UNHANDLED_INPUT:
n->_call_unhandled_input(p_input);
break;
@@ -925,6 +941,13 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal
}
}
+ for (const ObjectID &id : no_context_node_ids) {
+ Node *n = Object::cast_to<Node>(ObjectDB::get_instance(id));
+ if (n) {
+ n->_call_shortcut_input(p_input);
+ }
+ }
+
call_lock--;
if (call_lock == 0) {
call_skip.clear();
@@ -1390,6 +1413,9 @@ SceneTree::SceneTree() {
ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/msaa_3d", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_3d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")));
root->set_msaa_3d(Viewport::MSAA(msaa_mode_3d));
+ const bool transparent_background = GLOBAL_DEF("rendering/transparent_background", false);
+ root->set_transparent_background(transparent_background);
+
const int ssaa_mode = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/screen_space_aa", 0);
ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/screen_space_aa", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"));
root->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index f7a515dc1d..ad40346c36 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -1263,6 +1263,7 @@ void Viewport::_gui_show_tooltip() {
Point2 tooltip_offset = ProjectSettings::get_singleton()->get("display/mouse_cursor/tooltip_position_offset");
Rect2 r(gui.tooltip_pos + tooltip_offset, gui.tooltip_popup->get_contents_minimum_size());
+ r.size = r.size.min(panel->get_max_size());
Window *window = gui.tooltip_popup->get_parent_visible_window();
Rect2i vr = window->get_usable_parent_rect();
@@ -1403,10 +1404,6 @@ Control *Viewport::gui_find_control(const Point2 &p_global) {
}
Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform) {
- if (Object::cast_to<Viewport>(p_node)) {
- return nullptr;
- }
-
if (!p_node->is_visible()) {
return nullptr; // Canvas item hidden, discard.
}
@@ -1490,7 +1487,6 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
gui.key_event_accepted = false;
Point2 mpos = mb->get_position();
- gui.last_mouse_pos = mpos;
if (mb->is_pressed()) {
Size2 pos = mpos;
if (gui.mouse_focus_mask != MouseButton::NONE) {
@@ -1644,8 +1640,6 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
gui.key_event_accepted = false;
Point2 mpos = mm->get_position();
- gui.last_mouse_pos = mpos;
-
// Drag & drop.
if (!gui.drag_attempted && gui.mouse_focus && (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) {
gui.drag_accum += mm->get_relative();
@@ -2759,6 +2753,11 @@ void Viewport::push_input(const Ref<InputEvent> &p_event, bool p_local_coords) {
ev = p_event;
}
+ Ref<InputEventMouse> me = ev;
+ if (me.is_valid()) {
+ gui.last_mouse_pos = me->get_position();
+ }
+
if (is_embedding_subwindows() && _sub_windows_forward_input(ev)) {
set_input_as_handled();
return;
@@ -3727,6 +3726,7 @@ void Viewport::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_global_canvas_transform", "xform"), &Viewport::set_global_canvas_transform);
ClassDB::bind_method(D_METHOD("get_global_canvas_transform"), &Viewport::get_global_canvas_transform);
ClassDB::bind_method(D_METHOD("get_final_transform"), &Viewport::get_final_transform);
+ ClassDB::bind_method(D_METHOD("get_screen_transform"), &Viewport::get_screen_transform);
ClassDB::bind_method(D_METHOD("get_visible_rect"), &Viewport::get_visible_rect);
ClassDB::bind_method(D_METHOD("set_transparent_background", "enable"), &Viewport::set_transparent_background);
diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index 7fb3f32d36..ebb11ecee8 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -157,26 +157,18 @@ void Window::set_flag(Flags p_flag, bool p_enabled) {
embedder->_sub_window_update(this);
} else if (window_id != DisplayServer::INVALID_WINDOW_ID) {
-#ifdef TOOLS_ENABLED
- if ((p_flag != FLAG_POPUP) || !(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
+ if (!is_in_edited_scene_root()) {
DisplayServer::get_singleton()->window_set_flag(DisplayServer::WindowFlags(p_flag), p_enabled, window_id);
}
-#else
- DisplayServer::get_singleton()->window_set_flag(DisplayServer::WindowFlags(p_flag), p_enabled, window_id);
-#endif
}
}
bool Window::get_flag(Flags p_flag) const {
ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
if (window_id != DisplayServer::INVALID_WINDOW_ID) {
-#ifdef TOOLS_ENABLED
- if ((p_flag != FLAG_POPUP) || !(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
+ if (!is_in_edited_scene_root()) {
flags[p_flag] = DisplayServer::get_singleton()->window_get_flag(DisplayServer::WindowFlags(p_flag), window_id);
}
-#else
- flags[p_flag] = DisplayServer::get_singleton()->window_get_flag(DisplayServer::WindowFlags(p_flag), window_id);
-#endif
}
return flags[p_flag];
}
@@ -232,6 +224,14 @@ bool Window::is_embedded() const {
return _get_embedder() != nullptr;
}
+bool Window::is_in_edited_scene_root() const {
+#ifdef TOOLS_ENABLED
+ return (Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this));
+#else
+ return false;
+#endif
+}
+
void Window::_make_window() {
ERR_FAIL_COND(window_id != DisplayServer::INVALID_WINDOW_ID);
@@ -259,15 +259,12 @@ void Window::_make_window() {
#endif
DisplayServer::get_singleton()->window_set_title(tr_title, window_id);
DisplayServer::get_singleton()->window_attach_instance_id(get_instance_id(), window_id);
-#ifdef TOOLS_ENABLED
- if (!(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
- DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
- } else {
+
+ if (is_in_edited_scene_root()) {
DisplayServer::get_singleton()->window_set_exclusive(window_id, false);
+ } else {
+ DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
}
-#else
- DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
-#endif
_update_window_size();
@@ -465,14 +462,10 @@ void Window::set_visible(bool p_visible) {
//update transient exclusive
if (transient_parent) {
if (exclusive && visible) {
-#ifdef TOOLS_ENABLED
- if (!(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
+ if (!is_in_edited_scene_root()) {
ERR_FAIL_COND_MSG(transient_parent->exclusive_child && transient_parent->exclusive_child != this, "Transient parent has another exclusive child.");
transient_parent->exclusive_child = this;
}
-#else
- transient_parent->exclusive_child = this;
-#endif
} else {
if (transient_parent->exclusive_child == this) {
transient_parent->exclusive_child = nullptr;
@@ -519,13 +512,9 @@ void Window::_make_transient() {
window->transient_children.insert(this);
if (is_inside_tree() && is_visible() && exclusive) {
if (transient_parent->exclusive_child == nullptr) {
-#ifdef TOOLS_ENABLED
- if (!(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
+ if (!is_in_edited_scene_root()) {
transient_parent->exclusive_child = this;
}
-#else
- transient_parent->exclusive_child = this;
-#endif
} else if (transient_parent->exclusive_child != this) {
ERR_PRINT("Making child transient exclusive, but parent has another exclusive child");
}
@@ -568,27 +557,19 @@ void Window::set_exclusive(bool p_exclusive) {
exclusive = p_exclusive;
if (!embedder && window_id != DisplayServer::INVALID_WINDOW_ID) {
-#ifdef TOOLS_ENABLED
- if (!(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
- DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
- } else {
+ if (is_in_edited_scene_root()) {
DisplayServer::get_singleton()->window_set_exclusive(window_id, false);
+ } else {
+ DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
}
-#else
- DisplayServer::get_singleton()->window_set_exclusive(window_id, exclusive);
-#endif
}
if (transient_parent) {
if (p_exclusive && is_inside_tree() && is_visible()) {
ERR_FAIL_COND_MSG(transient_parent->exclusive_child && transient_parent->exclusive_child != this, "Transient parent has another exclusive child.");
-#ifdef TOOLS_ENABLED
- if (!(Engine::get_singleton()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()->is_ancestor_of(this) || get_tree()->get_edited_scene_root() == this))) {
+ if (!is_in_edited_scene_root()) {
transient_parent->exclusive_child = this;
}
-#else
- transient_parent->exclusive_child = this;
-#endif
} else {
if (transient_parent->exclusive_child == this) {
transient_parent->exclusive_child = nullptr;
@@ -606,6 +587,18 @@ bool Window::is_visible() const {
}
void Window::_update_window_size() {
+ // Force window to respect size limitations of rendering server
+ RenderingServer *rendering_server = RenderingServer::get_singleton();
+ if (rendering_server) {
+ Size2i max_window_size = rendering_server->get_maximum_viewport_size();
+
+ if (max_window_size != Size2i()) {
+ size = size.min(max_window_size);
+ min_size = min_size.min(max_window_size);
+ max_size = max_size.min(max_window_size);
+ }
+ }
+
Size2i size_limit;
if (wrap_controls) {
size_limit = get_contents_minimum_size();
@@ -651,9 +644,9 @@ void Window::_update_window_size() {
DisplayServer::get_singleton()->window_set_min_size(Size2i(), window_id);
}
- DisplayServer::get_singleton()->window_set_size(size, window_id);
DisplayServer::get_singleton()->window_set_max_size(max_size_valid ? max_size : Size2i(), window_id);
DisplayServer::get_singleton()->window_set_min_size(size_limit, window_id);
+ DisplayServer::get_singleton()->window_set_size(size, window_id);
}
//update the viewport
@@ -1847,6 +1840,11 @@ void Window::_bind_methods() {
}
Window::Window() {
+ RenderingServer *rendering_server = RenderingServer::get_singleton();
+ if (rendering_server) {
+ max_size = rendering_server->get_maximum_viewport_size();
+ }
+
theme_owner = memnew(ThemeOwner);
RS::get_singleton()->viewport_set_update_mode(get_viewport_rid(), RS::VIEWPORT_UPDATE_DISABLED);
}
diff --git a/scene/main/window.h b/scene/main/window.h
index 786f0ada38..03597b309a 100644
--- a/scene/main/window.h
+++ b/scene/main/window.h
@@ -234,6 +234,8 @@ public:
void set_clamp_to_embedder(bool p_enable);
bool is_clamped_to_embedder() const;
+ bool is_in_edited_scene_root() const;
+
bool can_draw() const;
void set_ime_active(bool p_active);
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index 2bcf569f4e..dfd9c6eb2f 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -5239,9 +5239,7 @@ bool Animation::_fetch_compressed(uint32_t p_compressed_track, double p_time, Ve
double page_base_time = compression.pages[page_index].time_offset;
const uint8_t *page_data = compression.pages[page_index].data.ptr();
-#ifndef _MSC_VER
-#warning Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported
-#endif
+ // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
uint32_t time_key_count = indices[p_compressed_track * 3 + 1];
@@ -5384,9 +5382,7 @@ void Animation::_get_compressed_key_indices_in_range(uint32_t p_compressed_track
double page_base_time = compression.pages[page_index].time_offset;
const uint8_t *page_data = compression.pages[page_index].data.ptr();
-#ifndef _MSC_VER
-#warning Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported
-#endif
+ // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
uint32_t time_key_count = indices[p_compressed_track * 3 + 1];
@@ -5456,9 +5452,7 @@ int Animation::_get_compressed_key_count(uint32_t p_compressed_track) const {
for (uint32_t i = 0; i < compression.pages.size(); i++) {
const uint8_t *page_data = compression.pages[i].data.ptr();
-#ifndef _MSC_VER
-#warning Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported
-#endif
+ // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
uint32_t time_key_count = indices[p_compressed_track * 3 + 1];
@@ -5492,9 +5486,7 @@ bool Animation::_fetch_compressed_by_index(uint32_t p_compressed_track, int p_in
for (uint32_t i = 0; i < compression.pages.size(); i++) {
const uint8_t *page_data = compression.pages[i].data.ptr();
-#ifndef _MSC_VER
-#warning Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported
-#endif
+ // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
uint32_t time_key_count = indices[p_compressed_track * 3 + 1];
diff --git a/scene/resources/bit_map.cpp b/scene/resources/bit_map.cpp
index 0505f6b559..1b06e09bb8 100644
--- a/scene/resources/bit_map.cpp
+++ b/scene/resources/bit_map.cpp
@@ -639,9 +639,7 @@ void BitMap::resize(const Size2i &p_new_size) {
}
Ref<Image> BitMap::convert_to_image() const {
- Ref<Image> image;
- image.instantiate();
- image->create(width, height, false, Image::FORMAT_L8);
+ Ref<Image> image = Image::create_empty(width, height, false, Image::FORMAT_L8);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
diff --git a/scene/resources/convex_polygon_shape_3d.cpp b/scene/resources/convex_polygon_shape_3d.cpp
index 4eaae111a1..5bcefcd0e4 100644
--- a/scene/resources/convex_polygon_shape_3d.cpp
+++ b/scene/resources/convex_polygon_shape_3d.cpp
@@ -42,9 +42,9 @@ Vector<Vector3> ConvexPolygonShape3D::get_debug_mesh_lines() const {
if (err == OK) {
Vector<Vector3> lines;
lines.resize(md.edges.size() * 2);
- for (int i = 0; i < md.edges.size(); i++) {
- lines.write[i * 2 + 0] = md.vertices[md.edges[i].a];
- lines.write[i * 2 + 1] = md.vertices[md.edges[i].b];
+ for (uint32_t i = 0; i < md.edges.size(); i++) {
+ lines.write[i * 2 + 0] = md.vertices[md.edges[i].vertex_a];
+ lines.write[i * 2 + 1] = md.vertices[md.edges[i].vertex_b];
}
return lines;
}
diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp
index ebdaaaa95f..23bd8a4be4 100644
--- a/scene/resources/environment.cpp
+++ b/scene/resources/environment.cpp
@@ -78,7 +78,7 @@ float Environment::get_sky_custom_fov() const {
void Environment::set_sky_rotation(const Vector3 &p_rotation) {
bg_sky_rotation = p_rotation;
- RS::get_singleton()->environment_set_sky_orientation(environment, Basis(p_rotation));
+ RS::get_singleton()->environment_set_sky_orientation(environment, Basis::from_euler(p_rotation));
}
Vector3 Environment::get_sky_rotation() const {
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index 838927e34f..8ae217dd1f 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -2348,7 +2348,7 @@ void BaseMaterial3D::set_on_top_of_alpha() {
set_flag(FLAG_DISABLE_DEPTH_TEST, true);
}
-void BaseMaterial3D::set_proximity_fade(bool p_enable) {
+void BaseMaterial3D::set_proximity_fade_enabled(bool p_enable) {
proximity_fade_enabled = p_enable;
_queue_shader_change();
notify_property_list_changed();
@@ -2624,7 +2624,7 @@ void BaseMaterial3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_refraction_texture_channel", "channel"), &BaseMaterial3D::set_refraction_texture_channel);
ClassDB::bind_method(D_METHOD("get_refraction_texture_channel"), &BaseMaterial3D::get_refraction_texture_channel);
- ClassDB::bind_method(D_METHOD("set_proximity_fade", "enabled"), &BaseMaterial3D::set_proximity_fade);
+ ClassDB::bind_method(D_METHOD("set_proximity_fade_enabled", "enabled"), &BaseMaterial3D::set_proximity_fade_enabled);
ClassDB::bind_method(D_METHOD("is_proximity_fade_enabled"), &BaseMaterial3D::is_proximity_fade_enabled);
ClassDB::bind_method(D_METHOD("set_proximity_fade_distance", "distance"), &BaseMaterial3D::set_proximity_fade_distance);
@@ -2808,7 +2808,7 @@ void BaseMaterial3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "point_size", PROPERTY_HINT_RANGE, "0.1,128,0.1,suffix:px"), "set_point_size", "get_point_size");
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_particle_trails"), "set_flag", "get_flag", FLAG_PARTICLE_TRAILS_MODE);
ADD_GROUP("Proximity Fade", "proximity_fade_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "proximity_fade_enable"), "set_proximity_fade", "is_proximity_fade_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "proximity_fade_enabled"), "set_proximity_fade_enabled", "is_proximity_fade_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "proximity_fade_distance", PROPERTY_HINT_RANGE, "0,4096,0.01,suffix:m"), "set_proximity_fade_distance", "get_proximity_fade_distance");
ADD_GROUP("MSDF", "msdf_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "msdf_pixel_range", PROPERTY_HINT_RANGE, "1,100,1"), "set_msdf_pixel_range", "get_msdf_pixel_range");
diff --git a/scene/resources/material.h b/scene/resources/material.h
index dd9589c577..b3c2159e70 100644
--- a/scene/resources/material.h
+++ b/scene/resources/material.h
@@ -719,7 +719,7 @@ public:
void set_on_top_of_alpha();
- void set_proximity_fade(bool p_enable);
+ void set_proximity_fade_enabled(bool p_enable);
bool is_proximity_fade_enabled() const;
void set_proximity_fade_distance(float p_distance);
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index 03ccae5b74..706db3af16 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -1576,9 +1576,8 @@ void ArrayMesh::_recompute_aabb() {
}
}
}
-#ifndef _MSC_VER
-#warning need to add binding to add_surface using future MeshSurfaceData object
-#endif
+
+// TODO: Need to add binding to add_surface using future MeshSurfaceData object.
void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) {
_create_if_empty();
diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp
index 1f71d583b1..1c99fa5554 100644
--- a/scene/resources/packed_scene.cpp
+++ b/scene/resources/packed_scene.cpp
@@ -1546,7 +1546,7 @@ Array SceneState::get_connection_binds(int p_idx) const {
return binds;
}
-bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method) {
+bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method, bool p_no_inheritance) {
// this method cannot be const because of this
Ref<SceneState> ss = this;
@@ -1578,6 +1578,10 @@ bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p
}
}
+ if (p_no_inheritance) {
+ break;
+ }
+
ss = ss->get_base_scene_state();
} while (ss.is_valid());
diff --git a/scene/resources/packed_scene.h b/scene/resources/packed_scene.h
index 8e1a1d29b6..c6f82ddd5e 100644
--- a/scene/resources/packed_scene.h
+++ b/scene/resources/packed_scene.h
@@ -176,7 +176,7 @@ public:
int get_connection_unbinds(int p_idx) const;
Array get_connection_binds(int p_idx) const;
- bool has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method);
+ bool has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method, bool p_no_inheritance = false);
Vector<NodePath> get_editable_instances() const;
diff --git a/scene/resources/particle_process_material.cpp b/scene/resources/particle_process_material.cpp
index e51c786786..b77430c154 100644
--- a/scene/resources/particle_process_material.cpp
+++ b/scene/resources/particle_process_material.cpp
@@ -115,6 +115,7 @@ void ParticleProcessMaterial::init_shaders() {
shader_names->sub_emitter_frequency = "sub_emitter_frequency";
shader_names->sub_emitter_amount_at_end = "sub_emitter_amount_at_end";
+ shader_names->sub_emitter_amount_at_collision = "sub_emitter_amount_at_collision";
shader_names->sub_emitter_keep_velocity = "sub_emitter_keep_velocity";
shader_names->collision_friction = "collision_friction";
@@ -235,6 +236,9 @@ void ParticleProcessMaterial::_update_shader() {
if (sub_emitter_mode == SUB_EMITTER_AT_END) {
code += "uniform int sub_emitter_amount_at_end;\n";
}
+ if (sub_emitter_mode == SUB_EMITTER_AT_COLLISION) {
+ code += "uniform int sub_emitter_amount_at_collision;\n";
+ }
code += "uniform bool sub_emitter_keep_velocity;\n";
}
@@ -830,6 +834,13 @@ void ParticleProcessMaterial::_update_shader() {
code += " TRANSFORM[3].z = 0.0;\n";
}
+ // scale by scale
+ code += " float base_scale = mix(scale_min, scale_max, scale_rand);\n";
+ code += " base_scale = sign(base_scale) * max(abs(base_scale), 0.001);\n";
+ code += " TRANSFORM[0].xyz *= base_scale * sign(tex_scale.r) * max(abs(tex_scale.r), 0.001);\n";
+ code += " TRANSFORM[1].xyz *= base_scale * sign(tex_scale.g) * max(abs(tex_scale.g), 0.001);\n";
+ code += " TRANSFORM[2].xyz *= base_scale * sign(tex_scale.b) * max(abs(tex_scale.b), 0.001);\n";
+
if (collision_mode == COLLISION_RIGID) {
code += " if (COLLIDED) {\n";
code += " if (length(VELOCITY) > 3.0) {\n";
@@ -844,21 +855,6 @@ void ParticleProcessMaterial::_update_shader() {
}
code += " }\n";
code += " }\n";
- }
-
- // scale by scale
- code += " float base_scale = mix(scale_min, scale_max, scale_rand);\n";
- code += " base_scale = sign(base_scale) * max(abs(base_scale), 0.001);\n";
- code += " TRANSFORM[0].xyz *= base_scale * sign(tex_scale.r) * max(abs(tex_scale.r), 0.001);\n";
- code += " TRANSFORM[1].xyz *= base_scale * sign(tex_scale.g) * max(abs(tex_scale.g), 0.001);\n";
- code += " TRANSFORM[2].xyz *= base_scale * sign(tex_scale.b) * max(abs(tex_scale.b), 0.001);\n";
-
- if (collision_mode == COLLISION_RIGID) {
- code += " if (COLLIDED) {\n";
- code += " TRANSFORM[3].xyz+=COLLISION_NORMAL * COLLISION_DEPTH;\n";
- code += " VELOCITY -= COLLISION_NORMAL * dot(COLLISION_NORMAL, VELOCITY) * (1.0 + collision_bounce);\n";
- code += " VELOCITY = mix(VELOCITY,vec3(0.0),collision_friction * DELTA * 100.0);\n";
- code += " }\n";
} else if (collision_mode == COLLISION_HIDE_ON_CONTACT) {
code += " if (COLLIDED) {\n";
code += " ACTIVE = false;\n";
@@ -874,7 +870,7 @@ void ParticleProcessMaterial::_update_shader() {
code += " if (DELTA >= interval_rem) emit_count = 1;\n";
} break;
case SUB_EMITTER_AT_COLLISION: {
- code += " if (COLLIDED) emit_count = 1;\n";
+ code += " if (COLLIDED) emit_count = sub_emitter_amount_at_collision;\n";
} break;
case SUB_EMITTER_AT_END: {
code += " float unit_delta = DELTA/LIFETIME;\n";
@@ -1433,6 +1429,10 @@ void ParticleProcessMaterial::_validate_property(PropertyInfo &p_property) const
p_property.usage = PROPERTY_USAGE_NONE;
}
+ if (p_property.name == "sub_emitter_amount_at_collision" && sub_emitter_mode != SUB_EMITTER_AT_COLLISION) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+
if (p_property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
p_property.usage = PROPERTY_USAGE_NONE;
}
@@ -1488,6 +1488,15 @@ int ParticleProcessMaterial::get_sub_emitter_amount_at_end() const {
return sub_emitter_amount_at_end;
}
+void ParticleProcessMaterial::set_sub_emitter_amount_at_collision(int p_amount) {
+ sub_emitter_amount_at_collision = p_amount;
+ RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->sub_emitter_amount_at_collision, p_amount);
+}
+
+int ParticleProcessMaterial::get_sub_emitter_amount_at_collision() const {
+ return sub_emitter_amount_at_collision;
+}
+
void ParticleProcessMaterial::set_sub_emitter_keep_velocity(bool p_enable) {
sub_emitter_keep_velocity = p_enable;
RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->sub_emitter_keep_velocity, p_enable);
@@ -1640,6 +1649,9 @@ void ParticleProcessMaterial::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_sub_emitter_amount_at_end"), &ParticleProcessMaterial::get_sub_emitter_amount_at_end);
ClassDB::bind_method(D_METHOD("set_sub_emitter_amount_at_end", "amount"), &ParticleProcessMaterial::set_sub_emitter_amount_at_end);
+ ClassDB::bind_method(D_METHOD("get_sub_emitter_amount_at_collision"), &ParticleProcessMaterial::get_sub_emitter_amount_at_collision);
+ ClassDB::bind_method(D_METHOD("set_sub_emitter_amount_at_collision", "amount"), &ParticleProcessMaterial::set_sub_emitter_amount_at_collision);
+
ClassDB::bind_method(D_METHOD("get_sub_emitter_keep_velocity"), &ParticleProcessMaterial::get_sub_emitter_keep_velocity);
ClassDB::bind_method(D_METHOD("set_sub_emitter_keep_velocity", "enable"), &ParticleProcessMaterial::set_sub_emitter_keep_velocity);
@@ -1752,6 +1764,7 @@ void ParticleProcessMaterial::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "sub_emitter_mode", PROPERTY_HINT_ENUM, "Disabled,Constant,At End,At Collision"), "set_sub_emitter_mode", "get_sub_emitter_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "sub_emitter_frequency", PROPERTY_HINT_RANGE, "0.01,100,0.01,suffix:Hz"), "set_sub_emitter_frequency", "get_sub_emitter_frequency");
ADD_PROPERTY(PropertyInfo(Variant::INT, "sub_emitter_amount_at_end", PROPERTY_HINT_RANGE, "1,32,1"), "set_sub_emitter_amount_at_end", "get_sub_emitter_amount_at_end");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sub_emitter_amount_at_collision", PROPERTY_HINT_RANGE, "1,32,1"), "set_sub_emitter_amount_at_collision", "get_sub_emitter_amount_at_collision");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sub_emitter_keep_velocity"), "set_sub_emitter_keep_velocity", "get_sub_emitter_keep_velocity");
ADD_GROUP("Attractor Interaction", "attractor_interaction_");
@@ -1859,6 +1872,7 @@ ParticleProcessMaterial::ParticleProcessMaterial() :
set_sub_emitter_mode(SUB_EMITTER_DISABLED);
set_sub_emitter_frequency(4);
set_sub_emitter_amount_at_end(1);
+ set_sub_emitter_amount_at_collision(1);
set_sub_emitter_keep_velocity(false);
set_attractor_interaction_enabled(true);
diff --git a/scene/resources/particle_process_material.h b/scene/resources/particle_process_material.h
index 8fe9223a47..64d828b3e7 100644
--- a/scene/resources/particle_process_material.h
+++ b/scene/resources/particle_process_material.h
@@ -246,6 +246,7 @@ private:
StringName sub_emitter_frequency;
StringName sub_emitter_amount_at_end;
+ StringName sub_emitter_amount_at_collision;
StringName sub_emitter_keep_velocity;
StringName collision_friction;
@@ -304,6 +305,7 @@ private:
SubEmitterMode sub_emitter_mode;
double sub_emitter_frequency = 0.0;
int sub_emitter_amount_at_end = 0;
+ int sub_emitter_amount_at_collision = 0;
bool sub_emitter_keep_velocity = false;
//do not save emission points here
@@ -418,6 +420,9 @@ public:
void set_sub_emitter_amount_at_end(int p_amount);
int get_sub_emitter_amount_at_end() const;
+ void set_sub_emitter_amount_at_collision(int p_amount);
+ int get_sub_emitter_amount_at_collision() const;
+
void set_sub_emitter_keep_velocity(bool p_enable);
bool get_sub_emitter_keep_velocity() const;
diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp
index 7d0336cff3..eb83a37c7b 100644
--- a/scene/resources/primitive_meshes.cpp
+++ b/scene/resources/primitive_meshes.cpp
@@ -771,6 +771,7 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
thisrow = 0;
prevrow = 0;
+ const real_t side_normal_y = (bottom_radius - top_radius) / height;
for (j = 0; j <= (rings + 1); j++) {
v = j;
v /= (rings + 1);
@@ -789,7 +790,7 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
Vector3 p = Vector3(x * radius, y, z * radius);
points.push_back(p);
- normals.push_back(Vector3(x, 0.0, z));
+ normals.push_back(Vector3(x, side_normal_y, z).normalized());
ADD_TANGENT(z, 0.0, -x, 1.0)
uvs.push_back(Vector2(u, v * 0.5));
point++;
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index c0d65fb445..85b538b1d9 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -445,7 +445,14 @@ Error ResourceLoaderText::load() {
// If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
path = ResourceUID::get_singleton()->get_id_path(uid);
} else {
+#ifdef TOOLS_ENABLED
+ // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
+ if (ResourceLoader::get_resource_uid(path) != uid) {
+ WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data());
+ }
+#else
WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data());
+#endif
}
}
diff --git a/scene/resources/shape_2d.cpp b/scene/resources/shape_2d.cpp
index fe43f345d4..61daf801e8 100644
--- a/scene/resources/shape_2d.cpp
+++ b/scene/resources/shape_2d.cpp
@@ -105,6 +105,7 @@ void Shape2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("collide_and_get_contacts", "local_xform", "with_shape", "shape_xform"), &Shape2D::collide_and_get_contacts);
ClassDB::bind_method(D_METHOD("collide_with_motion_and_get_contacts", "local_xform", "local_motion", "with_shape", "shape_xform", "shape_motion"), &Shape2D::collide_with_motion_and_get_contacts);
ClassDB::bind_method(D_METHOD("draw", "canvas_item", "color"), &Shape2D::draw);
+ ClassDB::bind_method(D_METHOD("get_rect"), &Shape2D::get_rect);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "custom_solver_bias", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_custom_solver_bias", "get_custom_solver_bias");
}
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index 4085aa8ec2..fbcf140925 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -122,7 +122,7 @@ void Texture2D::_bind_methods() {
GDVIRTUAL_BIND(_draw, "to_canvas_item", "pos", "modulate", "transpose")
GDVIRTUAL_BIND(_draw_rect, "to_canvas_item", "rect", "tile", "modulate", "transpose")
- GDVIRTUAL_BIND(_draw_rect_region, "tp_canvas_item", "rect", "src_rect", "modulate", "transpose", "clip_uv");
+ GDVIRTUAL_BIND(_draw_rect_region, "to_canvas_item", "rect", "src_rect", "modulate", "transpose", "clip_uv");
}
Texture2D::Texture2D() {
@@ -740,7 +740,7 @@ Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_si
}
}
- image->create(w, h, true, mipmap_images[0]->get_format(), img_data);
+ image->set_data(w, h, true, mipmap_images[0]->get_format(), img_data);
return image;
}
@@ -766,10 +766,7 @@ Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_si
f->get_buffer(wr, data.size());
}
- Ref<Image> image;
- image.instantiate();
-
- image->create(tw, th, mipmaps - i ? true : false, format, data);
+ Ref<Image> image = Image::create_from_data(tw, th, mipmaps - i ? true : false, format, data);
return image;
}
@@ -2336,11 +2333,11 @@ void GradientTexture2D::_update() {
image.instantiate();
if (gradient->get_points_count() <= 1) { // No need to interpolate.
- image->create(width, height, false, (use_hdr) ? Image::FORMAT_RGBAF : Image::FORMAT_RGBA8);
+ image->initialize_data(width, height, false, (use_hdr) ? Image::FORMAT_RGBAF : Image::FORMAT_RGBA8);
image->fill((gradient->get_points_count() == 1) ? gradient->get_color(0) : Color(0, 0, 0, 1));
} else {
if (use_hdr) {
- image->create(width, height, false, Image::FORMAT_RGBAF);
+ image->initialize_data(width, height, false, Image::FORMAT_RGBAF);
Gradient &g = **gradient;
// `create()` isn't available for non-uint8_t data, so fill in the data manually.
for (int y = 0; y < height; y++) {
@@ -2367,7 +2364,7 @@ void GradientTexture2D::_update() {
}
}
}
- image->create(width, height, false, Image::FORMAT_RGBA8, data);
+ image->set_data(width, height, false, Image::FORMAT_RGBA8, data);
}
}
diff --git a/scene/resources/texture.h b/scene/resources/texture.h
index 4e529de8ee..9a9f0ad1af 100644
--- a/scene/resources/texture.h
+++ b/scene/resources/texture.h
@@ -238,7 +238,7 @@ private:
Error _load_data(const String &p_path, int &r_width, int &r_height, Ref<Image> &image, bool &r_request_3d, bool &r_request_normal, bool &r_request_roughness, int &mipmap_limit, int p_size_limit = 0);
String path_to_file;
mutable RID texture;
- Image::Format format = Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_L8;
int w = 0;
int h = 0;
mutable Ref<BitMap> alpha_cache;
@@ -415,7 +415,7 @@ class ImageTextureLayered : public TextureLayered {
LayeredType layered_type;
mutable RID texture;
- Image::Format format = Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_L8;
int width = 0;
int height = 0;
@@ -495,7 +495,7 @@ private:
Error _load_data(const String &p_path, Vector<Ref<Image>> &images, int &mipmap_limit, int p_size_limit = 0);
String path_to_file;
mutable RID texture;
- Image::Format format = Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_L8;
int w = 0;
int h = 0;
int layers = 0;
@@ -587,7 +587,7 @@ class ImageTexture3D : public Texture3D {
mutable RID texture;
- Image::Format format = Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_L8;
int width = 1;
int height = 1;
int depth = 1;
@@ -641,7 +641,7 @@ private:
Error _load_data(const String &p_path, Vector<Ref<Image>> &r_data, Image::Format &r_format, int &r_width, int &r_height, int &r_depth, bool &r_mipmaps);
String path_to_file;
mutable RID texture;
- Image::Format format = Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_L8;
int w = 0;
int h = 0;
int d = 0;
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index d7d7b5fe31..3caf6484d9 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -1801,11 +1801,11 @@ Vector<Vector<Ref<Texture2D>>> TileSet::generate_terrains_icons(Size2i p_size) {
// Get the best tile.
Ref<Texture2D> texture = counts[terrain_set][terrain].texture;
Rect2i region = counts[terrain_set][terrain].region;
- image->create(region.size.x, region.size.y, false, Image::FORMAT_RGBA8);
+ image->initialize_data(region.size.x, region.size.y, false, Image::FORMAT_RGBA8);
image->blit_rect(texture->get_image(), region, Point2i());
image->resize(p_size.x, p_size.y, Image::INTERPOLATE_NEAREST);
} else {
- image->create(1, 1, false, Image::FORMAT_RGBA8);
+ image->initialize_data(1, 1, false, Image::FORMAT_RGBA8);
image->set_pixel(0, 0, get_terrain_color(terrain_set, terrain));
}
Ref<ImageTexture> icon = ImageTexture::create_from_image(image);
@@ -4602,9 +4602,7 @@ void TileSetAtlasSource::_update_padded_texture() {
return;
}
- Ref<Image> image;
- image.instantiate();
- image->create(size.x, size.y, false, src->get_format());
+ Ref<Image> image = Image::create_empty(size.x, size.y, false, src->get_format());
for (KeyValue<Vector2i, TileAlternativesData> kv : tiles) {
for (int frame = 0; frame < (int)kv.value.animation_frames_durations.size(); frame++) {
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index e156679711..8f175e99a6 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -277,6 +277,9 @@ public:
bool operator<(const TerrainsPattern &p_terrains_pattern) const;
bool operator==(const TerrainsPattern &p_terrains_pattern) const;
+ bool operator!=(const TerrainsPattern &p_terrains_pattern) const {
+ return !operator==(p_terrains_pattern);
+ };
void set_terrain(int p_terrain);
int get_terrain() const;
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index df9addb6bb..640f6dfcb7 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -1509,11 +1509,10 @@ bool VisualShader::_get(const StringName &p_name, Variant &r_ret) const {
}
void VisualShader::reset_state() {
-#ifndef _MSC_VER
-#warning everything needs to be cleared here
-#endif
+ // TODO: Everything needs to be cleared here.
emit_changed();
}
+
void VisualShader::_get_property_list(List<PropertyInfo> *p_list) const {
//mode
p_list->push_back(PropertyInfo(Variant::INT, PNAME("mode"), PROPERTY_HINT_ENUM, "Node3D,CanvasItem,Particles,Sky,Fog"));
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index de13912b75..04637983b5 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -1642,17 +1642,20 @@ bool VisualShaderNodeLinearSceneDepth::has_output_port_preview(int p_port) const
String VisualShaderNodeLinearSceneDepth::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
+ code += " {\n";
- code += " float _log_depth = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x;\n";
- code += " vec3 _depth_ndc = vec3(SCREEN_UV * 2.0 - 1.0, _log_depth);\n";
- code += " vec4 _depth_view = INV_PROJECTION_MATRIX * vec4(_depth_ndc, 1.0);\n";
- code += " _depth_view.xyz /= _depth_view.w;";
- code += vformat(" %s = -_depth_view.z;", p_output_vars[0]);
+ code += " float __log_depth = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x;\n";
+ code += " vec3 __depth_ndc = vec3(SCREEN_UV * 2.0 - 1.0, __log_depth);\n";
+ code += " vec4 __depth_view = INV_PROJECTION_MATRIX * vec4(__depth_ndc, 1.0);\n";
+ code += " __depth_view.xyz /= __depth_view.w;\n";
+ code += vformat(" %s = -__depth_view.z;\n", p_output_vars[0]);
+ code += " }\n";
return code;
}
VisualShaderNodeLinearSceneDepth::VisualShaderNodeLinearSceneDepth() {
+ simple_decl = false;
}
////////////// Float Op
@@ -3204,6 +3207,7 @@ String VisualShaderNodeUVPolarCoord::get_output_port_name(int p_port) const {
String VisualShaderNodeUVPolarCoord::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
+ code += " {\n";
String uv;
if (p_input_vars[0].is_empty()) {
@@ -3220,17 +3224,18 @@ String VisualShaderNodeUVPolarCoord::generate_code(Shader::Mode p_mode, VisualSh
String repeat = vformat("%s", p_input_vars[3]);
if (p_mode == Shader::MODE_CANVAS_ITEM) {
- code += vformat(" vec2 __dir = %s - %s;\n", uv, center);
- code += " float __radius = length(__dir) * 2.0;\n";
- code += " float __angle = atan(__dir.y, __dir.x) * 1.0/(PI * 2.0);\n";
- code += vformat(" %s = mod(vec2(__radius * %s, __angle * %s), 1.0);\n", p_output_vars[0], zoom, repeat);
+ code += vformat(" vec2 __dir = %s - %s;\n", uv, center);
+ code += " float __radius = length(__dir) * 2.0;\n";
+ code += " float __angle = atan(__dir.y, __dir.x) * 1.0 / (PI * 2.0);\n";
+ code += vformat(" %s = mod(vec2(__radius * %s, __angle * %s), 1.0);\n", p_output_vars[0], zoom, repeat);
} else {
- code += vformat(" vec2 __dir = %s - %s;\n", uv, center);
- code += " float __radius = length(__dir) * 2.0;\n";
- code += " float __angle = atan(__dir.y, __dir.x) * 1.0/(PI * 2.0);\n";
- code += vformat(" %s = vec2(__radius * %s, __angle * %s);\n", p_output_vars[0], zoom, repeat);
+ code += vformat(" vec2 __dir = %s - %s;\n", uv, center);
+ code += " float __radius = length(__dir) * 2.0;\n";
+ code += " float __angle = atan(__dir.y, __dir.x) * 1.0 / (PI * 2.0);\n";
+ code += vformat(" %s = vec2(__radius * %s, __angle * %s);\n", p_output_vars[0], zoom, repeat);
}
+ code += " }\n";
return code;
}
@@ -3238,6 +3243,8 @@ VisualShaderNodeUVPolarCoord::VisualShaderNodeUVPolarCoord() {
set_input_port_default_value(1, Vector2(0.5, 0.5)); // center
set_input_port_default_value(2, 1.0); // zoom
set_input_port_default_value(3, 1.0); // repeat
+
+ simple_decl = false;
}
////////////// Dot Product
@@ -7256,22 +7263,26 @@ bool VisualShaderNodeProximityFade::has_output_port_preview(int p_port) const {
String VisualShaderNodeProximityFade::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
+ code += " {\n";
String proximity_fade_distance = vformat("%s", p_input_vars[0]);
- code += " float __depth_tex = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).r;\n";
+ code += " float __depth_tex = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).r;\n";
if (!RenderingServer::get_singleton()->is_low_end()) {
- code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, __depth_tex, 1.0);\n";
+ code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, __depth_tex, 1.0);\n";
} else {
- code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(vec3(SCREEN_UV, __depth_tex) * 2.0 - 1.0, 1.0);\n";
+ code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(vec3(SCREEN_UV, __depth_tex) * 2.0 - 1.0, 1.0);\n";
}
- code += " __depth_world_pos.xyz /= __depth_world_pos.z;\n";
- code += vformat(" %s = clamp(1.0 - smoothstep(__depth_world_pos.z + %s, __depth_world_pos.z, VERTEX.z), 0.0, 1.0);\n", p_output_vars[0], p_input_vars[0]);
+ code += " __depth_world_pos.xyz /= __depth_world_pos.w;\n";
+ code += vformat(" %s = clamp(1.0 - smoothstep(__depth_world_pos.z + %s, __depth_world_pos.z, VERTEX.z), 0.0, 1.0);\n", p_output_vars[0], p_input_vars[0]);
+ code += " }\n";
return code;
}
VisualShaderNodeProximityFade::VisualShaderNodeProximityFade() {
set_input_port_default_value(0, 1.0);
+
+ simple_decl = false;
}
////////////// Random Range
@@ -7416,11 +7427,11 @@ String VisualShaderNodeRemap::get_output_port_name(int p_port) const {
String VisualShaderNodeRemap::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
-
- code += vformat(" float _input_range = %s - %s;\n", p_input_vars[2], p_input_vars[1]);
- code += vformat(" float _output_range = %s - %s;\n", p_input_vars[4], p_input_vars[3]);
- code += vformat(" %s = %s + _output_range * ((%s - %s) / _input_range);\n", p_output_vars[0], p_input_vars[3], p_input_vars[0], p_input_vars[1]);
-
+ code += " {\n";
+ code += vformat(" float __input_range = %s - %s;\n", p_input_vars[2], p_input_vars[1]);
+ code += vformat(" float __output_range = %s - %s;\n", p_input_vars[4], p_input_vars[3]);
+ code += vformat(" %s = %s + __output_range * ((%s - %s) / __input_range);\n", p_output_vars[0], p_input_vars[3], p_input_vars[0], p_input_vars[1]);
+ code += " }\n";
return code;
}
@@ -7429,4 +7440,6 @@ VisualShaderNodeRemap::VisualShaderNodeRemap() {
set_input_port_default_value(2, 1.0);
set_input_port_default_value(3, 0.0);
set_input_port_default_value(4, 1.0);
+
+ simple_decl = false;
}
diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp
index ab7354f6e7..f125b05a26 100644
--- a/scene/resources/visual_shader_particle_nodes.cpp
+++ b/scene/resources/visual_shader_particle_nodes.cpp
@@ -460,9 +460,9 @@ void VisualShaderNodeParticleMeshEmitter::_update_texture(const Vector<Vector2>
image.instantiate();
if (p_array.size() == 0) {
- image->create(1, 1, false, Image::Format::FORMAT_RGBF);
+ image->initialize_data(1, 1, false, Image::Format::FORMAT_RGBF);
} else {
- image->create(p_array.size(), 1, false, Image::Format::FORMAT_RGBF);
+ image->initialize_data(p_array.size(), 1, false, Image::Format::FORMAT_RGBF);
}
for (int i = 0; i < p_array.size(); i++) {
@@ -481,9 +481,9 @@ void VisualShaderNodeParticleMeshEmitter::_update_texture(const Vector<Vector3>
image.instantiate();
if (p_array.size() == 0) {
- image->create(1, 1, false, Image::Format::FORMAT_RGBF);
+ image->initialize_data(1, 1, false, Image::Format::FORMAT_RGBF);
} else {
- image->create(p_array.size(), 1, false, Image::Format::FORMAT_RGBF);
+ image->initialize_data(p_array.size(), 1, false, Image::Format::FORMAT_RGBF);
}
for (int i = 0; i < p_array.size(); i++) {
@@ -502,9 +502,9 @@ void VisualShaderNodeParticleMeshEmitter::_update_texture(const Vector<Color> &p
image.instantiate();
if (p_array.size() == 0) {
- image->create(1, 1, false, Image::Format::FORMAT_RGBA8);
+ image->initialize_data(1, 1, false, Image::Format::FORMAT_RGBA8);
} else {
- image->create(p_array.size(), 1, false, Image::Format::FORMAT_RGBA8);
+ image->initialize_data(p_array.size(), 1, false, Image::Format::FORMAT_RGBA8);
}
for (int i = 0; i < p_array.size(); i++) {
diff --git a/servers/display_server.cpp b/servers/display_server.cpp
index 4b97bede56..f079085543 100644
--- a/servers/display_server.cpp
+++ b/servers/display_server.cpp
@@ -865,9 +865,9 @@ Vector<String> DisplayServer::get_create_function_rendering_drivers(int p_index)
return server_create_functions[p_index].get_rendering_drivers_function();
}
-DisplayServer *DisplayServer::create(int p_index, const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+DisplayServer *DisplayServer::create(int p_index, const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
ERR_FAIL_INDEX_V(p_index, server_create_count, nullptr);
- return server_create_functions[p_index].create_function(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error);
+ return server_create_functions[p_index].create_function(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error);
}
void DisplayServer::_input_set_mouse_mode(Input::MouseMode p_mode) {
diff --git a/servers/display_server.h b/servers/display_server.h
index 8eafccc040..55e9fb55dc 100644
--- a/servers/display_server.h
+++ b/servers/display_server.h
@@ -72,7 +72,7 @@ public:
WINDOW_VIEW,
};
- typedef DisplayServer *(*CreateFunction)(const String &, WindowMode, VSyncMode, uint32_t, const Size2i &, Error &r_error);
+ typedef DisplayServer *(*CreateFunction)(const String &, WindowMode, VSyncMode, uint32_t, const Point2i *, const Size2i &, Error &r_error);
typedef Vector<String> (*GetRenderingDriversFunction)();
private:
@@ -382,7 +382,7 @@ public:
virtual void window_move_to_foreground(WindowID p_window = MAIN_WINDOW_ID) = 0;
virtual void window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window = MAIN_WINDOW_ID) {}
- virtual Vector2i window_get_safe_title_margins(WindowID p_window = MAIN_WINDOW_ID) const { return Vector2i(); }
+ virtual Vector3i window_get_safe_title_margins(WindowID p_window = MAIN_WINDOW_ID) const { return Vector3i(); }
virtual bool window_can_draw(WindowID p_window = MAIN_WINDOW_ID) const = 0;
@@ -483,7 +483,7 @@ public:
static int get_create_function_count();
static const char *get_create_function_name(int p_index);
static Vector<String> get_create_function_rendering_drivers(int p_index);
- static DisplayServer *create(int p_index, const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error);
+ static DisplayServer *create(int p_index, const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error);
DisplayServer();
~DisplayServer();
diff --git a/servers/display_server_headless.h b/servers/display_server_headless.h
index 3853ff4fdc..e1a27b6137 100644
--- a/servers/display_server_headless.h
+++ b/servers/display_server_headless.h
@@ -45,7 +45,7 @@ private:
return drivers;
}
- static DisplayServer *create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
+ static DisplayServer *create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, DisplayServer::VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, Error &r_error) {
r_error = OK;
RasterizerDummy::make_current();
return memnew(DisplayServerHeadless());
diff --git a/servers/physics_3d/godot_body_3d.cpp b/servers/physics_3d/godot_body_3d.cpp
index cec233d95b..53f4ab86f9 100644
--- a/servers/physics_3d/godot_body_3d.cpp
+++ b/servers/physics_3d/godot_body_3d.cpp
@@ -118,7 +118,7 @@ void GodotBody3D::update_mass_properties() {
shape_inertia_tensor = shape_basis * shape_inertia_tensor * shape_basis.transposed();
Vector3 shape_origin = shape_transform.origin - center_of_mass_local;
- inertia_tensor += shape_inertia_tensor + (Basis() * shape_origin.dot(shape_origin) - shape_origin.outer(shape_origin)) * mass;
+ inertia_tensor += shape_inertia_tensor + (Basis() * shape_origin.dot(shape_origin) - shape_origin.outer(shape_origin)) * mass_new;
}
// Set the inertia to a valid value when there are no valid shapes.
diff --git a/servers/physics_3d/godot_collision_solver_3d_sat.cpp b/servers/physics_3d/godot_collision_solver_3d_sat.cpp
index 933a5e28df..96253cb452 100644
--- a/servers/physics_3d/godot_collision_solver_3d_sat.cpp
+++ b/servers/physics_3d/godot_collision_solver_3d_sat.cpp
@@ -964,8 +964,8 @@ static void _collision_sphere_convex_polygon(const GodotShape3D *p_a, const Tran
// edges of B
for (int i = 0; i < edge_count; i++) {
- Vector3 v1 = p_transform_b.xform(vertices[edges[i].a]);
- Vector3 v2 = p_transform_b.xform(vertices[edges[i].b]);
+ Vector3 v1 = p_transform_b.xform(vertices[edges[i].vertex_a]);
+ Vector3 v2 = p_transform_b.xform(vertices[edges[i].vertex_b]);
Vector3 v3 = p_transform_a.origin;
Vector3 n1 = v2 - v1;
@@ -1404,7 +1404,7 @@ static void _collision_box_convex_polygon(const GodotShape3D *p_a, const Transfo
Vector3 e1 = p_transform_a.basis.get_column(i);
for (int j = 0; j < edge_count; j++) {
- Vector3 e2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]);
+ Vector3 e2 = p_transform_b.basis.xform(vertices[edges[j].vertex_a]) - p_transform_b.basis.xform(vertices[edges[j].vertex_b]);
Vector3 axis = e1.cross(e2).normalized();
@@ -1460,8 +1460,8 @@ static void _collision_box_convex_polygon(const GodotShape3D *p_a, const Transfo
}
for (int e = 0; e < edge_count; e++) {
- Vector3 p1 = p_transform_b.xform(vertices[edges[e].a]);
- Vector3 p2 = p_transform_b.xform(vertices[edges[e].b]);
+ Vector3 p1 = p_transform_b.xform(vertices[edges[e].vertex_a]);
+ Vector3 p2 = p_transform_b.xform(vertices[edges[e].vertex_b]);
Vector3 n = (p2 - p1);
if (!separator.test_axis((point - p2).cross(n).cross(n).normalized())) {
@@ -1771,7 +1771,7 @@ static void _collision_capsule_convex_polygon(const GodotShape3D *p_a, const Tra
for (int i = 0; i < edge_count; i++) {
// cylinder
- Vector3 edge_axis = p_transform_b.basis.xform(vertices[edges[i].a]) - p_transform_b.basis.xform(vertices[edges[i].b]);
+ Vector3 edge_axis = p_transform_b.basis.xform(vertices[edges[i].vertex_a]) - p_transform_b.basis.xform(vertices[edges[i].vertex_b]);
Vector3 axis = edge_axis.cross(p_transform_a.basis.get_column(1)).normalized();
if (!separator.test_axis(axis)) {
@@ -1789,8 +1789,8 @@ static void _collision_capsule_convex_polygon(const GodotShape3D *p_a, const Tra
Vector3 sphere_pos = p_transform_a.origin + ((i == 0) ? capsule_axis : -capsule_axis);
for (int j = 0; j < edge_count; j++) {
- Vector3 n1 = sphere_pos - p_transform_b.xform(vertices[edges[j].a]);
- Vector3 n2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]);
+ Vector3 n1 = sphere_pos - p_transform_b.xform(vertices[edges[j].vertex_a]);
+ Vector3 n2 = p_transform_b.basis.xform(vertices[edges[j].vertex_a]) - p_transform_b.basis.xform(vertices[edges[j].vertex_b]);
Vector3 axis = n1.cross(n2).cross(n2).normalized();
@@ -2075,6 +2075,16 @@ static void _collision_cylinder_face(const GodotShape3D *p_a, const Transform3D
separator.generate_contacts();
}
+static _FORCE_INLINE_ bool is_minkowski_face(const Vector3 &A, const Vector3 &B, const Vector3 &B_x_A, const Vector3 &C, const Vector3 &D, const Vector3 &D_x_C) {
+ // Test if arcs AB and CD intersect on the unit sphere
+ real_t CBA = C.dot(B_x_A);
+ real_t DBA = D.dot(B_x_A);
+ real_t ADC = A.dot(D_x_C);
+ real_t BDC = B.dot(D_x_C);
+
+ return (CBA * DBA < 0.0f) && (ADC * BDC < 0.0f) && (CBA * BDC > 0.0f);
+}
+
template <bool withMargin>
static void _collision_convex_polygon_convex_polygon(const GodotShape3D *p_a, const Transform3D &p_transform_a, const GodotShape3D *p_b, const Transform3D &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
const GodotConvexPolygonShape3D *convex_polygon_A = static_cast<const GodotConvexPolygonShape3D *>(p_a);
@@ -2129,16 +2139,27 @@ static void _collision_convex_polygon_convex_polygon(const GodotShape3D *p_a, co
}
// A<->B edges
+
for (int i = 0; i < edge_count_A; i++) {
- Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]) - p_transform_a.basis.xform(vertices_A[edges_A[i].b]);
+ Vector3 p1 = p_transform_a.xform(vertices_A[edges_A[i].vertex_a]);
+ Vector3 q1 = p_transform_a.xform(vertices_A[edges_A[i].vertex_b]);
+ Vector3 e1 = q1 - p1;
+ Vector3 u1 = p_transform_a.basis.xform(faces_A[edges_A[i].face_a].plane.normal).normalized();
+ Vector3 v1 = p_transform_a.basis.xform(faces_A[edges_A[i].face_b].plane.normal).normalized();
for (int j = 0; j < edge_count_B; j++) {
- Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[j].a]) - p_transform_b.basis.xform(vertices_B[edges_B[j].b]);
+ Vector3 p2 = p_transform_b.xform(vertices_B[edges_B[j].vertex_a]);
+ Vector3 q2 = p_transform_b.xform(vertices_B[edges_B[j].vertex_b]);
+ Vector3 e2 = q2 - p2;
+ Vector3 u2 = p_transform_b.basis.xform(faces_B[edges_B[j].face_a].plane.normal).normalized();
+ Vector3 v2 = p_transform_b.basis.xform(faces_B[edges_B[j].face_b].plane.normal).normalized();
- Vector3 axis = e1.cross(e2).normalized();
+ if (is_minkowski_face(u1, v1, -e1, -u2, -v2, -e2)) {
+ Vector3 axis = e1.cross(e2).normalized();
- if (!separator.test_axis(axis)) {
- return;
+ if (!separator.test_axis(axis)) {
+ return;
+ }
}
}
}
@@ -2157,8 +2178,8 @@ static void _collision_convex_polygon_convex_polygon(const GodotShape3D *p_a, co
//edge-vertex (shell)
for (int i = 0; i < edge_count_A; i++) {
- Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]);
- Vector3 e2 = p_transform_a.basis.xform(vertices_A[edges_A[i].b]);
+ Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].vertex_a]);
+ Vector3 e2 = p_transform_a.basis.xform(vertices_A[edges_A[i].vertex_b]);
Vector3 n = (e2 - e1);
for (int j = 0; j < vertex_count_B; j++) {
@@ -2171,8 +2192,8 @@ static void _collision_convex_polygon_convex_polygon(const GodotShape3D *p_a, co
}
for (int i = 0; i < edge_count_B; i++) {
- Vector3 e1 = p_transform_b.basis.xform(vertices_B[edges_B[i].a]);
- Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[i].b]);
+ Vector3 e1 = p_transform_b.basis.xform(vertices_B[edges_B[i].vertex_a]);
+ Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[i].vertex_b]);
Vector3 n = (e2 - e1);
for (int j = 0; j < vertex_count_A; j++) {
@@ -2231,7 +2252,7 @@ static void _collision_convex_polygon_face(const GodotShape3D *p_a, const Transf
// A<->B edges
for (int i = 0; i < edge_count; i++) {
- Vector3 e1 = p_transform_a.xform(vertices[edges[i].a]) - p_transform_a.xform(vertices[edges[i].b]);
+ Vector3 e1 = p_transform_a.xform(vertices[edges[i].vertex_a]) - p_transform_a.xform(vertices[edges[i].vertex_b]);
for (int j = 0; j < 3; j++) {
Vector3 e2 = vertex[j] - vertex[(j + 1) % 3];
@@ -2266,8 +2287,8 @@ static void _collision_convex_polygon_face(const GodotShape3D *p_a, const Transf
//edge-vertex (shell)
for (int i = 0; i < edge_count; i++) {
- Vector3 e1 = p_transform_a.basis.xform(vertices[edges[i].a]);
- Vector3 e2 = p_transform_a.basis.xform(vertices[edges[i].b]);
+ Vector3 e1 = p_transform_a.basis.xform(vertices[edges[i].vertex_a]);
+ Vector3 e2 = p_transform_a.basis.xform(vertices[edges[i].vertex_b]);
Vector3 n = (e2 - e1);
for (int j = 0; j < 3; j++) {
diff --git a/servers/physics_3d/godot_shape_3d.cpp b/servers/physics_3d/godot_shape_3d.cpp
index e051c688fa..1443cd166b 100644
--- a/servers/physics_3d/godot_shape_3d.cpp
+++ b/servers/physics_3d/godot_shape_3d.cpp
@@ -817,48 +817,78 @@ GodotCylinderShape3D::GodotCylinderShape3D() {}
/********** CONVEX POLYGON *************/
void GodotConvexPolygonShape3D::project_range(const Vector3 &p_normal, const Transform3D &p_transform, real_t &r_min, real_t &r_max) const {
- int vertex_count = mesh.vertices.size();
+ uint32_t vertex_count = mesh.vertices.size();
if (vertex_count == 0) {
return;
}
const Vector3 *vrts = &mesh.vertices[0];
- for (int i = 0; i < vertex_count; i++) {
- real_t d = p_normal.dot(p_transform.xform(vrts[i]));
+ if (vertex_count > 3 * extreme_vertices.size()) {
+ // For a large mesh, two calls to get_support() is faster than a full
+ // scan over all vertices.
- if (i == 0 || d > r_max) {
- r_max = d;
- }
- if (i == 0 || d < r_min) {
- r_min = d;
+ Vector3 n = p_transform.basis.xform_inv(p_normal).normalized();
+ r_min = p_normal.dot(p_transform.xform(get_support(-n)));
+ r_max = p_normal.dot(p_transform.xform(get_support(n)));
+ } else {
+ for (uint32_t i = 0; i < vertex_count; i++) {
+ real_t d = p_normal.dot(p_transform.xform(vrts[i]));
+
+ if (i == 0 || d > r_max) {
+ r_max = d;
+ }
+ if (i == 0 || d < r_min) {
+ r_min = d;
+ }
}
}
}
Vector3 GodotConvexPolygonShape3D::get_support(const Vector3 &p_normal) const {
- Vector3 n = p_normal;
-
- int vert_support_idx = -1;
- real_t support_max = 0;
-
- int vertex_count = mesh.vertices.size();
- if (vertex_count == 0) {
+ if (mesh.vertices.size() == 0) {
return Vector3();
}
- const Vector3 *vrts = &mesh.vertices[0];
-
- for (int i = 0; i < vertex_count; i++) {
- real_t d = n.dot(vrts[i]);
+ // Find an initial guess for the support vertex by checking the ones we
+ // found in _setup().
- if (i == 0 || d > support_max) {
- support_max = d;
- vert_support_idx = i;
+ int best_vertex = -1;
+ real_t max_support = 0.0;
+ for (uint32_t i = 0; i < extreme_vertices.size(); i++) {
+ real_t s = p_normal.dot(mesh.vertices[extreme_vertices[i]]);
+ if (best_vertex == -1 || s > max_support) {
+ best_vertex = extreme_vertices[i];
+ max_support = s;
}
}
+ if (extreme_vertices.size() == mesh.vertices.size()) {
+ // We've already checked every vertex, so we can return now.
+ return mesh.vertices[best_vertex];
+ }
+
+ // Move along the surface until we reach the true support vertex.
- return vrts[vert_support_idx];
+ int last_vertex = -1;
+ while (true) {
+ int next_vertex = -1;
+ for (uint32_t i = 0; i < vertex_neighbors[best_vertex].size(); i++) {
+ int vert = vertex_neighbors[best_vertex][i];
+ if (vert != last_vertex) {
+ real_t s = p_normal.dot(mesh.vertices[vert]);
+ if (s > max_support) {
+ next_vertex = vert;
+ max_support = s;
+ break;
+ }
+ }
+ }
+ if (next_vertex == -1) {
+ return mesh.vertices[best_vertex];
+ }
+ last_vertex = best_vertex;
+ best_vertex = next_vertex;
+ }
}
void GodotConvexPolygonShape3D::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount, FeatureType &r_type) const {
@@ -915,13 +945,13 @@ void GodotConvexPolygonShape3D::get_supports(const Vector3 &p_normal, int p_max,
}
for (int i = 0; i < ec; i++) {
- real_t dot = (vertices[edges[i].a] - vertices[edges[i].b]).normalized().dot(p_normal);
+ real_t dot = (vertices[edges[i].vertex_a] - vertices[edges[i].vertex_b]).normalized().dot(p_normal);
dot = ABS(dot);
- if (dot < edge_support_threshold && (edges[i].a == vtx || edges[i].b == vtx)) {
+ if (dot < edge_support_threshold && (edges[i].vertex_a == vtx || edges[i].vertex_b == vtx)) {
r_amount = 2;
r_type = FEATURE_EDGE;
- r_supports[0] = vertices[edges[i].a];
- r_supports[1] = vertices[edges[i].b];
+ r_supports[0] = vertices[edges[i].vertex_a];
+ r_supports[1] = vertices[edges[i].vertex_b];
return;
}
}
@@ -1025,8 +1055,8 @@ Vector3 GodotConvexPolygonShape3D::get_closest_point_to(const Vector3 &p_point)
int ec = mesh.edges.size();
for (int i = 0; i < ec; i++) {
Vector3 s[2] = {
- vertices[edges[i].a],
- vertices[edges[i].b]
+ vertices[edges[i].vertex_a],
+ vertices[edges[i].vertex_b]
};
Vector3 closest = Geometry3D::get_closest_point_to_segment(p_point, s);
@@ -1058,7 +1088,7 @@ void GodotConvexPolygonShape3D::_setup(const Vector<Vector3> &p_vertices) {
AABB _aabb;
- for (int i = 0; i < mesh.vertices.size(); i++) {
+ for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
if (i == 0) {
_aabb.position = mesh.vertices[i];
} else {
@@ -1067,6 +1097,43 @@ void GodotConvexPolygonShape3D::_setup(const Vector<Vector3> &p_vertices) {
}
configure(_aabb);
+
+ // Pre-compute the extreme vertices in 26 directions. This will be used
+ // to speed up get_support() by letting us quickly get a good guess for
+ // the support vertex.
+
+ for (int x = -1; x < 2; x++) {
+ for (int y = -1; y < 2; y++) {
+ for (int z = -1; z < 2; z++) {
+ if (x != 0 || y != 0 || z != 0) {
+ Vector3 dir(x, y, z);
+ dir.normalize();
+ real_t max_support = 0.0;
+ int best_vertex = -1;
+ for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
+ real_t s = dir.dot(mesh.vertices[i]);
+ if (best_vertex == -1 || s > max_support) {
+ best_vertex = i;
+ max_support = s;
+ }
+ }
+ if (extreme_vertices.find(best_vertex) == -1)
+ extreme_vertices.push_back(best_vertex);
+ }
+ }
+ }
+ }
+
+ // Record all the neighbors of each vertex. This is used in get_support().
+
+ if (extreme_vertices.size() < mesh.vertices.size()) {
+ vertex_neighbors.resize(mesh.vertices.size());
+ for (uint32_t i = 0; i < mesh.edges.size(); i++) {
+ Geometry3D::MeshData::Edge &edge = mesh.edges[i];
+ vertex_neighbors[edge.vertex_a].push_back(edge.vertex_b);
+ vertex_neighbors[edge.vertex_b].push_back(edge.vertex_a);
+ }
+ }
}
void GodotConvexPolygonShape3D::set_data(const Variant &p_data) {
@@ -1074,7 +1141,12 @@ void GodotConvexPolygonShape3D::set_data(const Variant &p_data) {
}
Variant GodotConvexPolygonShape3D::get_data() const {
- return mesh.vertices;
+ Vector<Vector3> vertices;
+ vertices.resize(mesh.vertices.size());
+ for (uint32_t i = 0; i < mesh.vertices.size(); i++) {
+ vertices.write[i] = mesh.vertices[i];
+ }
+ return vertices;
}
GodotConvexPolygonShape3D::GodotConvexPolygonShape3D() {
diff --git a/servers/physics_3d/godot_shape_3d.h b/servers/physics_3d/godot_shape_3d.h
index 1fc8f7c711..dc8e34e2bc 100644
--- a/servers/physics_3d/godot_shape_3d.h
+++ b/servers/physics_3d/godot_shape_3d.h
@@ -277,6 +277,8 @@ public:
struct GodotConvexPolygonShape3D : public GodotShape3D {
Geometry3D::MeshData mesh;
+ LocalVector<int> extreme_vertices;
+ LocalVector<LocalVector<int>> vertex_neighbors;
void _setup(const Vector<Vector3> &p_vertices);
diff --git a/servers/rendering/dummy/storage/utilities.h b/servers/rendering/dummy/storage/utilities.h
index cb7b2a2b63..a42ab0d814 100644
--- a/servers/rendering/dummy/storage/utilities.h
+++ b/servers/rendering/dummy/storage/utilities.h
@@ -109,6 +109,8 @@ public:
virtual String get_video_adapter_vendor() const override { return String(); }
virtual RenderingDevice::DeviceType get_video_adapter_type() const override { return RenderingDevice::DeviceType::DEVICE_TYPE_OTHER; }
virtual String get_video_adapter_api_version() const override { return String(); }
+
+ virtual Size2i get_maximum_viewport_size() const override { return Size2i(); };
};
} // namespace RendererDummy
diff --git a/servers/rendering/renderer_rd/effects/copy_effects.cpp b/servers/rendering/renderer_rd/effects/copy_effects.cpp
index 53237c1dfb..a14228eb3d 100644
--- a/servers/rendering/renderer_rd/effects/copy_effects.cpp
+++ b/servers/rendering/renderer_rd/effects/copy_effects.cpp
@@ -357,8 +357,8 @@ void CopyEffects::copy_to_rect(RID p_source_rd_texture, RID p_dest_texture, cons
copy.push_constant.flags |= COPY_FLAG_ALPHA_TO_ONE;
}
- copy.push_constant.section[0] = 0;
- copy.push_constant.section[1] = 0;
+ copy.push_constant.section[0] = p_rect.position.x;
+ copy.push_constant.section[1] = p_rect.position.y;
copy.push_constant.section[2] = p_rect.size.width;
copy.push_constant.section[3] = p_rect.size.height;
copy.push_constant.target[0] = p_rect.position.x;
diff --git a/servers/rendering/renderer_rd/environment/gi.cpp b/servers/rendering/renderer_rd/environment/gi.cpp
index 9b6be0b422..550fe27e4c 100644
--- a/servers/rendering/renderer_rd/environment/gi.cpp
+++ b/servers/rendering/renderer_rd/environment/gi.cpp
@@ -2335,7 +2335,7 @@ void GI::SDFGI::render_region(Ref<RenderSceneBuffersRD> p_render_buffers, int p_
img.instantiate();
for (uint32_t i = 0; i < cascade_size; i++) {
Vector<uint8_t> subarr = data.slice(128 * 128 * i, 128 * 128 * (i + 1));
- img->create(cascade_size, cascade_size, false, Image::FORMAT_L8, subarr);
+ img->set_data(cascade_size, cascade_size, false, Image::FORMAT_L8, subarr);
img->save_png("res://cascade_sdf_" + itos(cascade) + "_" + itos(i) + ".png");
}
@@ -2866,7 +2866,8 @@ void GI::VoxelGIInstance::update(bool p_update_light_instances, const Vector<RID
{
Transform3D to_cell = gi->voxel_gi_get_to_cell_xform(probe);
- Transform3D to_probe_xform = (transform * to_cell.affine_inverse()).affine_inverse();
+ Transform3D to_probe_xform = to_cell * transform.affine_inverse();
+
//update lights
for (uint32_t i = 0; i < light_count; i++) {
diff --git a/servers/rendering/renderer_rd/environment/sky.cpp b/servers/rendering/renderer_rd/environment/sky.cpp
index 4ff2a66975..6940276040 100644
--- a/servers/rendering/renderer_rd/environment/sky.cpp
+++ b/servers/rendering/renderer_rd/environment/sky.cpp
@@ -772,9 +772,7 @@ Ref<Image> SkyRD::Sky::bake_panorama(float p_energy, int p_roughness_layers, con
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rad_tex, 0);
RD::get_singleton()->free(rad_tex);
- Ref<Image> img;
- img.instantiate();
- img->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
+ Ref<Image> img = Image::create_from_data(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
for (int i = 0; i < p_size.width; i++) {
for (int j = 0; j < p_size.height; j++) {
Color c = img->get_pixel(i, j);
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 84d2ad328c..ceed287184 100644
--- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
+++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
@@ -754,7 +754,7 @@ void RenderForwardClustered::_fill_instance_data(RenderListType p_render_list, i
bool cant_repeat = instance_data.flags & INSTANCE_DATA_FLAG_MULTIMESH || inst->mesh_instance.is_valid();
- if (prev_surface != nullptr && !cant_repeat && prev_surface->sort.sort_key1 == surface->sort.sort_key1 && prev_surface->sort.sort_key2 == surface->sort.sort_key2 && repeats < RenderElementInfo::MAX_REPEATS) {
+ if (prev_surface != nullptr && !cant_repeat && prev_surface->sort.sort_key1 == surface->sort.sort_key1 && prev_surface->sort.sort_key2 == surface->sort.sort_key2 && inst->mirror == prev_surface->owner->mirror && repeats < RenderElementInfo::MAX_REPEATS) {
//this element is the same as the previous one, count repeats to draw it using instancing
repeats++;
} else {
@@ -940,12 +940,13 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con
// LOD
if (p_render_data->scene_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
- //lod
- Vector3 lod_support_min = inst->transformed_aabb.get_support(-p_render_data->scene_data->lod_camera_plane.normal);
- Vector3 lod_support_max = inst->transformed_aabb.get_support(p_render_data->scene_data->lod_camera_plane.normal);
+ // Get the LOD support points on the mesh AABB.
+ Vector3 lod_support_min = inst->transformed_aabb.get_support(p_render_data->scene_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
+ Vector3 lod_support_max = inst->transformed_aabb.get_support(-p_render_data->scene_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
- float distance_min = p_render_data->scene_data->lod_camera_plane.distance_to(lod_support_min);
- float distance_max = p_render_data->scene_data->lod_camera_plane.distance_to(lod_support_max);
+ // Get the distances to those points on the AABB from the camera origin.
+ float distance_min = (float)p_render_data->scene_data->cam_transform.origin.distance_to(lod_support_min);
+ float distance_max = (float)p_render_data->scene_data->cam_transform.origin.distance_to(lod_support_max);
float distance = 0.0;
@@ -962,8 +963,8 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con
distance = 1.0;
}
- uint32_t indices;
- surf->sort.lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, &indices);
+ uint32_t indices = 0;
+ surf->sort.lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, indices);
if (p_render_data->render_info) {
indices = _indices_to_primitives(surf->primitive, indices);
if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
@@ -1830,7 +1831,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co
RID rp_uniform_set = _setup_render_pass_uniform_set(RENDER_LIST_OPAQUE, nullptr, RID());
bool finish_depth = using_ssao || using_sdfgi || using_voxelgi;
- RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, depth_pass_mode, 0, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, depth_pass_mode, 0, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
_render_list_with_threads(&render_list_params, depth_framebuffer, needs_pre_resolve ? RD::INITIAL_ACTION_CONTINUE : RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, needs_pre_resolve ? RD::INITIAL_ACTION_CONTINUE : RD::INITIAL_ACTION_CLEAR, finish_depth ? RD::FINAL_ACTION_READ : RD::FINAL_ACTION_CONTINUE, needs_pre_resolve ? Vector<Color>() : depth_pass_clear);
RD::get_singleton()->draw_command_end_label();
@@ -1900,7 +1901,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co
}
}
- RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, PASS_MODE_COLOR, color_pass_flags, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, PASS_MODE_COLOR, color_pass_flags, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
_render_list_with_threads(&render_list_params, color_framebuffer, keep_color ? RD::INITIAL_ACTION_KEEP : RD::INITIAL_ACTION_CLEAR, will_continue_color ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ, depth_pre_pass ? (continue_depth ? RD::INITIAL_ACTION_CONTINUE : RD::INITIAL_ACTION_KEEP) : RD::INITIAL_ACTION_CLEAR, will_continue_depth ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ, c, 1.0, 0);
if (will_continue_color && using_separate_specular) {
// close the specular framebuffer, as it's no longer used
@@ -2021,7 +2022,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co
{
uint32_t transparent_color_pass_flags = (color_pass_flags | COLOR_PASS_FLAG_TRANSPARENT) & ~(COLOR_PASS_FLAG_SEPARATE_SPECULAR);
RID alpha_framebuffer = rb_data.is_valid() ? rb_data->get_color_pass_fb(transparent_color_pass_flags) : color_only_framebuffer;
- RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), false, PASS_MODE_COLOR, transparent_color_pass_flags, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), false, PASS_MODE_COLOR, transparent_color_pass_flags, rb_data.is_null(), p_render_data->directional_light_soft_shadows, rp_uniform_set, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
_render_list_with_threads(&render_list_params, alpha_framebuffer, can_continue_color ? RD::INITIAL_ACTION_CONTINUE : RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, can_continue_depth ? RD::INITIAL_ACTION_CONTINUE : RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ);
}
@@ -2307,7 +2308,6 @@ void RenderForwardClustered::_render_shadow_append(RID p_framebuffer, const Page
scene_data.view_projection[0] = p_projection;
scene_data.z_far = p_zfar;
scene_data.z_near = 0.0;
- scene_data.lod_camera_plane = p_camera_plane;
scene_data.lod_distance_multiplier = p_lod_distance_multiplier;
scene_data.dual_paraboloid_side = p_use_dp_flip ? -1 : 1;
scene_data.opaque_prepass_threshold = 0.1f;
@@ -2378,7 +2378,7 @@ void RenderForwardClustered::_render_shadow_end(uint32_t p_barrier) {
for (uint32_t i = 0; i < scene_state.shadow_passes.size(); i++) {
SceneState::ShadowPass &shadow_pass = scene_state.shadow_passes[i];
- RenderListParameters render_list_parameters(render_list[RENDER_LIST_SECONDARY].elements.ptr() + shadow_pass.element_from, render_list[RENDER_LIST_SECONDARY].element_info.ptr() + shadow_pass.element_from, shadow_pass.element_count, shadow_pass.flip_cull, shadow_pass.pass_mode, 0, true, false, shadow_pass.rp_uniform_set, false, Vector2(), shadow_pass.camera_plane, shadow_pass.lod_distance_multiplier, shadow_pass.screen_mesh_lod_threshold, 1, shadow_pass.element_from, RD::BARRIER_MASK_NO_BARRIER);
+ RenderListParameters render_list_parameters(render_list[RENDER_LIST_SECONDARY].elements.ptr() + shadow_pass.element_from, render_list[RENDER_LIST_SECONDARY].element_info.ptr() + shadow_pass.element_from, shadow_pass.element_count, shadow_pass.flip_cull, shadow_pass.pass_mode, 0, true, false, shadow_pass.rp_uniform_set, false, Vector2(), shadow_pass.lod_distance_multiplier, shadow_pass.screen_mesh_lod_threshold, 1, shadow_pass.element_from, RD::BARRIER_MASK_NO_BARRIER);
_render_list_with_threads(&render_list_parameters, shadow_pass.framebuffer, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_DISCARD, shadow_pass.initial_depth_action, shadow_pass.final_depth_action, Vector<Color>(), 1.0, 0, shadow_pass.rect);
}
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 55f1ef01af..670eb93e20 100644
--- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h
+++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h
@@ -206,7 +206,6 @@ class RenderForwardClustered : public RendererSceneRenderRD {
RID render_pass_uniform_set;
bool force_wireframe = false;
Vector2 uv_offset;
- Plane lod_plane;
float lod_distance_multiplier = 0.0;
float screen_mesh_lod_threshold = 0.0;
RD::FramebufferFormatID framebuffer_format = 0;
@@ -214,7 +213,7 @@ class RenderForwardClustered : public RendererSceneRenderRD {
uint32_t barrier = RD::BARRIER_MASK_ALL;
bool use_directional_soft_shadow = false;
- RenderListParameters(GeometryInstanceSurfaceDataCache **p_elements, RenderElementInfo *p_element_info, int p_element_count, bool p_reverse_cull, PassMode p_pass_mode, uint32_t p_color_pass_flags, bool p_no_gi, bool p_use_directional_soft_shadows, RID p_render_pass_uniform_set, bool p_force_wireframe = false, const Vector2 &p_uv_offset = Vector2(), const Plane &p_lod_plane = Plane(), float p_lod_distance_multiplier = 0.0, float p_screen_mesh_lod_threshold = 0.0, uint32_t p_view_count = 1, uint32_t p_element_offset = 0, uint32_t p_barrier = RD::BARRIER_MASK_ALL) {
+ RenderListParameters(GeometryInstanceSurfaceDataCache **p_elements, RenderElementInfo *p_element_info, int p_element_count, bool p_reverse_cull, PassMode p_pass_mode, uint32_t p_color_pass_flags, bool p_no_gi, bool p_use_directional_soft_shadows, RID p_render_pass_uniform_set, bool p_force_wireframe = false, const Vector2 &p_uv_offset = Vector2(), float p_lod_distance_multiplier = 0.0, float p_screen_mesh_lod_threshold = 0.0, uint32_t p_view_count = 1, uint32_t p_element_offset = 0, uint32_t p_barrier = RD::BARRIER_MASK_ALL) {
elements = p_elements;
element_info = p_element_info;
element_count = p_element_count;
@@ -226,7 +225,6 @@ class RenderForwardClustered : public RendererSceneRenderRD {
render_pass_uniform_set = p_render_pass_uniform_set;
force_wireframe = p_force_wireframe;
uv_offset = p_uv_offset;
- lod_plane = p_lod_plane;
lod_distance_multiplier = p_lod_distance_multiplier;
screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
element_offset = p_element_offset;
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 2b2090f8ed..f76d016ae7 100644
--- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
+++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
@@ -916,7 +916,7 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color
}
RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
- RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, PASS_MODE_COLOR, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].element_info.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, PASS_MODE_COLOR, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
render_list_params.framebuffer_format = fb_format;
if ((uint32_t)render_list_params.element_count > render_list_thread_threshold && false) {
// secondary command buffers need more testing at this time
@@ -983,7 +983,7 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color
if (using_subpass_transparent) {
RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
- RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, PASS_MODE_COLOR_TRANSPARENT, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, PASS_MODE_COLOR_TRANSPARENT, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
render_list_params.framebuffer_format = fb_format;
if ((uint32_t)render_list_params.element_count > render_list_thread_threshold && false) {
// secondary command buffers need more testing at this time
@@ -1022,7 +1022,7 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color
// _setup_environment(p_render_data, p_render_data->reflection_probe.is_valid(), screen_size, !p_render_data->reflection_probe.is_valid(), p_default_bg_color, false);
RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
- RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, PASS_MODE_COLOR, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_camera_plane, p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
+ RenderListParameters render_list_params(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].element_info.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, PASS_MODE_COLOR, rp_uniform_set, spec_constant_base_flags, get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME, Vector2(), p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, p_render_data->scene_data->view_count);
render_list_params.framebuffer_format = fb_format;
if ((uint32_t)render_list_params.element_count > render_list_thread_threshold && false) {
// secondary command buffers need more testing at this time
@@ -1266,7 +1266,6 @@ void RenderForwardMobile::_render_shadow_append(RID p_framebuffer, const PagedAr
scene_data.view_projection[0] = p_projection;
scene_data.z_near = 0.0;
scene_data.z_far = p_zfar;
- scene_data.lod_camera_plane = p_camera_plane;
scene_data.lod_distance_multiplier = p_lod_distance_multiplier;
scene_data.dual_paraboloid_side = p_use_dp_flip ? -1 : 1;
scene_data.opaque_prepass_threshold = 0.1;
@@ -1335,7 +1334,7 @@ void RenderForwardMobile::_render_shadow_end(uint32_t p_barrier) {
for (uint32_t i = 0; i < scene_state.shadow_passes.size(); i++) {
SceneState::ShadowPass &shadow_pass = scene_state.shadow_passes[i];
- RenderListParameters render_list_parameters(render_list[RENDER_LIST_SECONDARY].elements.ptr() + shadow_pass.element_from, render_list[RENDER_LIST_SECONDARY].element_info.ptr() + shadow_pass.element_from, shadow_pass.element_count, shadow_pass.flip_cull, shadow_pass.pass_mode, shadow_pass.rp_uniform_set, 0, false, Vector2(), shadow_pass.camera_plane, shadow_pass.lod_distance_multiplier, shadow_pass.screen_mesh_lod_threshold, 1, shadow_pass.element_from, RD::BARRIER_MASK_NO_BARRIER);
+ RenderListParameters render_list_parameters(render_list[RENDER_LIST_SECONDARY].elements.ptr() + shadow_pass.element_from, render_list[RENDER_LIST_SECONDARY].element_info.ptr() + shadow_pass.element_from, shadow_pass.element_count, shadow_pass.flip_cull, shadow_pass.pass_mode, shadow_pass.rp_uniform_set, 0, false, Vector2(), shadow_pass.lod_distance_multiplier, shadow_pass.screen_mesh_lod_threshold, 1, shadow_pass.element_from, RD::BARRIER_MASK_NO_BARRIER);
_render_list_with_threads(&render_list_parameters, shadow_pass.framebuffer, RD::INITIAL_ACTION_DROP, RD::FINAL_ACTION_DISCARD, shadow_pass.initial_depth_action, shadow_pass.final_depth_action, Vector<Color>(), 1.0, 0, shadow_pass.rect);
}
@@ -1808,12 +1807,13 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const
// LOD
if (p_render_data->scene_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
- //lod
- Vector3 lod_support_min = inst->transformed_aabb.get_support(-p_render_data->scene_data->lod_camera_plane.normal);
- Vector3 lod_support_max = inst->transformed_aabb.get_support(p_render_data->scene_data->lod_camera_plane.normal);
+ // Get the LOD support points on the mesh AABB.
+ Vector3 lod_support_min = inst->transformed_aabb.get_support(p_render_data->scene_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
+ Vector3 lod_support_max = inst->transformed_aabb.get_support(-p_render_data->scene_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
- float distance_min = p_render_data->scene_data->lod_camera_plane.distance_to(lod_support_min);
- float distance_max = p_render_data->scene_data->lod_camera_plane.distance_to(lod_support_max);
+ // Get the distances to those points on the AABB from the camera origin.
+ float distance_min = (float)p_render_data->scene_data->cam_transform.origin.distance_to(lod_support_min);
+ float distance_max = (float)p_render_data->scene_data->cam_transform.origin.distance_to(lod_support_max);
float distance = 0.0;
@@ -1830,8 +1830,8 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const
distance = 1.0;
}
- uint32_t indices;
- surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, &indices);
+ uint32_t indices = 0;
+ surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->scene_data->lod_distance_multiplier, p_render_data->scene_data->screen_mesh_lod_threshold, indices);
if (p_render_data->render_info) {
indices = _indices_to_primitives(surf->primitive, indices);
if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
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 415bd79ad6..ce64d805b7 100644
--- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h
+++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h
@@ -163,7 +163,6 @@ private:
RID render_pass_uniform_set;
bool force_wireframe = false;
Vector2 uv_offset;
- Plane lod_plane;
uint32_t spec_constant_base_flags = 0;
float lod_distance_multiplier = 0.0;
float screen_mesh_lod_threshold = 0.0;
@@ -172,7 +171,7 @@ private:
uint32_t barrier = RD::BARRIER_MASK_ALL;
uint32_t subpass = 0;
- RenderListParameters(GeometryInstanceSurfaceDataCache **p_elements, RenderElementInfo *p_element_info, int p_element_count, bool p_reverse_cull, PassMode p_pass_mode, RID p_render_pass_uniform_set, uint32_t p_spec_constant_base_flags = 0, bool p_force_wireframe = false, const Vector2 &p_uv_offset = Vector2(), const Plane &p_lod_plane = Plane(), float p_lod_distance_multiplier = 0.0, float p_screen_mesh_lod_threshold = 0.0, uint32_t p_view_count = 1, uint32_t p_element_offset = 0, uint32_t p_barrier = RD::BARRIER_MASK_ALL) {
+ RenderListParameters(GeometryInstanceSurfaceDataCache **p_elements, RenderElementInfo *p_element_info, int p_element_count, bool p_reverse_cull, PassMode p_pass_mode, RID p_render_pass_uniform_set, uint32_t p_spec_constant_base_flags = 0, bool p_force_wireframe = false, const Vector2 &p_uv_offset = Vector2(), float p_lod_distance_multiplier = 0.0, float p_screen_mesh_lod_threshold = 0.0, uint32_t p_view_count = 1, uint32_t p_element_offset = 0, uint32_t p_barrier = RD::BARRIER_MASK_ALL) {
elements = p_elements;
element_info = p_element_info;
element_count = p_element_count;
@@ -183,7 +182,6 @@ private:
render_pass_uniform_set = p_render_pass_uniform_set;
force_wireframe = p_force_wireframe;
uv_offset = p_uv_offset;
- lod_plane = p_lod_plane;
lod_distance_multiplier = p_lod_distance_multiplier;
screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
element_offset = p_element_offset;
diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp
index 9151c53823..7a2336970b 100644
--- a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp
+++ b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "pipeline_cache_rd.h"
+
#include "core/os/memory.h"
RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD::FramebufferFormatID p_framebuffer_format_id, bool p_wireframe, uint32_t p_render_pass, uint32_t p_bool_specializations) {
@@ -70,9 +71,7 @@ RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD
}
void PipelineCacheRD::_clear() {
-#ifndef _MSC_VER
-#warning Clear should probably recompile all the variants already compiled instead to avoid stalls? needs discussion
-#endif
+ // TODO: Clear should probably recompile all the variants already compiled instead to avoid stalls? Needs discussion.
if (versions) {
for (uint32_t i = 0; i < version_count; i++) {
//shader may be gone, so this may not be valid
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
index e5e82552f4..dc0214e307 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
@@ -1075,10 +1075,7 @@ void RendererCanvasRenderRD::_render_items(RID p_to_render_target, int p_item_co
clear_colors.push_back(texture_storage->render_target_get_clear_request_color(p_to_render_target));
texture_storage->render_target_disable_clear_request(p_to_render_target);
}
-#ifndef _MSC_VER
-#warning TODO obtain from framebuffer format eventually when this is implemented
-#endif
-
+ // TODO: Obtain from framebuffer format eventually when this is implemented.
fb_uniform_set = texture_storage->render_target_get_framebuffer_uniform_set(p_to_render_target);
}
@@ -1114,8 +1111,20 @@ void RendererCanvasRenderRD::_render_items(RID p_to_render_target, int p_item_co
RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
- if (material.is_null() && ci->canvas_group != nullptr) {
- material = default_canvas_group_material;
+ if (ci->canvas_group != nullptr) {
+ if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
+ if (!p_to_backbuffer) {
+ material = default_clip_children_material;
+ }
+ } else {
+ if (material.is_null()) {
+ if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {
+ material = default_clip_children_material;
+ } else {
+ material = default_canvas_group_material;
+ }
+ }
+ }
}
if (material != prev_material) {
@@ -1440,10 +1449,12 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list);
item_count = 0;
- Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
-
- if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_OPAQUE) {
+ if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {
+ Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
+ if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
+ items[item_count++] = ci->canvas_group_owner;
+ }
} else if (!backbuffer_cleared) {
texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));
backbuffer_cleared = true;
@@ -1623,7 +1634,7 @@ void RendererCanvasRenderRD::light_update_shadow(RID p_rid, int p_shadow_index,
projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
}
- Vector3 cam_target = Basis(Vector3(0, 0, Math_TAU * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
+ Vector3 cam_target = Basis::from_euler(Vector3(0, 0, Math_TAU * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
projection = projection * Projection(Transform3D().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
ShadowRenderPushConstant push_constant;
@@ -2741,6 +2752,26 @@ void fragment() {
material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
}
+ {
+ default_clip_children_shader = material_storage->shader_allocate();
+ material_storage->shader_initialize(default_clip_children_shader);
+
+ material_storage->shader_set_code(default_clip_children_shader, R"(
+// Default clip children shader.
+
+shader_type canvas_item;
+
+void fragment() {
+ vec4 c = textureLod(SCREEN_TEXTURE, SCREEN_UV, 0.0);
+ COLOR.rgb = c.rgb;
+}
+)");
+ default_clip_children_material = material_storage->material_allocate();
+ material_storage->material_initialize(default_clip_children_material);
+
+ material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);
+ }
+
static_assert(sizeof(PushConstant) == 128);
}
@@ -2792,6 +2823,9 @@ RendererCanvasRenderRD::~RendererCanvasRenderRD() {
material_storage->material_free(default_canvas_group_material);
material_storage->shader_free(default_canvas_group_shader);
+ material_storage->material_free(default_clip_children_material);
+ material_storage->shader_free(default_clip_children_shader);
+
{
if (state.canvas_state_buffer.is_valid()) {
RD::get_singleton()->free(state.canvas_state_buffer);
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
index 67db56d913..4f1f77af5e 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h
@@ -421,6 +421,8 @@ class RendererCanvasRenderRD : public RendererCanvasRender {
RID default_canvas_group_shader;
RID default_canvas_group_material;
+ RID default_clip_children_material;
+ RID default_clip_children_shader;
RS::CanvasItemTextureFilter default_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;
RS::CanvasItemTextureRepeat default_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;
diff --git a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp
index dd3f62e509..3289bfb0ea 100644
--- a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp
@@ -102,10 +102,8 @@ void RendererCompositorRD::begin_frame(double frame_step) {
}
void RendererCompositorRD::end_frame(bool p_swap_buffers) {
-#ifndef _MSC_VER
-#warning TODO: likely pass a bool to swap buffers to avoid display?
-#endif
- RD::get_singleton()->swap_buffers(); //probably should pass some bool to avoid display?
+ // TODO: Likely pass a bool to swap buffers to avoid display?
+ RD::get_singleton()->swap_buffers();
}
void RendererCompositorRD::initialize() {
diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
index 061263ef76..75fe84f46b 100644
--- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp
@@ -250,9 +250,7 @@ Ref<Image> RendererSceneRenderRD::environment_bake_panorama(RID p_env, bool p_ba
panorama_color = ambient_color.lerp(panorama_color, ambient_color_sky_mix);
}
- Ref<Image> panorama;
- panorama.instantiate();
- panorama->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
+ Ref<Image> panorama = Image::create_empty(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
panorama->fill(panorama_color);
return panorama;
}
@@ -1101,7 +1099,6 @@ void RendererSceneRenderRD::render_scene(const Ref<RenderSceneBuffers> &p_render
// this should be the same for all cameras..
scene_data.lod_distance_multiplier = p_camera_data->main_projection.get_lod_multiplier();
- scene_data.lod_camera_plane = Plane(-p_camera_data->main_transform.basis.get_column(Vector3::AXIS_Z), p_camera_data->main_transform.get_origin());
if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
scene_data.screen_mesh_lod_threshold = 0.0;
@@ -1306,36 +1303,28 @@ TypedArray<Image> RendererSceneRenderRD::bake_render_uv2(RID p_base, const Typed
{
PackedByteArray data = RD::get_singleton()->texture_get_data(albedo_alpha_tex, 0);
- Ref<Image> img;
- img.instantiate();
- img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
+ Ref<Image> img = Image::create_from_data(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(albedo_alpha_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(normal_tex, 0);
- Ref<Image> img;
- img.instantiate();
- img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
+ Ref<Image> img = Image::create_from_data(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(normal_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(orm_tex, 0);
- Ref<Image> img;
- img.instantiate();
- img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
+ Ref<Image> img = Image::create_from_data(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
RD::get_singleton()->free(orm_tex);
ret.push_back(img);
}
{
PackedByteArray data = RD::get_singleton()->texture_get_data(emission_tex, 0);
- Ref<Image> img;
- img.instantiate();
- img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBAH, data);
+ Ref<Image> img = Image::create_from_data(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBAH, data);
RD::get_singleton()->free(emission_tex);
ret.push_back(img);
}
diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp
index 0f2dea6fe9..5e9eadadd9 100644
--- a/servers/rendering/renderer_rd/shader_rd.cpp
+++ b/servers/rendering/renderer_rd/shader_rd.cpp
@@ -180,6 +180,7 @@ void ShaderRD::_build_variant_code(StringBuilder &builder, uint32_t p_variant, c
#if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
builder.append("#define MOLTENVK_USED\n");
#endif
+ builder.append(String("#define RENDER_DRIVER_") + OS::get_singleton()->get_current_rendering_driver_name().to_upper() + "\n");
} break;
case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {
builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)
diff --git a/servers/rendering/renderer_rd/shaders/canvas.glsl b/servers/rendering/renderer_rd/shaders/canvas.glsl
index 45dc63aa17..8593e6b265 100644
--- a/servers/rendering/renderer_rd/shaders/canvas.glsl
+++ b/servers/rendering/renderer_rd/shaders/canvas.glsl
@@ -598,13 +598,11 @@ void main() {
normal = normalize((canvas_data.canvas_normal_transform * vec4(normal, 0.0)).xyz);
}
- vec3 base_color = color.rgb;
+ vec4 base_color = color;
if (bool(draw_data.flags & FLAGS_USING_LIGHT_MASK)) {
color = vec4(0.0); //invisible by default due to using light mask
}
- vec4 original_color = color;
-
#ifdef MODE_LIGHT_ONLY
color = vec4(0.0);
#elif !defined(MODE_UNSHADED)
@@ -624,12 +622,14 @@ void main() {
#ifdef LIGHT_CODE_USED
vec4 shadow_modulate = vec4(1.0);
- light_color = light_compute(light_vertex, vec3(direction, light_array.data[light_base].height), normal, light_color, light_color.a, specular_shininess, shadow_modulate, screen_uv, uv, color, true);
+ light_color = light_compute(light_vertex, vec3(direction, light_array.data[light_base].height), normal, light_color, light_color.a, specular_shininess, shadow_modulate, screen_uv, uv, base_color, true);
#else
if (normal_used) {
vec3 light_vec = normalize(mix(vec3(direction, 0.0), vec3(0, 0, 1), light_array.data[light_base].height));
- light_color.rgb = light_normal_compute(light_vec, normal, base_color, light_color.rgb, specular_shininess, specular_shininess_used);
+ light_color.rgb = light_normal_compute(light_vec, normal, base_color.rgb, light_color.rgb, specular_shininess, specular_shininess_used);
+ } else {
+ light_color.rgb *= base_color.rgb;
}
#endif
@@ -646,8 +646,6 @@ void main() {
);
}
- light_color.rgb *= original_color.rgb;
-
light_blend_compute(light_base, light_color, color.rgb);
}
@@ -657,20 +655,7 @@ void main() {
if (i >= light_count) {
break;
}
- uint light_base;
- if (i < 8) {
- if (i < 4) {
- light_base = draw_data.lights[0];
- } else {
- light_base = draw_data.lights[1];
- }
- } else {
- if (i < 12) {
- light_base = draw_data.lights[2];
- } else {
- light_base = draw_data.lights[3];
- }
- }
+ uint light_base = draw_data.lights[i >> 2];
light_base >>= (i & 3) * 8;
light_base &= 0xFF;
@@ -685,7 +670,7 @@ void main() {
vec3 light_position = vec3(light_array.data[light_base].position, light_array.data[light_base].height);
light_color.rgb *= light_base_color.rgb;
- light_color = light_compute(light_vertex, light_position, normal, light_color, light_base_color.a, specular_shininess, shadow_modulate, screen_uv, uv, color, false);
+ light_color = light_compute(light_vertex, light_position, normal, light_color, light_base_color.a, specular_shininess, shadow_modulate, screen_uv, uv, base_color, false);
#else
light_color.rgb *= light_base_color.rgb * light_base_color.a;
@@ -695,7 +680,9 @@ void main() {
vec3 pos = light_vertex;
vec3 light_vec = normalize(light_pos - pos);
- light_color.rgb = light_normal_compute(light_vec, normal, base_color, light_color.rgb, specular_shininess, specular_shininess_used);
+ light_color.rgb = light_normal_compute(light_vec, normal, base_color.rgb, light_color.rgb, specular_shininess, specular_shininess_used);
+ } else {
+ light_color.rgb *= base_color.rgb;
}
#endif
if (any(lessThan(tex_uv, vec2(0.0, 0.0))) || any(greaterThanEqual(tex_uv, vec2(1.0, 1.0)))) {
@@ -743,8 +730,6 @@ void main() {
);
}
- light_color.rgb *= original_color.rgb;
-
light_blend_compute(light_base, light_color, color.rgb);
}
#endif
diff --git a/servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl b/servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl
index eed9038502..28507e6c12 100644
--- a/servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl
+++ b/servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl
@@ -381,7 +381,7 @@ void main() {
float cell_depth_size = abs(view_pos.z - get_depth_at_pos(fog_cell_size.z, pos.z + 1));
//compute directional lights
- if (total_density > 0.001) {
+ if (total_density > 0.00005) {
for (uint i = 0; i < params.directional_light_count; i++) {
if (directional_lights.data[i].volumetric_fog_energy > 0.001) {
vec3 shadow_attenuation = vec3(1.0);
diff --git a/servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl b/servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl
index 1a8a1f3aa3..293532bf2d 100644
--- a/servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl
+++ b/servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl
@@ -1447,18 +1447,24 @@ void fragment_shader(in SceneData scene_data) {
}
//finalize ambient light here
- ambient_light *= albedo.rgb;
- ambient_light *= ao;
+ {
+#if defined(AMBIENT_LIGHT_DISABLED)
+ ambient_light = vec3(0.0, 0.0, 0.0);
+#else
+ ambient_light *= albedo.rgb;
+ ambient_light *= ao;
+
+ if (bool(implementation_data.ss_effects_flags & SCREEN_SPACE_EFFECTS_FLAGS_USE_SSIL)) {
+ vec4 ssil = textureLod(sampler2D(ssil_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), screen_uv, 0.0);
+ ambient_light *= 1.0 - ssil.a;
+ ambient_light += ssil.rgb * albedo.rgb;
+ }
+#endif // AMBIENT_LIGHT_DISABLED
+ }
// convert ao to direct light ao
ao = mix(1.0, ao, ao_light_affect);
- if (bool(implementation_data.ss_effects_flags & SCREEN_SPACE_EFFECTS_FLAGS_USE_SSIL)) {
- vec4 ssil = textureLod(sampler2D(ssil_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), screen_uv, 0.0);
- ambient_light *= 1.0 - ssil.a;
- ambient_light += ssil.rgb * albedo.rgb;
- }
-
//this saves some VGPRs
vec3 f0 = F0(metallic, specular, albedo);
diff --git a/servers/rendering/renderer_rd/shaders/forward_mobile/scene_forward_mobile.glsl b/servers/rendering/renderer_rd/shaders/forward_mobile/scene_forward_mobile.glsl
index 33fd4c35b1..9aeaa6d978 100644
--- a/servers/rendering/renderer_rd/shaders/forward_mobile/scene_forward_mobile.glsl
+++ b/servers/rendering/renderer_rd/shaders/forward_mobile/scene_forward_mobile.glsl
@@ -1172,8 +1172,14 @@ void main() {
} //Reflection probes
// finalize ambient light here
- ambient_light *= albedo.rgb;
- ambient_light *= ao;
+ {
+#if defined(AMBIENT_LIGHT_DISABLED)
+ ambient_light = vec3(0.0, 0.0, 0.0);
+#else
+ ambient_light *= albedo.rgb;
+ ambient_light *= ao;
+#endif // AMBIENT_LIGHT_DISABLED
+ }
// convert ao to direct light ao
ao = mix(1.0, ao, ao_light_affect);
diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
index 968973bbe7..d8ef4baa41 100644
--- a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp
@@ -903,7 +903,9 @@ _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type,
case ShaderLanguage::TYPE_BVEC3:
case ShaderLanguage::TYPE_IVEC3:
case ShaderLanguage::TYPE_UVEC3:
- case ShaderLanguage::TYPE_VEC3:
+ case ShaderLanguage::TYPE_VEC3: {
+ memset(data, 0, 12 * p_array_size);
+ } break;
case ShaderLanguage::TYPE_BVEC4:
case ShaderLanguage::TYPE_IVEC4:
case ShaderLanguage::TYPE_UVEC4:
diff --git a/servers/rendering/renderer_rd/storage_rd/mesh_storage.h b/servers/rendering/renderer_rd/storage_rd/mesh_storage.h
index c8a33bd4d7..6a7400631d 100644
--- a/servers/rendering/renderer_rd/storage_rd/mesh_storage.h
+++ b/servers/rendering/renderer_rd/storage_rd/mesh_storage.h
@@ -398,13 +398,11 @@ public:
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 {
+ _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) 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;
- }
+ 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) {
@@ -415,9 +413,7 @@ public:
if (current_lod == -1) {
return 0;
} else {
- if (r_index_count) {
- *r_index_count = s->lods[current_lod].index_count;
- }
+ r_index_count = s->lods[current_lod].index_count;
return current_lod + 1;
}
}
diff --git a/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp b/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
index 78f4c410c3..240f743387 100644
--- a/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/particles_storage.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "particles_storage.h"
+
#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
#include "servers/rendering/rendering_server_globals.h"
#include "texture_storage.h"
@@ -1334,10 +1335,7 @@ void ParticlesStorage::update_particles() {
}
}
-#ifndef _MSC_VER
-#warning Should use display refresh rate for all this
-#endif
-
+ // TODO: Should use display refresh rate for all this.
float screen_hz = 60;
int fixed_fps = 0;
diff --git a/servers/rendering/renderer_rd/storage_rd/render_scene_data_rd.h b/servers/rendering/renderer_rd/storage_rd/render_scene_data_rd.h
index c2dc7d5f4c..9c031acc1e 100644
--- a/servers/rendering/renderer_rd/storage_rd/render_scene_data_rd.h
+++ b/servers/rendering/renderer_rd/storage_rd/render_scene_data_rd.h
@@ -61,7 +61,6 @@ public:
float z_far = 0.0;
float lod_distance_multiplier = 0.0;
- Plane lod_camera_plane;
float screen_mesh_lod_threshold = 0.0;
uint32_t directional_light_count = 0;
diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
index b3a7e05ff5..bc70c57b69 100644
--- a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "texture_storage.h"
+
#include "../effects/copy_effects.h"
#include "../framebuffer_cache_rd.h"
#include "material_storage.h"
@@ -1123,9 +1124,7 @@ 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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
texture_2d_initialize(p_texture, image);
@@ -1134,9 +1133,7 @@ void TextureStorage::texture_2d_placeholder_initialize(RID p_texture) {
void TextureStorage::texture_2d_layered_placeholder_initialize(RID p_texture, RS::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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
Vector<Ref<Image>> images;
@@ -1155,9 +1152,7 @@ void TextureStorage::texture_2d_layered_placeholder_initialize(RID p_texture, RS
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);
+ Ref<Image> image = Image::create_empty(4, 4, false, Image::FORMAT_RGBA8);
image->fill(Color(1, 0, 1, 1));
Vector<Ref<Image>> images;
@@ -1180,9 +1175,7 @@ Ref<Image> TextureStorage::texture_2d_get(RID p_texture) const {
#endif
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(tex->rd_texture, 0);
ERR_FAIL_COND_V(data.size() == 0, Ref<Image>());
- Ref<Image> image;
- image.instantiate();
- image->create(tex->width, tex->height, tex->mipmaps > 1, tex->validated_format, data);
+ Ref<Image> image = Image::create_from_data(tex->width, tex->height, tex->mipmaps > 1, tex->validated_format, data);
ERR_FAIL_COND_V(image->is_empty(), Ref<Image>());
if (tex->format != tex->validated_format) {
image->convert(tex->format);
@@ -1203,9 +1196,7 @@ Ref<Image> TextureStorage::texture_2d_layer_get(RID p_texture, int p_layer) cons
Vector<uint8_t> data = RD::get_singleton()->texture_get_data(tex->rd_texture, p_layer);
ERR_FAIL_COND_V(data.size() == 0, Ref<Image>());
- Ref<Image> image;
- image.instantiate();
- image->create(tex->width, tex->height, tex->mipmaps > 1, tex->validated_format, data);
+ Ref<Image> image = Image::create_from_data(tex->width, tex->height, tex->mipmaps > 1, tex->validated_format, data);
ERR_FAIL_COND_V(image->is_empty(), Ref<Image>());
if (tex->format != tex->validated_format) {
image->convert(tex->format);
@@ -1231,9 +1222,7 @@ Vector<Ref<Image>> TextureStorage::texture_3d_get(RID p_texture) const {
ERR_FAIL_COND_V(bs.offset + bs.buffer_size > (uint32_t)all_data.size(), Vector<Ref<Image>>());
Vector<uint8_t> sub_region = all_data.slice(bs.offset, bs.offset + bs.buffer_size);
- Ref<Image> img;
- img.instantiate();
- img->create(bs.size.width, bs.size.height, false, tex->validated_format, sub_region);
+ Ref<Image> img = Image::create_from_data(bs.size.width, bs.size.height, false, tex->validated_format, sub_region);
ERR_FAIL_COND_V(img->is_empty(), Vector<Ref<Image>>());
if (tex->format != tex->validated_format) {
img->convert(tex->format);
@@ -1496,9 +1485,7 @@ Ref<Image> TextureStorage::_validate_texture_format(const Ref<Image> &p_image, T
} break;
case Image::FORMAT_RGBE9995: {
r_format.format = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
-#ifndef _MSC_VER
-#warning TODO need to make a function in Image to swap bits for this
-#endif
+ // TODO: Need to make a function in Image to swap bits for this.
r_format.swizzle_r = RD::TEXTURE_SWIZZLE_IDENTITY;
r_format.swizzle_g = RD::TEXTURE_SWIZZLE_IDENTITY;
r_format.swizzle_b = RD::TEXTURE_SWIZZLE_IDENTITY;
@@ -2462,6 +2449,7 @@ void TextureStorage::_update_render_target(RenderTarget *rt) {
RD::TEXTURE_SAMPLES_8,
};
rd_color_multisample_format.samples = texture_samples[rt->msaa];
+ rd_color_multisample_format.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
RD::TextureView rd_view_multisample;
rd_color_multisample_format.is_resolve_buffer = false;
rt->color_multisample = RD::get_singleton()->texture_create(rd_color_multisample_format, rd_view_multisample);
diff --git a/servers/rendering/renderer_rd/storage_rd/utilities.cpp b/servers/rendering/renderer_rd/storage_rd/utilities.cpp
index e517186955..4048c46d28 100644
--- a/servers/rendering/renderer_rd/storage_rd/utilities.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/utilities.cpp
@@ -321,3 +321,11 @@ RenderingDevice::DeviceType Utilities::get_video_adapter_type() const {
String Utilities::get_video_adapter_api_version() const {
return RenderingDevice::get_singleton()->get_device_api_version();
}
+
+Size2i Utilities::get_maximum_viewport_size() const {
+ RenderingDevice *device = RenderingDevice::get_singleton();
+
+ int max_x = device->limit_get(RenderingDevice::LIMIT_MAX_VIEWPORT_DIMENSIONS_X);
+ int max_y = device->limit_get(RenderingDevice::LIMIT_MAX_VIEWPORT_DIMENSIONS_Y);
+ return Size2i(max_x, max_y);
+}
diff --git a/servers/rendering/renderer_rd/storage_rd/utilities.h b/servers/rendering/renderer_rd/storage_rd/utilities.h
index a80eb8510e..dda656c380 100644
--- a/servers/rendering/renderer_rd/storage_rd/utilities.h
+++ b/servers/rendering/renderer_rd/storage_rd/utilities.h
@@ -115,6 +115,8 @@ public:
virtual String get_video_adapter_vendor() const override;
virtual RenderingDevice::DeviceType get_video_adapter_type() const override;
virtual String get_video_adapter_api_version() const override;
+
+ virtual Size2i get_maximum_viewport_size() const override;
};
} // namespace RendererRD
diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp
index 41819268bd..348f6e4695 100644
--- a/servers/rendering/renderer_scene_cull.cpp
+++ b/servers/rendering/renderer_scene_cull.cpp
@@ -869,12 +869,7 @@ void RendererSceneCull::instance_set_transform(RID p_instance, const Transform3D
for (int i = 0; i < 4; i++) {
const Vector3 &v = i < 3 ? p_transform.basis.rows[i] : p_transform.origin;
- ERR_FAIL_COND(Math::is_inf(v.x));
- ERR_FAIL_COND(Math::is_nan(v.x));
- ERR_FAIL_COND(Math::is_inf(v.y));
- ERR_FAIL_COND(Math::is_nan(v.y));
- ERR_FAIL_COND(Math::is_inf(v.z));
- ERR_FAIL_COND(Math::is_nan(v.z));
+ ERR_FAIL_COND(!v.is_finite());
}
#endif
diff --git a/servers/rendering/renderer_scene_occlusion_cull.cpp b/servers/rendering/renderer_scene_occlusion_cull.cpp
index bda0950097..e1ca5a7103 100644
--- a/servers/rendering/renderer_scene_occlusion_cull.cpp
+++ b/servers/rendering/renderer_scene_occlusion_cull.cpp
@@ -180,7 +180,7 @@ RID RendererSceneOcclusionCull::HZBuffer::get_debug_texture() {
ptrw[i] = MIN(mips[0][i] / debug_tex_range, 1.0) * 255;
}
- debug_image->create(sizes[0].x, sizes[0].y, false, Image::FORMAT_L8, debug_data);
+ debug_image->set_data(sizes[0].x, sizes[0].y, false, Image::FORMAT_L8, debug_data);
if (debug_texture.is_null()) {
debug_texture = RS::get_singleton()->texture_2d_create(debug_image);
diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp
index dd190437a3..93118f39e7 100644
--- a/servers/rendering/rendering_device.cpp
+++ b/servers/rendering/rendering_device.cpp
@@ -974,6 +974,8 @@ void RenderingDevice::_bind_methods() {
BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X);
BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y);
BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z);
+ BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_X);
+ BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_Y);
BIND_ENUM_CONSTANT(MEMORY_TEXTURES);
BIND_ENUM_CONSTANT(MEMORY_BUFFERS);
diff --git a/servers/rendering/rendering_device.h b/servers/rendering/rendering_device.h
index 29e5c9cd77..d0b85d8220 100644
--- a/servers/rendering/rendering_device.h
+++ b/servers/rendering/rendering_device.h
@@ -958,7 +958,7 @@ public:
bool wireframe;
PolygonCullMode cull_mode;
PolygonFrontFace front_face;
- bool depth_bias_enable;
+ bool depth_bias_enabled;
float depth_bias_constant_factor;
float depth_bias_clamp;
float depth_bias_slope_factor;
@@ -970,7 +970,7 @@ public:
wireframe = false;
cull_mode = POLYGON_CULL_DISABLED;
front_face = POLYGON_FRONT_FACE_CLOCKWISE;
- depth_bias_enable = false;
+ depth_bias_enabled = false;
depth_bias_constant_factor = 0;
depth_bias_clamp = 0;
depth_bias_slope_factor = 0;
@@ -1252,6 +1252,8 @@ public:
LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X,
LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y,
LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z,
+ LIMIT_MAX_VIEWPORT_DIMENSIONS_X,
+ LIMIT_MAX_VIEWPORT_DIMENSIONS_Y,
LIMIT_SUBGROUP_SIZE,
LIMIT_SUBGROUP_IN_SHADERS, // Set flags using SHADER_STAGE_VERTEX_BIT, SHADER_STAGE_FRAGMENT_BIT, etc.
LIMIT_SUBGROUP_OPERATIONS,
diff --git a/servers/rendering/rendering_device_binds.h b/servers/rendering/rendering_device_binds.h
index d95b46933c..c710bd0a10 100644
--- a/servers/rendering/rendering_device_binds.h
+++ b/servers/rendering/rendering_device_binds.h
@@ -517,7 +517,7 @@ public:
RD_SETGET(bool, wireframe)
RD_SETGET(RD::PolygonCullMode, cull_mode)
RD_SETGET(RD::PolygonFrontFace, front_face)
- RD_SETGET(bool, depth_bias_enable)
+ RD_SETGET(bool, depth_bias_enabled)
RD_SETGET(float, depth_bias_constant_factor)
RD_SETGET(float, depth_bias_clamp)
RD_SETGET(float, depth_bias_slope_factor)
@@ -531,7 +531,7 @@ protected:
RD_BIND(Variant::BOOL, RDPipelineRasterizationState, wireframe);
RD_BIND(Variant::INT, RDPipelineRasterizationState, cull_mode);
RD_BIND(Variant::INT, RDPipelineRasterizationState, front_face);
- RD_BIND(Variant::BOOL, RDPipelineRasterizationState, depth_bias_enable);
+ RD_BIND(Variant::BOOL, RDPipelineRasterizationState, depth_bias_enabled);
RD_BIND(Variant::FLOAT, RDPipelineRasterizationState, depth_bias_constant_factor);
RD_BIND(Variant::FLOAT, RDPipelineRasterizationState, depth_bias_clamp);
RD_BIND(Variant::FLOAT, RDPipelineRasterizationState, depth_bias_slope_factor);
diff --git a/servers/rendering/rendering_server_default.cpp b/servers/rendering/rendering_server_default.cpp
index 9103b0cf56..c0cd564308 100644
--- a/servers/rendering/rendering_server_default.cpp
+++ b/servers/rendering/rendering_server_default.cpp
@@ -331,6 +331,14 @@ bool RenderingServerDefault::is_low_end() const {
return RendererCompositor::is_low_end();
}
+Size2i RenderingServerDefault::get_maximum_viewport_size() const {
+ if (RSG::utilities) {
+ return RSG::utilities->get_maximum_viewport_size();
+ } else {
+ return Size2i();
+ }
+}
+
void RenderingServerDefault::_thread_exit() {
exit.set();
}
diff --git a/servers/rendering/rendering_server_default.h b/servers/rendering/rendering_server_default.h
index fe212151e3..a68c7ddf2c 100644
--- a/servers/rendering/rendering_server_default.h
+++ b/servers/rendering/rendering_server_default.h
@@ -994,6 +994,8 @@ public:
virtual void set_print_gpu_profile(bool p_enable) override;
+ virtual Size2i get_maximum_viewport_size() const override;
+
RenderingServerDefault(bool p_create_thread = false);
~RenderingServerDefault();
};
diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp
index a92292209f..4d27c400f0 100644
--- a/servers/rendering/shader_language.cpp
+++ b/servers/rendering/shader_language.cpp
@@ -8635,12 +8635,15 @@ Error ShaderLanguage::_parse_shader(const HashMap<StringName, FunctionInfo> &p_f
} break;
case TK_HINT_SCREEN_TEXTURE: {
new_hint = ShaderNode::Uniform::HINT_SCREEN_TEXTURE;
+ --texture_uniforms;
} break;
case TK_HINT_NORMAL_ROUGHNESS_TEXTURE: {
new_hint = ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE;
+ --texture_uniforms;
} break;
case TK_HINT_DEPTH_TEXTURE: {
new_hint = ShaderNode::Uniform::HINT_DEPTH_TEXTURE;
+ --texture_uniforms;
} break;
case TK_FILTER_NEAREST: {
new_filter = FILTER_NEAREST;
diff --git a/servers/rendering/storage/utilities.h b/servers/rendering/storage/utilities.h
index d240d58917..23a782c14a 100644
--- a/servers/rendering/storage/utilities.h
+++ b/servers/rendering/storage/utilities.h
@@ -181,6 +181,8 @@ public:
virtual String get_video_adapter_vendor() const = 0;
virtual RenderingDevice::DeviceType get_video_adapter_type() const = 0;
virtual String get_video_adapter_api_version() const = 0;
+
+ virtual Size2i get_maximum_viewport_size() const = 0;
};
#endif // RENDERER_UTILITIES_H
diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp
index 627cd9f062..e1a3fe46be 100644
--- a/servers/rendering_server.cpp
+++ b/servers/rendering_server.cpp
@@ -2636,7 +2636,8 @@ void RenderingServer::_bind_methods() {
BIND_ENUM_CONSTANT(CANVAS_ITEM_TEXTURE_REPEAT_MAX);
BIND_ENUM_CONSTANT(CANVAS_GROUP_MODE_DISABLED);
- BIND_ENUM_CONSTANT(CANVAS_GROUP_MODE_OPAQUE);
+ BIND_ENUM_CONSTANT(CANVAS_GROUP_MODE_CLIP_ONLY);
+ BIND_ENUM_CONSTANT(CANVAS_GROUP_MODE_CLIP_AND_DRAW);
BIND_ENUM_CONSTANT(CANVAS_GROUP_MODE_TRANSPARENT);
/* CANVAS LIGHT */
@@ -2791,10 +2792,10 @@ void RenderingServer::mesh_add_surface_from_mesh_data(RID p_mesh, const Geometry
Vector<Vector3> vertices;
Vector<Vector3> normals;
- for (int i = 0; i < p_mesh_data.faces.size(); i++) {
+ for (uint32_t i = 0; i < p_mesh_data.faces.size(); i++) {
const Geometry3D::MeshData::Face &f = p_mesh_data.faces[i];
- for (int j = 2; j < f.indices.size(); j++) {
+ for (uint32_t j = 2; j < f.indices.size(); j++) {
vertices.push_back(p_mesh_data.vertices[f.indices[0]]);
normals.push_back(f.plane.normal);
@@ -2868,12 +2869,13 @@ void RenderingServer::init() {
GLOBAL_DEF("rendering/2d/shadow_atlas/size", 2048);
- // Already defined in RenderingDeviceVulkan::initialize which runs before this code.
+ // Already defined in some RenderingDevice*::initialize, which run before this code.
// We re-define them here just for doctool's sake. Make sure to keep default values in sync.
GLOBAL_DEF("rendering/rendering_device/staging_buffer/block_size_kb", 256);
GLOBAL_DEF("rendering/rendering_device/staging_buffer/max_size_mb", 128);
GLOBAL_DEF("rendering/rendering_device/staging_buffer/texture_upload_region_size_px", 64);
- GLOBAL_DEF("rendering/rendering_device/descriptor_pools/max_descriptors_per_pool", 64);
+ // Vulkan-specific.
+ GLOBAL_DEF("rendering/rendering_device/vulkan/max_descriptors_per_pool", 64);
// Number of commands that can be drawn per frame.
GLOBAL_DEF_RST("rendering/gl_compatibility/item_buffer_size", 16384);
diff --git a/servers/rendering_server.h b/servers/rendering_server.h
index 6885d80301..36779690de 100644
--- a/servers/rendering_server.h
+++ b/servers/rendering_server.h
@@ -1367,7 +1367,8 @@ public:
enum CanvasGroupMode {
CANVAS_GROUP_MODE_DISABLED,
- CANVAS_GROUP_MODE_OPAQUE,
+ CANVAS_GROUP_MODE_CLIP_ONLY,
+ CANVAS_GROUP_MODE_CLIP_AND_DRAW,
CANVAS_GROUP_MODE_TRANSPARENT,
};
@@ -1574,6 +1575,8 @@ public:
virtual void set_print_gpu_profile(bool p_enable) = 0;
+ virtual Size2i get_maximum_viewport_size() const = 0;
+
RenderingDevice *get_rendering_device() const;
RenderingDevice *create_local_rendering_device() const;
diff --git a/servers/xr/xr_interface.cpp b/servers/xr/xr_interface.cpp
index 430e2042d9..a5ee1d5726 100644
--- a/servers/xr/xr_interface.cpp
+++ b/servers/xr/xr_interface.cpp
@@ -222,12 +222,7 @@ RID XRInterface::get_vrs_texture() {
data_ptr[d++] = density;
}
}
-
- Ref<Image> image;
- image.instantiate();
- image->create_from_data(vrs_sizei.x, vrs_sizei.y, false, Image::FORMAT_R8, data);
-
- images.push_back(image);
+ images.push_back(Image::create_from_data(vrs_sizei.x, vrs_sizei.y, false, Image::FORMAT_R8, data));
}
if (images.size() == 1) {
diff --git a/tests/core/math/test_aabb.h b/tests/core/math/test_aabb.h
index d5f54a139e..ebaf441abf 100644
--- a/tests/core/math/test_aabb.h
+++ b/tests/core/math/test_aabb.h
@@ -389,6 +389,27 @@ TEST_CASE("[AABB] Expanding") {
aabb.expand(Vector3(-20, 0, 0)).is_equal_approx(AABB(Vector3(-20, 0, -2.5), Vector3(22.5, 7, 6))),
"expand() with non-contained point should return the expected AABB.");
}
+
+TEST_CASE("[AABB] Finite number checks") {
+ const Vector3 x(0, 1, 2);
+ const Vector3 infinite(NAN, NAN, NAN);
+
+ CHECK_MESSAGE(
+ AABB(x, x).is_finite(),
+ "AABB with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ AABB(infinite, x).is_finite(),
+ "AABB with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ AABB(x, infinite).is_finite(),
+ "AABB with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ AABB(infinite, infinite).is_finite(),
+ "AABB with two components infinite should not be finite.");
+}
+
} // namespace TestAABB
#endif // TEST_AABB_H
diff --git a/tests/core/math/test_basis.h b/tests/core/math/test_basis.h
index b6493c5726..90ca9e439f 100644
--- a/tests/core/math/test_basis.h
+++ b/tests/core/math/test_basis.h
@@ -170,8 +170,7 @@ void test_rotation(Vector3 deg_original_euler, RotOrder rot_order) {
// Double check `to_rotation` decomposing with XYZ rotation order.
const Vector3 euler_xyz_from_rotation = to_rotation.get_euler(Basis::EULER_ORDER_XYZ);
- Basis rotation_from_xyz_computed_euler;
- rotation_from_xyz_computed_euler.set_euler(euler_xyz_from_rotation, Basis::EULER_ORDER_XYZ);
+ Basis rotation_from_xyz_computed_euler = Basis::from_euler(euler_xyz_from_rotation, Basis::EULER_ORDER_XYZ);
res = to_rotation.inverse() * rotation_from_xyz_computed_euler;
@@ -334,6 +333,40 @@ TEST_CASE("[Basis] Set axis angle") {
bugNan.get_axis_angle(axis, angle);
CHECK(!Math::is_nan(angle));
}
+
+TEST_CASE("[Basis] Finite number checks") {
+ const Vector3 x(0, 1, 2);
+ const Vector3 infinite(NAN, NAN, NAN);
+
+ CHECK_MESSAGE(
+ Basis(x, x, x).is_finite(),
+ "Basis with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Basis(infinite, x, x).is_finite(),
+ "Basis with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Basis(x, infinite, x).is_finite(),
+ "Basis with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Basis(x, x, infinite).is_finite(),
+ "Basis with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Basis(infinite, infinite, x).is_finite(),
+ "Basis with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Basis(infinite, x, infinite).is_finite(),
+ "Basis with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Basis(x, infinite, infinite).is_finite(),
+ "Basis with two components infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Basis(infinite, infinite, infinite).is_finite(),
+ "Basis with three components infinite should not be finite.");
+}
+
} // namespace TestBasis
#endif // TEST_BASIS_H
diff --git a/tests/core/math/test_plane.h b/tests/core/math/test_plane.h
index d81a5af1ce..84d9a0ff7d 100644
--- a/tests/core/math/test_plane.h
+++ b/tests/core/math/test_plane.h
@@ -167,6 +167,29 @@ TEST_CASE("[Plane] Intersection") {
vec_out.is_equal_approx(Vector3(1, 1, 1)),
"intersects_segment() should modify vec_out to the expected result.");
}
+
+TEST_CASE("[Plane] Finite number checks") {
+ const Vector3 x(0, 1, 2);
+ const Vector3 infinite_vec(NAN, NAN, NAN);
+ const real_t y = 0;
+ const real_t infinite_y = NAN;
+
+ CHECK_MESSAGE(
+ Plane(x, y).is_finite(),
+ "Plane with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Plane(x, infinite_y).is_finite(),
+ "Plane with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Plane(infinite_vec, y).is_finite(),
+ "Plane with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Plane(infinite_vec, infinite_y).is_finite(),
+ "Plane with two components infinite should not be finite.");
+}
+
} // namespace TestPlane
#endif // TEST_PLANE_H
diff --git a/tests/core/math/test_quaternion.h b/tests/core/math/test_quaternion.h
index 63d30759bb..eb5fea1d2d 100644
--- a/tests/core/math/test_quaternion.h
+++ b/tests/core/math/test_quaternion.h
@@ -192,7 +192,7 @@ TEST_CASE("[Quaternion] Construct Basis Euler") {
double roll = Math::deg_to_rad(10.0);
Vector3 euler_yxz(pitch, yaw, roll);
Quaternion q_yxz(euler_yxz);
- Basis basis_axes(euler_yxz);
+ Basis basis_axes = Basis::from_euler(euler_yxz);
Quaternion q(basis_axes);
CHECK(q.is_equal_approx(q_yxz));
}
@@ -218,7 +218,7 @@ TEST_CASE("[Quaternion] Construct Basis Axes") {
// This is by design, but may be subject to change.
// Workaround by constructing Basis from Euler angles.
// basis_axes = Basis(i_unit, j_unit, k_unit);
- Basis basis_axes(euler_yxz);
+ Basis basis_axes = Basis::from_euler(euler_yxz);
Quaternion q(basis_axes);
CHECK(basis_axes.get_column(0).is_equal_approx(i_unit));
@@ -334,7 +334,7 @@ TEST_CASE("[Quaternion] xform unit vectors") {
TEST_CASE("[Quaternion] xform vector") {
// Arbitrary quaternion rotates an arbitrary vector.
Vector3 euler_yzx(Math::deg_to_rad(31.41), Math::deg_to_rad(-49.16), Math::deg_to_rad(12.34));
- Basis basis_axes(euler_yzx);
+ Basis basis_axes = Basis::from_euler(euler_yzx);
Quaternion q(basis_axes);
Vector3 v_arb(3.0, 4.0, 5.0);
@@ -347,7 +347,7 @@ TEST_CASE("[Quaternion] xform vector") {
// Test vector xform for a single combination of Quaternion and Vector.
void test_quat_vec_rotate(Vector3 euler_yzx, Vector3 v_in) {
- Basis basis_axes(euler_yzx);
+ Basis basis_axes = Basis::from_euler(euler_yzx);
Quaternion q(basis_axes);
Vector3 v_rot = q.xform(v_in);
@@ -384,6 +384,63 @@ TEST_CASE("[Stress][Quaternion] Many vector xforms") {
}
}
+TEST_CASE("[Quaternion] Finite number checks") {
+ const real_t x = NAN;
+
+ CHECK_MESSAGE(
+ Quaternion(0, 1, 2, 3).is_finite(),
+ "Quaternion with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, 1, 2, 3).is_finite(),
+ "Quaternion with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, x, 2, 3).is_finite(),
+ "Quaternion with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, 1, x, 3).is_finite(),
+ "Quaternion with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, 1, 2, x).is_finite(),
+ "Quaternion with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, x, 2, 3).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, 1, x, 3).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, 1, 2, x).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, x, x, 3).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, x, 2, x).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, 1, x, x).is_finite(),
+ "Quaternion with two components infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Quaternion(0, x, x, x).is_finite(),
+ "Quaternion with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, 1, x, x).is_finite(),
+ "Quaternion with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, x, 2, x).is_finite(),
+ "Quaternion with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, x, x, 3).is_finite(),
+ "Quaternion with three components infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Quaternion(x, x, x, x).is_finite(),
+ "Quaternion with four components infinite should not be finite.");
+}
+
} // namespace TestQuaternion
#endif // TEST_QUATERNION_H
diff --git a/tests/core/math/test_rect2.h b/tests/core/math/test_rect2.h
index 6323b214db..d784875c1c 100644
--- a/tests/core/math/test_rect2.h
+++ b/tests/core/math/test_rect2.h
@@ -300,6 +300,27 @@ TEST_CASE("[Rect2] Merging") {
Rect2(0, 100, 1280, 720).merge(Rect2(-4000, -4000, 100, 100)).is_equal_approx(Rect2(-4000, -4000, 5280, 4820)),
"merge() with non-enclosed Rect2 should return the expected result.");
}
+
+TEST_CASE("[Rect2] Finite number checks") {
+ const Vector2 x(0, 1);
+ const Vector2 infinite(NAN, NAN);
+
+ CHECK_MESSAGE(
+ Rect2(x, x).is_finite(),
+ "Rect2 with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Rect2(infinite, x).is_finite(),
+ "Rect2 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Rect2(x, infinite).is_finite(),
+ "Rect2 with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Rect2(infinite, infinite).is_finite(),
+ "Rect2 with two components infinite should not be finite.");
+}
+
} // namespace TestRect2
#endif // TEST_RECT2_H
diff --git a/tests/core/math/test_transform_2d.h b/tests/core/math/test_transform_2d.h
index 697bf63fc5..ab51bcd7da 100644
--- a/tests/core/math/test_transform_2d.h
+++ b/tests/core/math/test_transform_2d.h
@@ -83,6 +83,40 @@ TEST_CASE("[Transform2D] rotation") {
CHECK(orig.rotated(phi) == R * orig);
CHECK(orig.rotated_local(phi) == orig * R);
}
+
+TEST_CASE("[Transform2D] Finite number checks") {
+ const Vector2 x(0, 1);
+ const Vector2 infinite(NAN, NAN);
+
+ CHECK_MESSAGE(
+ Transform2D(x, x, x).is_finite(),
+ "Transform2D with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Transform2D(infinite, x, x).is_finite(),
+ "Transform2D with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Transform2D(x, infinite, x).is_finite(),
+ "Transform2D with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Transform2D(x, x, infinite).is_finite(),
+ "Transform2D with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Transform2D(infinite, infinite, x).is_finite(),
+ "Transform2D with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Transform2D(infinite, x, infinite).is_finite(),
+ "Transform2D with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Transform2D(x, infinite, infinite).is_finite(),
+ "Transform2D with two components infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Transform2D(infinite, infinite, infinite).is_finite(),
+ "Transform2D with three components infinite should not be finite.");
+}
+
} // namespace TestTransform2D
#endif // TEST_TRANSFORM_2D_H
diff --git a/tests/core/math/test_transform_3d.h b/tests/core/math/test_transform_3d.h
index da166b43f7..d2730f3577 100644
--- a/tests/core/math/test_transform_3d.h
+++ b/tests/core/math/test_transform_3d.h
@@ -84,6 +84,29 @@ TEST_CASE("[Transform3D] rotation") {
CHECK(orig.rotated(axis, phi) == R * orig);
CHECK(orig.rotated_local(axis, phi) == orig * R);
}
+
+TEST_CASE("[Transform3D] Finite number checks") {
+ const Vector3 y(0, 1, 2);
+ const Vector3 infinite_vec(NAN, NAN, NAN);
+ const Basis x(y, y, y);
+ const Basis infinite_basis(infinite_vec, infinite_vec, infinite_vec);
+
+ CHECK_MESSAGE(
+ Transform3D(x, y).is_finite(),
+ "Transform3D with all components finite should be finite");
+
+ CHECK_FALSE_MESSAGE(
+ Transform3D(x, infinite_vec).is_finite(),
+ "Transform3D with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Transform3D(infinite_basis, y).is_finite(),
+ "Transform3D with one component infinite should not be finite.");
+
+ CHECK_FALSE_MESSAGE(
+ Transform3D(infinite_basis, infinite_vec).is_finite(),
+ "Transform3D with two components infinite should not be finite.");
+}
+
} // namespace TestTransform3D
#endif // TEST_TRANSFORM_3D_H
diff --git a/tests/core/math/test_vector2.h b/tests/core/math/test_vector2.h
index 0d7f1163e4..a87b9ffc02 100644
--- a/tests/core/math/test_vector2.h
+++ b/tests/core/math/test_vector2.h
@@ -465,6 +465,32 @@ TEST_CASE("[Vector2] Linear algebra methods") {
Math::is_equal_approx(Vector2(-a.x, a.y).dot(Vector2(b.x, -b.y)), (real_t)-57.3),
"Vector2 dot should return expected value.");
}
+
+TEST_CASE("[Vector2] Finite number checks") {
+ const double infinite[] = { NAN, INFINITY, -INFINITY };
+
+ CHECK_MESSAGE(
+ Vector2(0, 1).is_finite(),
+ "Vector2(0, 1) should be finite");
+
+ for (double x : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector2(x, 1).is_finite(),
+ "Vector2 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector2(0, x).is_finite(),
+ "Vector2 with one component infinite should not be finite.");
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector2(x, y).is_finite(),
+ "Vector2 with two components infinite should not be finite.");
+ }
+ }
+}
+
} // namespace TestVector2
#endif // TEST_VECTOR2_H
diff --git a/tests/core/math/test_vector3.h b/tests/core/math/test_vector3.h
index be271bad1f..4932cd04db 100644
--- a/tests/core/math/test_vector3.h
+++ b/tests/core/math/test_vector3.h
@@ -479,6 +479,51 @@ TEST_CASE("[Vector3] Linear algebra methods") {
Math::is_equal_approx(Vector3(-a.x, a.y, -a.z).dot(Vector3(b.x, -b.y, b.z)), (real_t)-75.24),
"Vector3 dot should return expected value.");
}
+
+TEST_CASE("[Vector3] Finite number checks") {
+ const double infinite[] = { NAN, INFINITY, -INFINITY };
+
+ CHECK_MESSAGE(
+ Vector3(0, 1, 2).is_finite(),
+ "Vector3(0, 1, 2) should be finite");
+
+ for (double x : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector3(x, 1, 2).is_finite(),
+ "Vector3 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector3(0, x, 2).is_finite(),
+ "Vector3 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector3(0, 1, x).is_finite(),
+ "Vector3 with one component infinite should not be finite.");
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector3(x, y, 2).is_finite(),
+ "Vector3 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector3(x, 1, y).is_finite(),
+ "Vector3 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector3(0, x, y).is_finite(),
+ "Vector3 with two components infinite should not be finite.");
+ }
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ for (double z : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector3(x, y, z).is_finite(),
+ "Vector3 with three components infinite should not be finite.");
+ }
+ }
+ }
+}
+
} // namespace TestVector3
#endif // TEST_VECTOR3_H
diff --git a/tests/core/math/test_vector4.h b/tests/core/math/test_vector4.h
index 3f50f16635..b31db56f67 100644
--- a/tests/core/math/test_vector4.h
+++ b/tests/core/math/test_vector4.h
@@ -314,6 +314,84 @@ TEST_CASE("[Vector4] Linear algebra methods") {
Math::is_equal_approx((vector1 * 2).dot(vector2 * 4), (real_t)-25.9 * 8),
"Vector4 dot product should work as expected.");
}
+
+TEST_CASE("[Vector4] Finite number checks") {
+ const double infinite[] = { NAN, INFINITY, -INFINITY };
+
+ CHECK_MESSAGE(
+ Vector4(0, 1, 2, 3).is_finite(),
+ "Vector4(0, 1, 2, 3) should be finite");
+
+ for (double x : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, 1, 2, 3).is_finite(),
+ "Vector4 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, x, 2, 3).is_finite(),
+ "Vector4 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, 1, x, 3).is_finite(),
+ "Vector4 with one component infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, 1, 2, x).is_finite(),
+ "Vector4 with one component infinite should not be finite.");
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, y, 2, 3).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, 1, y, 3).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, 1, 2, y).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, x, y, 3).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, x, 2, y).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, 1, x, y).is_finite(),
+ "Vector4 with two components infinite should not be finite.");
+ }
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ for (double z : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector4(0, x, y, z).is_finite(),
+ "Vector4 with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, 1, y, z).is_finite(),
+ "Vector4 with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, y, 2, z).is_finite(),
+ "Vector4 with three components infinite should not be finite.");
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, y, z, 3).is_finite(),
+ "Vector4 with three components infinite should not be finite.");
+ }
+ }
+ }
+
+ for (double x : infinite) {
+ for (double y : infinite) {
+ for (double z : infinite) {
+ for (double w : infinite) {
+ CHECK_FALSE_MESSAGE(
+ Vector4(x, y, z, w).is_finite(),
+ "Vector4 with four components infinite should not be finite.");
+ }
+ }
+ }
+ }
+}
+
} // namespace TestVector4
#endif // TEST_VECTOR4_H
diff --git a/tests/core/string/test_string.h b/tests/core/string/test_string.h
index 969f5fc096..cd1b421ce8 100644
--- a/tests/core/string/test_string.h
+++ b/tests/core/string/test_string.h
@@ -411,9 +411,13 @@ TEST_CASE("[String] Number to string") {
CHECK(String::num_real(3.141593) == "3.141593");
CHECK(String::num_real(3.141) == "3.141"); // No trailing zeros.
#ifdef REAL_T_IS_DOUBLE
+ CHECK_MESSAGE(String::num_real(123.456789) == "123.456789", "Prints the appropriate amount of digits for real_t = double.");
+ CHECK_MESSAGE(String::num_real(-123.456789) == "-123.456789", "Prints the appropriate amount of digits for real_t = double.");
CHECK_MESSAGE(String::num_real(Math_PI) == "3.14159265358979", "Prints the appropriate amount of digits for real_t = double.");
CHECK_MESSAGE(String::num_real(3.1415f) == "3.1414999961853", "Prints more digits of 32-bit float when real_t = double (ones that would be reliable for double) and no trailing zero.");
#else
+ CHECK_MESSAGE(String::num_real(123.456789) == "123.4568", "Prints the appropriate amount of digits for real_t = float.");
+ CHECK_MESSAGE(String::num_real(-123.456789) == "-123.4568", "Prints the appropriate amount of digits for real_t = float.");
CHECK_MESSAGE(String::num_real(Math_PI) == "3.141593", "Prints the appropriate amount of digits for real_t = float.");
CHECK_MESSAGE(String::num_real(3.1415f) == "3.1415", "Prints only reliable digits of 32-bit float when real_t = float.");
#endif // REAL_T_IS_DOUBLE
@@ -1424,20 +1428,22 @@ TEST_CASE("[String] dedent") {
}
TEST_CASE("[String] Path functions") {
- static const char *path[7] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc", "C:\\test.", "res://test", "/.test" };
- static const char *base_dir[7] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot", "C:\\", "res://", "/" };
- static const char *base_name[7] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test", "C:\\test", "res://test", "/" };
- static const char *ext[7] = { "tscn", "xscn", "scn", "doc", "", "", "test" };
- static const char *file[7] = { "test.tscn", "test.xscn", "test.scn", "test.doc", "test.", "test", ".test" };
- static const bool abs[7] = { true, true, false, false, true, true, true };
-
- for (int i = 0; i < 7; i++) {
+ static const char *path[8] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc", "C:\\test.", "res://test", "user://test", "/.test" };
+ static const char *base_dir[8] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot", "C:\\", "res://", "user://", "/" };
+ static const char *base_name[8] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test", "C:\\test", "res://test", "user://test", "/" };
+ static const char *ext[8] = { "tscn", "xscn", "scn", "doc", "", "", "", "test" };
+ static const char *file[8] = { "test.tscn", "test.xscn", "test.scn", "test.doc", "test.", "test", "test", ".test" };
+ static const char *simplified[8] = { "C:/Godot/project/test.tscn", "/Godot/project/test.xscn", "Godot/project/test.scn", "Godot/test.doc", "C:/test.", "res://test", "user://test", "/.test" };
+ static const bool abs[8] = { true, true, false, false, true, true, true, true };
+
+ for (int i = 0; i < 8; i++) {
CHECK(String(path[i]).get_base_dir() == base_dir[i]);
CHECK(String(path[i]).get_basename() == base_name[i]);
CHECK(String(path[i]).get_extension() == ext[i]);
CHECK(String(path[i]).get_file() == file[i]);
CHECK(String(path[i]).is_absolute_path() == abs[i]);
CHECK(String(path[i]).is_relative_path() != abs[i]);
+ CHECK(String(path[i]).simplify_path() == String(simplified[i]));
CHECK(String(path[i]).simplify_path().get_base_dir().path_join(file[i]) == String(path[i]).simplify_path());
}
diff --git a/tests/scene/test_bit_map.h b/tests/scene/test_bit_map.h
index 635449181e..a102f40725 100644
--- a/tests/scene/test_bit_map.h
+++ b/tests/scene/test_bit_map.h
@@ -76,15 +76,11 @@ TEST_CASE("[BitMap] Create bit map from image alpha") {
bit_map.create_from_image_alpha(empty_img);
CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Bitmap should have its old values because bitmap creation from an empty image should fail.");
- Ref<Image> wrong_format_img;
- wrong_format_img.instantiate();
- wrong_format_img->create(3, 3, false, Image::Format::FORMAT_DXT1);
+ Ref<Image> wrong_format_img = Image::create_empty(3, 3, false, Image::Format::FORMAT_DXT1);
bit_map.create_from_image_alpha(wrong_format_img);
CHECK_MESSAGE(bit_map.get_size() == Size2i(256, 256), "Bitmap should have its old values because converting from a compressed image should fail.");
- Ref<Image> img;
- img.instantiate();
- img->create(3, 3, false, Image::Format::FORMAT_RGBA8);
+ Ref<Image> img = Image::create_empty(3, 3, false, Image::Format::FORMAT_RGBA8);
img->set_pixel(0, 0, Color(0, 0, 0, 0));
img->set_pixel(0, 1, Color(0, 0, 0, 0.09f));
img->set_pixel(0, 2, Color(0, 0, 0, 0.25f));
diff --git a/tests/scene/test_text_edit.h b/tests/scene/test_text_edit.h
index 6b831bc9c7..4b92b9daff 100644
--- a/tests/scene/test_text_edit.h
+++ b/tests/scene/test_text_edit.h
@@ -637,17 +637,42 @@ TEST_CASE("[SceneTree][TextEdit] text entry") {
}
SUBCASE("[TextEdit] select word under caret") {
- text_edit->set_text("test test");
+ text_edit->set_text("\ntest test\ntest test");
+
text_edit->set_caret_column(0);
+ text_edit->set_caret_line(1);
+
+ text_edit->add_caret(2, 0);
+ text_edit->add_caret(2, 2);
+ CHECK(text_edit->get_caret_count() == 3);
+
+ MessageQueue::get_singleton()->flush();
+
+ SIGNAL_DISCARD("text_set");
+ SIGNAL_DISCARD("text_changed");
+ SIGNAL_DISCARD("lines_edited_from");
+ SIGNAL_DISCARD("caret_changed");
+
text_edit->select_word_under_caret();
- CHECK(text_edit->get_selected_text() == "test");
- CHECK(text_edit->has_selection());
- CHECK(text_edit->get_selection_from_line() == 0);
- CHECK(text_edit->get_selection_from_column() == 0);
- CHECK(text_edit->get_selection_to_line() == 0);
- CHECK(text_edit->get_selection_to_column() == 4);
- CHECK(text_edit->get_caret_line() == 0);
- CHECK(text_edit->get_caret_column() == 4);
+ CHECK(text_edit->has_selection(0));
+ CHECK(text_edit->get_selected_text(0) == "test");
+ CHECK(text_edit->get_selection_from_line(0) == 1);
+ CHECK(text_edit->get_selection_from_column(0) == 0);
+ CHECK(text_edit->get_selection_to_line(0) == 1);
+ CHECK(text_edit->get_selection_to_column(0) == 4);
+ CHECK(text_edit->get_caret_line(0) == 1);
+ CHECK(text_edit->get_caret_column(0) == 4);
+
+ CHECK(text_edit->has_selection(1));
+ CHECK(text_edit->get_selected_text(1) == "test");
+ CHECK(text_edit->get_selection_from_line(1) == 2);
+ CHECK(text_edit->get_selection_from_column(1) == 0);
+ CHECK(text_edit->get_selection_to_line(1) == 2);
+ CHECK(text_edit->get_selection_to_column(1) == 4);
+ CHECK(text_edit->get_caret_line(1) == 2);
+ CHECK(text_edit->get_caret_column(1) == 4);
+
+ CHECK(text_edit->get_caret_count() == 2);
text_edit->select_word_under_caret();
CHECK_FALSE(text_edit->has_selection());
@@ -656,27 +681,44 @@ TEST_CASE("[SceneTree][TextEdit] text entry") {
SEND_GUI_ACTION(text_edit, "ui_text_select_word_under_caret");
CHECK(text_edit->get_viewport()->is_input_handled());
MessageQueue::get_singleton()->flush();
- CHECK(text_edit->has_selection());
- CHECK(text_edit->get_selected_text() == "test");
- CHECK(text_edit->get_selection_from_line() == 0);
- CHECK(text_edit->get_selection_from_column() == 0);
- CHECK(text_edit->get_selection_to_line() == 0);
- CHECK(text_edit->get_selection_to_column() == 4);
- CHECK(text_edit->get_caret_line() == 0);
- CHECK(text_edit->get_caret_column() == 4);
+ CHECK(text_edit->has_selection(0));
+ CHECK(text_edit->get_selected_text(0) == "test");
+ CHECK(text_edit->get_selection_from_line(0) == 1);
+ CHECK(text_edit->get_selection_from_column(0) == 0);
+ CHECK(text_edit->get_selection_to_line(0) == 1);
+ CHECK(text_edit->get_selection_to_column(0) == 4);
+ CHECK(text_edit->get_caret_line(0) == 1);
+ CHECK(text_edit->get_caret_column(0) == 4);
+
+ CHECK(text_edit->has_selection(1));
+ CHECK(text_edit->get_selected_text(1) == "test");
+ CHECK(text_edit->get_selection_from_line(1) == 2);
+ CHECK(text_edit->get_selection_from_column(1) == 0);
+ CHECK(text_edit->get_selection_to_line(1) == 2);
+ CHECK(text_edit->get_selection_to_column(1) == 4);
+ CHECK(text_edit->get_caret_line(1) == 2);
+ CHECK(text_edit->get_caret_column(1) == 4);
+
+ CHECK(text_edit->get_selected_text() == "test\ntest");
SIGNAL_CHECK("caret_changed", empty_signal_args);
text_edit->set_selecting_enabled(false);
text_edit->select_word_under_caret();
CHECK_FALSE(text_edit->has_selection());
CHECK(text_edit->get_selected_text() == "");
- CHECK(text_edit->get_caret_line() == 0);
- CHECK(text_edit->get_caret_column() == 4);
+ CHECK(text_edit->get_caret_line(0) == 1);
+ CHECK(text_edit->get_caret_column(0) == 4);
+ CHECK(text_edit->get_caret_line(1) == 2);
+ CHECK(text_edit->get_caret_column(1) == 4);
SIGNAL_CHECK_FALSE("caret_changed");
text_edit->set_selecting_enabled(true);
- text_edit->set_caret_line(0);
- text_edit->set_caret_column(5);
+ text_edit->set_caret_line(1, false, true, 0, 0);
+ text_edit->set_caret_column(5, false, 0);
+
+ text_edit->set_caret_line(2, false, true, 0, 1);
+ text_edit->set_caret_column(5, false, 1);
+
text_edit->select_word_under_caret();
CHECK_FALSE(text_edit->has_selection());
CHECK(text_edit->get_selected_text() == "");
@@ -684,11 +726,53 @@ TEST_CASE("[SceneTree][TextEdit] text entry") {
text_edit->select_word_under_caret();
CHECK_FALSE(text_edit->has_selection());
CHECK(text_edit->get_selected_text() == "");
- CHECK(text_edit->get_caret_line() == 0);
- CHECK(text_edit->get_caret_column() == 5);
+ CHECK(text_edit->get_caret_line(0) == 1);
+ CHECK(text_edit->get_caret_column(0) == 5);
+ CHECK(text_edit->get_caret_line(1) == 2);
+ CHECK(text_edit->get_caret_column(1) == 5);
SIGNAL_CHECK_FALSE("caret_changed");
}
+ SUBCASE("[TextEdit] add selection for next occurrence") {
+ text_edit->set_text("\ntest other_test\nrandom test\nword test word");
+ text_edit->set_caret_column(0);
+ text_edit->set_caret_line(1);
+
+ text_edit->select_word_under_caret();
+ CHECK(text_edit->has_selection(0));
+ CHECK(text_edit->get_selected_text(0) == "test");
+
+ text_edit->add_selection_for_next_occurrence();
+ CHECK(text_edit->get_caret_count() == 2);
+ CHECK(text_edit->get_selected_text(1) == "test");
+ CHECK(text_edit->get_selection_from_line(1) == 1);
+ CHECK(text_edit->get_selection_from_column(1) == 13);
+ CHECK(text_edit->get_selection_to_line(1) == 1);
+ CHECK(text_edit->get_selection_to_column(1) == 17);
+ CHECK(text_edit->get_caret_line(1) == 1);
+ CHECK(text_edit->get_caret_column(1) == 17);
+
+ text_edit->add_selection_for_next_occurrence();
+ CHECK(text_edit->get_caret_count() == 3);
+ CHECK(text_edit->get_selected_text(2) == "test");
+ CHECK(text_edit->get_selection_from_line(2) == 2);
+ CHECK(text_edit->get_selection_from_column(2) == 9);
+ CHECK(text_edit->get_selection_to_line(2) == 2);
+ CHECK(text_edit->get_selection_to_column(2) == 13);
+ CHECK(text_edit->get_caret_line(2) == 2);
+ CHECK(text_edit->get_caret_column(2) == 13);
+
+ text_edit->add_selection_for_next_occurrence();
+ CHECK(text_edit->get_caret_count() == 4);
+ CHECK(text_edit->get_selected_text(3) == "test");
+ CHECK(text_edit->get_selection_from_line(3) == 3);
+ CHECK(text_edit->get_selection_from_column(3) == 5);
+ CHECK(text_edit->get_selection_to_line(3) == 3);
+ CHECK(text_edit->get_selection_to_column(3) == 9);
+ CHECK(text_edit->get_caret_line(3) == 3);
+ CHECK(text_edit->get_caret_column(3) == 9);
+ }
+
SUBCASE("[TextEdit] deselect on focus loss") {
text_edit->set_text("test");
@@ -2944,6 +3028,18 @@ TEST_CASE("[SceneTree][TextEdit] text entry") {
SIGNAL_CHECK("lines_edited_from", lines_edited_args);
text_edit->set_overtype_mode_enabled(false);
CHECK_FALSE(text_edit->is_overtype_mode_enabled());
+
+ lines_edited_args.remove_at(0);
+ lines_edited_args.remove_at(1);
+
+ SEND_GUI_KEY_EVENT(text_edit, Key::TAB);
+ CHECK(text_edit->get_viewport()->is_input_handled());
+ CHECK(text_edit->get_text() == "A\tB\nA\tB");
+ CHECK(text_edit->get_caret_column() == 2);
+ CHECK(text_edit->get_caret_column(1) == 2);
+ SIGNAL_CHECK("caret_changed", empty_signal_args);
+ SIGNAL_CHECK("text_changed", empty_signal_args);
+ SIGNAL_CHECK("lines_edited_from", lines_edited_args);
}
SIGNAL_UNWATCH(text_edit, "text_set");
@@ -3321,6 +3417,11 @@ TEST_CASE("[SceneTree][TextEdit] muiticaret") {
CHECK(text_edit->get_caret_count() == 1);
CHECK(text_edit->get_caret_line(0) == 0);
CHECK(text_edit->get_caret_column(0) == 1);
+
+ ERR_PRINT_OFF;
+ text_edit->remove_caret(0);
+ CHECK(text_edit->get_caret_count() == 1);
+ ERR_PRINT_ON;
}
SUBCASE("[TextEdit] caret index edit order") {
@@ -3857,6 +3958,32 @@ TEST_CASE("[SceneTree][TextEdit] viewport") {
CHECK(text_edit->get_last_full_visible_line_wrap_index() == 0);
CHECK(text_edit->get_caret_wrap_index() == 0);
+ // Typing and undo / redo should adjust viewport
+ text_edit->set_caret_line(0);
+ text_edit->set_caret_column(0);
+ text_edit->set_line_as_first_visible(5);
+ MessageQueue::get_singleton()->flush();
+ CHECK(text_edit->get_first_visible_line() == 5);
+
+ SEND_GUI_KEY_EVENT(text_edit, Key::A);
+ CHECK(text_edit->get_first_visible_line() == 0);
+
+ text_edit->set_line_as_first_visible(5);
+ MessageQueue::get_singleton()->flush();
+ CHECK(text_edit->get_first_visible_line() == 5);
+
+ text_edit->undo();
+ MessageQueue::get_singleton()->flush();
+ CHECK(text_edit->get_first_visible_line() == 0);
+
+ text_edit->set_line_as_first_visible(5);
+ MessageQueue::get_singleton()->flush();
+ CHECK(text_edit->get_first_visible_line() == 5);
+
+ text_edit->redo();
+ MessageQueue::get_singleton()->flush();
+ CHECK(text_edit->get_first_visible_line() == 0);
+
memdelete(text_edit);
}
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 4c861eacba..d30d4a9e70 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -199,7 +199,7 @@ struct GodotTestCaseListener : public doctest::IReporter {
OS::get_singleton()->set_has_server_feature_callback(nullptr);
for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
if (String("headless") == DisplayServer::get_create_function_name(i)) {
- DisplayServer::create(i, "", DisplayServer::WindowMode::WINDOW_MODE_MINIMIZED, DisplayServer::VSyncMode::VSYNC_ENABLED, 0, Vector2i(0, 0), err);
+ DisplayServer::create(i, "", DisplayServer::WindowMode::WINDOW_MODE_MINIMIZED, DisplayServer::VSyncMode::VSYNC_ENABLED, 0, nullptr, Vector2i(0, 0), err);
break;
}
}
diff --git a/thirdparty/README.md b/thirdparty/README.md
index ac97d9c2a2..19c155a2d4 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -656,7 +656,7 @@ instead of `miniz.h` as an external dependency.
## thorvg
- Upstream: https://github.com/Samsung/thorvg
-- Version: 0.8.1 (c4ccb1078f4390ec749ab8e05ba7e9e35f81285f, 2022)
+- Version: 0.8.2 (496796f1e5e85bd5fbba36dae987edb1b3945592, 2022)
- License: MIT
Files extracted from upstream source:
diff --git a/thirdparty/glad/KHR/khrplatform.h b/thirdparty/glad/KHR/khrplatform.h
index dd22d92701..01646449ca 100644
--- a/thirdparty/glad/KHR/khrplatform.h
+++ b/thirdparty/glad/KHR/khrplatform.h
@@ -153,6 +153,20 @@ typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
+/*
+ * To support platform where unsigned long cannot be used interchangeably with
+ * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
+ * Ideally, we could just use (u)intptr_t everywhere, but this could result in
+ * ABI breakage if khronos_uintptr_t is changed from unsigned long to
+ * unsigned long long or similar (this results in different C++ name mangling).
+ * To avoid changes for existing platforms, we restrict usage of intptr_t to
+ * platforms where the size of a pointer is larger than the size of long.
+ */
+#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
+#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
+#define KHRONOS_USE_INTPTR_T
+#endif
+#endif
#elif defined(__VMS ) || defined(__sgi)
@@ -235,14 +249,21 @@ typedef unsigned short int khronos_uint16_t;
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
-#ifdef _WIN64
+#ifdef KHRONOS_USE_INTPTR_T
+typedef intptr_t khronos_intptr_t;
+typedef uintptr_t khronos_uintptr_t;
+#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
-typedef signed long long int khronos_ssize_t;
-typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
+#endif
+
+#if defined(_WIN64)
+typedef signed long long int khronos_ssize_t;
+typedef unsigned long long int khronos_usize_t;
+#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
diff --git a/thirdparty/glad/glad.c b/thirdparty/glad/glad.c
index dc1b8cb697..4b20178ef7 100644
--- a/thirdparty/glad/glad.c
+++ b/thirdparty/glad/glad.c
@@ -1,6 +1,6 @@
/*
- OpenGL loader generated by glad 0.1.34 on Tue Nov 17 16:41:02 2020.
+ OpenGL loader generated by glad 0.1.36 on Sun Sep 4 15:50:32 2022.
Language/Generator: C/C++
Specification: gl
@@ -11,16 +11,18 @@
GL_ARB_framebuffer_object,
GL_EXT_framebuffer_blit,
GL_EXT_framebuffer_multisample,
- GL_EXT_framebuffer_object
+ GL_EXT_framebuffer_object,
+ GL_OVR_multiview,
+ GL_OVR_multiview2
Loader: True
Local files: False
Omit khrplatform: False
Reproducible: False
Commandline:
- --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object"
+ --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object,GL_OVR_multiview,GL_OVR_multiview2"
Online:
- https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object
+ https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object&extensions=GL_OVR_multiview&extensions=GL_OVR_multiview2
*/
#include <stdio.h>
@@ -1000,6 +1002,8 @@ int GLAD_GL_ARB_framebuffer_object = 0;
int GLAD_GL_EXT_framebuffer_blit = 0;
int GLAD_GL_EXT_framebuffer_multisample = 0;
int GLAD_GL_EXT_framebuffer_object = 0;
+int GLAD_GL_OVR_multiview = 0;
+int GLAD_GL_OVR_multiview2 = 0;
PFNGLDEBUGMESSAGECONTROLARBPROC glad_glDebugMessageControlARB = NULL;
PFNGLDEBUGMESSAGEINSERTARBPROC glad_glDebugMessageInsertARB = NULL;
PFNGLDEBUGMESSAGECALLBACKARBPROC glad_glDebugMessageCallbackARB = NULL;
@@ -1023,6 +1027,7 @@ PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glad_glFramebufferTexture3DEXT = NULL;
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glad_glFramebufferRenderbufferEXT = NULL;
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glad_glGetFramebufferAttachmentParameterivEXT = NULL;
PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT = NULL;
+PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC glad_glFramebufferTextureMultiviewOVR = NULL;
static void load_GL_VERSION_1_0(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_0) return;
glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace");
@@ -1844,6 +1849,10 @@ static void load_GL_EXT_framebuffer_object(GLADloadproc load) {
glad_glGetFramebufferAttachmentParameterivEXT = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)load("glGetFramebufferAttachmentParameterivEXT");
glad_glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)load("glGenerateMipmapEXT");
}
+static void load_GL_OVR_multiview(GLADloadproc load) {
+ if(!GLAD_GL_OVR_multiview) return;
+ glad_glFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)load("glFramebufferTextureMultiviewOVR");
+}
static int find_extensionsGL(void) {
if (!get_exts()) return 0;
GLAD_GL_ARB_debug_output = has_ext("GL_ARB_debug_output");
@@ -1851,6 +1860,8 @@ static int find_extensionsGL(void) {
GLAD_GL_EXT_framebuffer_blit = has_ext("GL_EXT_framebuffer_blit");
GLAD_GL_EXT_framebuffer_multisample = has_ext("GL_EXT_framebuffer_multisample");
GLAD_GL_EXT_framebuffer_object = has_ext("GL_EXT_framebuffer_object");
+ GLAD_GL_OVR_multiview = has_ext("GL_OVR_multiview");
+ GLAD_GL_OVR_multiview2 = has_ext("GL_OVR_multiview2");
free_exts();
return 1;
}
@@ -1934,6 +1945,7 @@ int gladLoadGLLoader(GLADloadproc load) {
load_GL_EXT_framebuffer_blit(load);
load_GL_EXT_framebuffer_multisample(load);
load_GL_EXT_framebuffer_object(load);
+ load_GL_OVR_multiview(load);
return GLVersion.major != 0 || GLVersion.minor != 0;
}
diff --git a/thirdparty/glad/glad/glad.h b/thirdparty/glad/glad/glad.h
index f211e6aa57..37d12e4ee2 100644
--- a/thirdparty/glad/glad/glad.h
+++ b/thirdparty/glad/glad/glad.h
@@ -1,6 +1,6 @@
/*
- OpenGL loader generated by glad 0.1.34 on Tue Nov 17 16:41:02 2020.
+ OpenGL loader generated by glad 0.1.36 on Sun Sep 4 15:50:32 2022.
Language/Generator: C/C++
Specification: gl
@@ -11,16 +11,18 @@
GL_ARB_framebuffer_object,
GL_EXT_framebuffer_blit,
GL_EXT_framebuffer_multisample,
- GL_EXT_framebuffer_object
+ GL_EXT_framebuffer_object,
+ GL_OVR_multiview,
+ GL_OVR_multiview2
Loader: True
Local files: False
Omit khrplatform: False
Reproducible: False
Commandline:
- --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object"
+ --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object,GL_OVR_multiview,GL_OVR_multiview2"
Online:
- https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object
+ https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object&extensions=GL_OVR_multiview&extensions=GL_OVR_multiview2
*/
@@ -3687,6 +3689,10 @@ GLAPI PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv;
#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53
#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54
#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632
+#define GL_MAX_VIEWS_OVR 0x9631
+#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633
#ifndef GL_ARB_debug_output
#define GL_ARB_debug_output 1
GLAPI int GLAD_GL_ARB_debug_output;
@@ -3776,6 +3782,17 @@ typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC)(GLenum target);
GLAPI PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT;
#define glGenerateMipmapEXT glad_glGenerateMipmapEXT
#endif
+#ifndef GL_OVR_multiview
+#define GL_OVR_multiview 1
+GLAPI int GLAD_GL_OVR_multiview;
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews);
+GLAPI PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC glad_glFramebufferTextureMultiviewOVR;
+#define glFramebufferTextureMultiviewOVR glad_glFramebufferTextureMultiviewOVR
+#endif
+#ifndef GL_OVR_multiview2
+#define GL_OVR_multiview2 1
+GLAPI int GLAD_GL_OVR_multiview2;
+#endif
#ifdef __cplusplus
}
diff --git a/thirdparty/thorvg/inc/config.h b/thirdparty/thorvg/inc/config.h
index 879b70442b..68935c583b 100644
--- a/thirdparty/thorvg/inc/config.h
+++ b/thirdparty/thorvg/inc/config.h
@@ -13,5 +13,5 @@
#define THORVG_JPG_LOADER_SUPPORT 1
-#define THORVG_VERSION_STRING "0.8.1"
+#define THORVG_VERSION_STRING "0.8.2"
#endif
diff --git a/thirdparty/thorvg/src/lib/sw_engine/tvgSwCommon.h b/thirdparty/thorvg/src/lib/sw_engine/tvgSwCommon.h
index 47b0cb83f5..157fdb8f82 100644
--- a/thirdparty/thorvg/src/lib/sw_engine/tvgSwCommon.h
+++ b/thirdparty/thorvg/src/lib/sw_engine/tvgSwCommon.h
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
diff --git a/thirdparty/thorvg/src/lib/sw_engine/tvgSwFill.cpp b/thirdparty/thorvg/src/lib/sw_engine/tvgSwFill.cpp
index bba6f26a0b..04014a9ec3 100644
--- a/thirdparty/thorvg/src/lib/sw_engine/tvgSwFill.cpp
+++ b/thirdparty/thorvg/src/lib/sw_engine/tvgSwFill.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
diff --git a/thirdparty/thorvg/src/lib/sw_engine/tvgSwMath.cpp b/thirdparty/thorvg/src/lib/sw_engine/tvgSwMath.cpp
index ced66ae35c..1027bb1f79 100644
--- a/thirdparty/thorvg/src/lib/sw_engine/tvgSwMath.cpp
+++ b/thirdparty/thorvg/src/lib/sw_engine/tvgSwMath.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
diff --git a/thirdparty/thorvg/src/lib/sw_engine/tvgSwRaster.cpp b/thirdparty/thorvg/src/lib/sw_engine/tvgSwRaster.cpp
index 810df8d435..bf1c10a0c3 100644
--- a/thirdparty/thorvg/src/lib/sw_engine/tvgSwRaster.cpp
+++ b/thirdparty/thorvg/src/lib/sw_engine/tvgSwRaster.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -22,8 +22,8 @@
#ifdef _WIN32
#include <malloc.h>
-#elif defined(__FreeBSD__)
- #include <stdlib.h>
+#elif __FreeBSD__
+ #include<stdlib.h>
#else
#include <alloca.h>
#endif
diff --git a/thirdparty/thorvg/src/lib/sw_engine/tvgSwStroke.cpp b/thirdparty/thorvg/src/lib/sw_engine/tvgSwStroke.cpp
index be4392740e..fa213cc5d3 100644
--- a/thirdparty/thorvg/src/lib/sw_engine/tvgSwStroke.cpp
+++ b/thirdparty/thorvg/src/lib/sw_engine/tvgSwStroke.cpp
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
diff --git a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp
deleted file mode 100644
index 522c3c71a6..0000000000
--- a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (c) 2021 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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 <memory.h>
-#include <turbojpeg.h>
-#include "tvgLoader.h"
-#include "tvgJpgLoader.h"
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-void JpgLoader::clear()
-{
- if (freeData) free(data);
- data = nullptr;
- size = 0;
- freeData = false;
-}
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-JpgLoader::JpgLoader()
-{
- jpegDecompressor = tjInitDecompress();
-}
-
-
-JpgLoader::~JpgLoader()
-{
- if (freeData) free(data);
- tjDestroy(jpegDecompressor);
-
- //This image is shared with raster engine.
- tjFree(image);
-}
-
-
-bool JpgLoader::open(const string& path)
-{
- clear();
-
- auto jpegFile = fopen(path.c_str(), "rb");
- if (!jpegFile) return false;
-
- auto ret = false;
-
- //determine size
- if (fseek(jpegFile, 0, SEEK_END) < 0) goto finalize;
- if (((size = ftell(jpegFile)) < 1)) goto finalize;
- if (fseek(jpegFile, 0, SEEK_SET)) goto finalize;
-
- data = (unsigned char *) malloc(size);
- if (!data) goto finalize;
-
- freeData = true;
-
- if (fread(data, size, 1, jpegFile) < 1) goto failure;
-
- int width, height, subSample, colorSpace;
- if (tjDecompressHeader3(jpegDecompressor, data, size, &width, &height, &subSample, &colorSpace) < 0) {
- TVGERR("JPG LOADER", "%s", tjGetErrorStr());
- goto failure;
- }
-
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- ret = true;
-
- goto finalize;
-
-failure:
- clear();
-
-finalize:
- fclose(jpegFile);
- return ret;
-}
-
-
-bool JpgLoader::open(const char* data, uint32_t size, bool copy)
-{
- clear();
-
- int width, height, subSample, colorSpace;
- if (tjDecompressHeader3(jpegDecompressor, (unsigned char *) data, size, &width, &height, &subSample, &colorSpace) < 0) return false;
-
- if (copy) {
- this->data = (unsigned char *) malloc(size);
- if (!this->data) return false;
- memcpy((unsigned char *)this->data, data, size);
- freeData = true;
- } else {
- this->data = (unsigned char *) data;
- freeData = false;
- }
-
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- this->size = size;
-
- return true;
-}
-
-
-bool JpgLoader::read()
-{
- if (image) tjFree(image);
- image = (unsigned char *)tjAlloc(static_cast<int>(w) * static_cast<int>(h) * tjPixelSize[TJPF_BGRX]);
- if (!image) return false;
-
- //decompress jpg image
- if (tjDecompress2(jpegDecompressor, data, size, image, static_cast<int>(w), 0, static_cast<int>(h), TJPF_BGRX, 0) < 0) {
- TVGERR("JPG LOADER", "%s", tjGetErrorStr());
- tjFree(image);
- image = nullptr;
- return false;
- }
-
- return true;
-}
-
-
-bool JpgLoader::close()
-{
- clear();
- return true;
-}
-
-
-unique_ptr<Surface> JpgLoader::bitmap()
-{
- if (!image) return nullptr;
-
- auto surface = static_cast<Surface*>(malloc(sizeof(Surface)));
- surface->buffer = (uint32_t*)(image);
- surface->stride = w;
- surface->w = w;
- surface->h = h;
- surface->cs = SwCanvas::ARGB8888;
-
- return unique_ptr<Surface>(surface);
-}
diff --git a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h
deleted file mode 100644
index 3f82af8003..0000000000
--- a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2021 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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 _TVG_JPG_LOADER_H_
-#define _TVG_JPG_LOADER_H_
-
-using tjhandle = void*;
-
-//TODO: Use Task?
-class JpgLoader : public LoadModule
-{
-public:
- JpgLoader();
- ~JpgLoader();
-
- using LoadModule::open;
- bool open(const string& path) override;
- bool open(const char* data, uint32_t size, bool copy) override;
- bool read() override;
- bool close() override;
-
- unique_ptr<Surface> bitmap() override;
-
-private:
- void clear();
-
- tjhandle jpegDecompressor;
- unsigned char* data = nullptr;
- unsigned char *image = nullptr;
- unsigned long size = 0;
- bool freeData = false;
-};
-
-#endif //_TVG_JPG_LOADER_H_
diff --git a/thirdparty/thorvg/src/loaders/png/tvgLodePng.cpp b/thirdparty/thorvg/src/loaders/png/tvgLodePng.cpp
deleted file mode 100644
index eaed025c54..0000000000
--- a/thirdparty/thorvg/src/loaders/png/tvgLodePng.cpp
+++ /dev/null
@@ -1,2647 +0,0 @@
-/*
- * Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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.
- */
-
-/*
- LodePNG version 20200306
-
- Copyright (c) 2005-2020 Lode Vandevenne
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any sourcedistribution.
-*/
-
-#include <cstdlib>
-#include "tvgLodePng.h"
-
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
- #pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
- #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
-#endif /*_MSC_VER */
-
-
-/* convince the compiler to inline a function, for use when this measurably improves performance */
-/* inline is not available in C90, but use it when supported by the compiler */
-#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
- #define LODEPNG_INLINE inline
-#else
- #define LODEPNG_INLINE /* not available */
-#endif
-
-/* restrict is not available in C90, but use it when supported by the compiler */
-#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\
- (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \
- (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus))
- #define LODEPNG_RESTRICT __restrict
-#else
- #define LODEPNG_RESTRICT /* not available */
-#endif
-
-#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
-#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
-#define LODEPNG_ABS(x) ((x) < 0 ? -(x) : (x))
-
-
-/* Replacements for C library functions such as memcpy and strlen, to support platforms
-where a full C library is not available. The compiler can recognize them and compile
-to something as fast. */
-
-static void lodepng_memcpy(void* LODEPNG_RESTRICT dst, const void* LODEPNG_RESTRICT src, size_t size)
-{
- size_t i;
- for (i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i];
-}
-
-
-static void lodepng_memset(void* LODEPNG_RESTRICT dst, int value, size_t num)
-{
- size_t i;
- for (i = 0; i < num; i++) ((char*)dst)[i] = (char)value;
-}
-
-
-/* does not check memory out of bounds, do not use on untrusted data */
-static size_t lodepng_strlen(const char* a)
-{
- const char* orig = a;
- /* avoid warning about unused function in case of disabled COMPILE... macros */
- (void)(&lodepng_strlen);
- while (*a) a++;
- return (size_t)(a - orig);
-}
-
-
-/* Safely check if adding two integers will overflow (no undefined
-behavior, compiler removing the code, etc...) and output result. */
-static int lodepng_addofl(size_t a, size_t b, size_t* result)
-{
- *result = a + b; /* Unsigned addition is well defined and safe in C90 */
- return *result < a;
-}
-
-
-/* Safely check if multiplying two integers will overflow (no undefined
-behavior, compiler removing the code, etc...) and output result. */
-static int lodepng_mulofl(size_t a, size_t b, size_t* result)
-{
- *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
- return (a != 0 && *result / a != b);
-}
-
-
-/* Safely check if a + b > c, even if overflow could happen. */
-static int lodepng_gtofl(size_t a, size_t b, size_t c)
-{
- size_t d;
- if (lodepng_addofl(a, b, &d)) return 1;
- return d > c;
-}
-
-
-/*
- Often in case of an error a value is assigned to a variable and then it breaks
- out of a loop (to go to the cleanup phase of a function). This macro does that.
- It makes the error handling code shorter and more readable.
-
- Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83);
-*/
-#define CERROR_BREAK(errorvar, code){\
- errorvar = code;\
- break;\
-}
-
-/* version of CERROR_BREAK that assumes the common case where the error variable is named "error" */
-#define ERROR_BREAK(code) CERROR_BREAK(error, code)
-
-/* Set error var to the error code, and return it.*/
-#define CERROR_RETURN_ERROR(errorvar, code){\
- errorvar = code;\
- return code;\
-}
-
-/* Try the code, if it returns error, also return the error. */
-#define CERROR_TRY_RETURN(call){\
- unsigned error = call;\
- if(error) return error;\
-}
-
-/* Set error var to the error code, and return from the void function. */
-#define CERROR_RETURN(errorvar, code){\
- errorvar = code;\
- return;\
-}
-
-
-/* dynamic vector of unsigned chars */
-struct ucvector
-{
- unsigned char* data;
- size_t size; /*used size*/
- size_t allocsize; /*allocated size*/
-};
-
-
-/* returns 1 if success, 0 if failure ==> nothing done */
-static unsigned ucvector_resize(ucvector* p, size_t size)
-{
- if (size > p->allocsize) {
- size_t newsize = size + (p->allocsize >> 1u);
- void* data = realloc(p->data, newsize);
- if(data) {
- p->allocsize = newsize;
- p->data = (unsigned char*)data;
- }
- else return 0; /*error: not enough memory*/
- }
- p->size = size;
- return 1; /*success*/
-}
-
-
-static ucvector ucvector_init(unsigned char* buffer, size_t size)
-{
- ucvector v;
- v.data = buffer;
- v.allocsize = v.size = size;
- return v;
-}
-
-
-static unsigned lodepng_read32bitInt(const unsigned char* buffer)
-{
- return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) | ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* ////////////////////////////////////////////////////////////////////////// */
-/* // End of common code and tools. Begin of Zlib related code. // */
-/* ////////////////////////////////////////////////////////////////////////// */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-struct LodePNGBitReader
-{
- const unsigned char* data;
- size_t size; /*size of data in bytes*/
- size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/
- size_t bp;
- unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/
-};
-
-
-/* data size argument is in bytes. Returns error if size too large causing overflow */
-static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size)
-{
- size_t temp;
- reader->data = data;
- reader->size = size;
- /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */
- if (lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;
- /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and
- trying to ensure 32 more bits*/
- if (lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;
- reader->bp = 0;
- reader->buffer = 0;
- return 0; /*ok*/
- }
-
-/*
- ensureBits functions:
- Ensures the reader can at least read nbits bits in one or more readBits calls,
- safely even if not enough bits are available.
- Returns 1 if there are enough bits available, 0 if not.
-*/
-
-/*See ensureBits documentation above. This one ensures exactly 1 bit */
-/*static unsigned ensureBits1(LodePNGBitReader* reader) {
- if(reader->bp >= reader->bitsize) return 0;
- reader->buffer = (unsigned)reader->data[reader->bp >> 3u] >> (reader->bp & 7u);
- return 1;
-}*/
-
-/*See ensureBits documentation above. This one ensures up to 9 bits */
-static unsigned ensureBits9(LodePNGBitReader* reader, size_t nbits)
-{
- size_t start = reader->bp >> 3u;
- size_t size = reader->size;
- if (start + 1u < size) {
- reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u);
- reader->buffer >>= (reader->bp & 7u);
- return 1;
- } else {
- reader->buffer = 0;
- if (start + 0u < size) reader->buffer |= reader->data[start + 0];
- reader->buffer >>= (reader->bp & 7u);
- return reader->bp + nbits <= reader->bitsize;
- }
-}
-
-
-/*See ensureBits documentation above. This one ensures up to 17 bits */
-static unsigned ensureBits17(LodePNGBitReader* reader, size_t nbits)
-{
- size_t start = reader->bp >> 3u;
- size_t size = reader->size;
- if (start + 2u < size) {
- reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u);
- reader->buffer >>= (reader->bp & 7u);
- return 1;
- } else {
- reader->buffer = 0;
- if (start + 0u < size) reader->buffer |= reader->data[start + 0];
- if (start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
- reader->buffer >>= (reader->bp & 7u);
- return reader->bp + nbits <= reader->bitsize;
- }
-}
-
-
-/*See ensureBits documentation above. This one ensures up to 25 bits */
-static LODEPNG_INLINE unsigned ensureBits25(LodePNGBitReader* reader, size_t nbits)
-{
- size_t start = reader->bp >> 3u;
- size_t size = reader->size;
- if (start + 3u < size) {
- reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
- reader->buffer >>= (reader->bp & 7u);
- return 1;
- } else {
- reader->buffer = 0;
- if (start + 0u < size) reader->buffer |= reader->data[start + 0];
- if (start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
- if (start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
- reader->buffer >>= (reader->bp & 7u);
- return reader->bp + nbits <= reader->bitsize;
- }
-}
-
-
-/*See ensureBits documentation above. This one ensures up to 32 bits */
-static LODEPNG_INLINE unsigned ensureBits32(LodePNGBitReader* reader, size_t nbits)
-{
- size_t start = reader->bp >> 3u;
- size_t size = reader->size;
- if(start + 4u < size) {
- reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
- reader->buffer >>= (reader->bp & 7u);
- reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u)));
- return 1;
- } else {
- reader->buffer = 0;
- if (start + 0u < size) reader->buffer |= reader->data[start + 0];
- if (start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
- if (start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
- if (start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u);
- reader->buffer >>= (reader->bp & 7u);
- return reader->bp + nbits <= reader->bitsize;
- }
-}
-
-
-/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */
-static unsigned peekBits(LodePNGBitReader* reader, size_t nbits)
-{
- /* The shift allows nbits to be only up to 31. */
- return reader->buffer & ((1u << nbits) - 1u);
-}
-
-
-/* Must have enough bits available with ensureBits */
-static void advanceBits(LodePNGBitReader* reader, size_t nbits)
-{
- reader->buffer >>= nbits;
- reader->bp += nbits;
-}
-
-
-/* Must have enough bits available with ensureBits */
-static unsigned readBits(LodePNGBitReader* reader, size_t nbits)
-{
- unsigned result = peekBits(reader, nbits);
- advanceBits(reader, nbits);
- return result;
-}
-
-
-/* Public for testing only. steps and result must have numsteps values. */
-unsigned lode_png_test_bitreader(const unsigned char* data, size_t size, size_t numsteps, const size_t* steps, unsigned* result)
-{
- size_t i;
- LodePNGBitReader reader;
- unsigned error = LodePNGBitReader_init(&reader, data, size);
- if (error) return 0;
- for (i = 0; i < numsteps; i++) {
- size_t step = steps[i];
- unsigned ok;
- if (step > 25) ok = ensureBits32(&reader, step);
- else if (step > 17) ok = ensureBits25(&reader, step);
- else if (step > 9) ok = ensureBits17(&reader, step);
- else ok = ensureBits9(&reader, step);
- if (!ok) return 0;
- result[i] = readBits(&reader, step);
- }
- return 1;
-}
-
-
-static unsigned reverseBits(unsigned bits, unsigned num)
-{
- /*TODO: implement faster lookup table based version when needed*/
- unsigned i, result = 0;
- for (i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;
- return result;
-}
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Deflate - Huffman / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-#define FIRST_LENGTH_CODE_INDEX 257
-#define LAST_LENGTH_CODE_INDEX 285
-/*256 literals, the end code, some length codes, and 2 unused codes*/
-#define NUM_DEFLATE_CODE_SYMBOLS 288
-/*the distance codes have their own symbols, 30 used, 2 unused*/
-#define NUM_DISTANCE_SYMBOLS 32
-/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
-#define NUM_CODE_LENGTH_CODES 19
-
-/*the base lengths represented by codes 257-285*/
-static const unsigned LENGTHBASE[29]
- = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
- 67, 83, 99, 115, 131, 163, 195, 227, 258};
-
-/*the extra bits used by codes 257-285 (added to base length)*/
-static const unsigned LENGTHEXTRA[29]
- = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
- 4, 4, 4, 4, 5, 5, 5, 5, 0};
-
-/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
-static const unsigned DISTANCEBASE[30]
- = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
- 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
-
-/*the extra bits of backwards distances (added to base)*/
-static const unsigned DISTANCEEXTRA[30]
- = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
- 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
-
-/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman
-tree of the dynamic huffman tree lengths is generated*/
-static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
- = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
-
-/* ////////////////////////////////////////////////////////////////////////// */
-
-/*
-Huffman tree struct, containing multiple representations of the tree
-*/
-struct HuffmanTree
-{
- unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/
- unsigned* lengths; /*the lengths of the huffman codes*/
- unsigned maxbitlen; /*maximum number of bits a single code can get*/
- unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
- /* for reading only */
- unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/
- unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/
-};
-
-
-static void HuffmanTree_init(HuffmanTree* tree)
-{
- tree->codes = 0;
- tree->lengths = 0;
- tree->table_len = 0;
- tree->table_value = 0;
-}
-
-
-static void HuffmanTree_cleanup(HuffmanTree* tree)
-{
- free(tree->codes);
- free(tree->lengths);
- free(tree->table_len);
- free(tree->table_value);
-}
-
-
-/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/
-/* values 8u and 9u work the fastest */
-#define FIRSTBITS 9u
-
-/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination,
-which is possible in case of only 0 or 1 present symbols. */
-#define INVALIDSYMBOL 65535u
-
-/* make table for huffman decoding */
-static unsigned HuffmanTree_makeTable(HuffmanTree* tree)
-{
- static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/
- static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;
- size_t i, numpresent, pointer, size; /*total table size*/
- unsigned* maxlens = (unsigned*)malloc(headsize * sizeof(unsigned));
- if (!maxlens) return 83; /*alloc fail*/
-
- /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/
- lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens));
- for (i = 0; i < tree->numcodes; i++) {
- unsigned symbol = tree->codes[i];
- unsigned l = tree->lengths[i];
- unsigned index;
- if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/
- /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/
- index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);
- maxlens[index] = LODEPNG_MAX(maxlens[index], l);
- }
- /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */
- size = headsize;
- for (i = 0; i < headsize; ++i) {
- unsigned l = maxlens[i];
- if (l > FIRSTBITS) size += (1u << (l - FIRSTBITS));
- }
- tree->table_len = (unsigned char*)malloc(size * sizeof(*tree->table_len));
- tree->table_value = (unsigned short*)malloc(size * sizeof(*tree->table_value));
- if (!tree->table_len || !tree->table_value) {
- free(maxlens);
- /* freeing tree->table values is done at a higher scope */
- return 83; /*alloc fail*/
- }
- /*initialize with an invalid length to indicate unused entries*/
- for (i = 0; i < size; ++i) tree->table_len[i] = 16;
-
- /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/
- pointer = headsize;
- for (i = 0; i < headsize; ++i) {
- unsigned l = maxlens[i];
- if(l <= FIRSTBITS) continue;
- tree->table_len[i] = l;
- tree->table_value[i] = pointer;
- pointer += (1u << (l - FIRSTBITS));
- }
- free(maxlens);
-
- /*fill in the first table for short symbols, or secondary table for long symbols*/
- numpresent = 0;
- for (i = 0; i < tree->numcodes; ++i) {
- unsigned l = tree->lengths[i];
- unsigned symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/
- /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/
- unsigned reverse = reverseBits(symbol, l);
- if (l == 0) continue;
- numpresent++;
-
- if (l <= FIRSTBITS) {
- /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/
- unsigned num = 1u << (FIRSTBITS - l);
- unsigned j;
- for (j = 0; j < num; ++j) {
- /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/
- unsigned index = reverse | (j << l);
- if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
- tree->table_len[index] = l;
- tree->table_value[index] = i;
- }
- } else {
- /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/
- /*the FIRSTBITS MSBs of the symbol are the first table index*/
- unsigned index = reverse & mask;
- unsigned maxlen = tree->table_len[index];
- /*log2 of secondary table length, should be >= l - FIRSTBITS*/
- unsigned tablelen = maxlen - FIRSTBITS;
- unsigned start = tree->table_value[index]; /*starting index in secondary table*/
- unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/
- unsigned j;
- if (maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
- for (j = 0; j < num; ++j) {
- unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */
- unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));
- tree->table_len[index2] = l;
- tree->table_value[index2] = i;
- }
- }
- }
-
- if (numpresent < 2) {
- /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits,
- but deflate uses 1 bit instead. In case of 0 symbols, no symbols can
- appear at all, but such huffman tree could still exist (e.g. if distance
- codes are never used). In both cases, not all symbols of the table will be
- filled in. Fill them in with an invalid symbol value so returning them from
- huffmanDecodeSymbol will cause error. */
- for (i = 0; i < size; ++i) {
- if (tree->table_len[i] == 16) {
- /* As length, use a value smaller than FIRSTBITS for the head table,
- and a value larger than FIRSTBITS for the secondary table, to ensure
- valid behavior for advanceBits when reading this symbol. */
- tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1);
- tree->table_value[i] = INVALIDSYMBOL;
- }
- }
- } else {
- /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
- If that is not the case (due to too long length codes), the table will not
- have been fully used, and this is an error (not all bit combinations can be
- decoded): an oversubscribed huffman tree, indicated by error 55. */
- for (i = 0; i < size; ++i) {
- if (tree->table_len[i] == 16) return 55;
- }
- }
- return 0;
-}
-
-
-/*
- Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
- numcodes, lengths and maxbitlen must already be filled in correctly. return
- value is error.
-*/
-static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
-{
- unsigned* blcount;
- unsigned* nextcode;
- unsigned error = 0;
- unsigned bits, n;
-
- tree->codes = (unsigned*)malloc(tree->numcodes * sizeof(unsigned));
- blcount = (unsigned*)malloc((tree->maxbitlen + 1) * sizeof(unsigned));
- nextcode = (unsigned*)malloc((tree->maxbitlen + 1) * sizeof(unsigned));
- if (!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/
-
- if (!error) {
- for (n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;
- /*step 1: count number of instances of each code length*/
- for (bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];
- /*step 2: generate the nextcode values*/
- for(bits = 1; bits <= tree->maxbitlen; ++bits) {
- nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u;
- }
- /*step 3: generate all the codes*/
- for (n = 0; n != tree->numcodes; ++n) {
- if (tree->lengths[n] != 0) {
- tree->codes[n] = nextcode[tree->lengths[n]]++;
- /*remove superfluous bits from the code*/
- tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);
- }
- }
- }
-
- free(blcount);
- free(nextcode);
-
- if (!error) error = HuffmanTree_makeTable(tree);
- return error;
-}
-
-
-/*
- given the code lengths (as stored in the PNG file), generate the tree as defined
- by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
- return value is error.
-*/
-static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, size_t numcodes, unsigned maxbitlen)
-{
- unsigned i;
- tree->lengths = (unsigned*)malloc(numcodes * sizeof(unsigned));
- if (!tree->lengths) return 83; /*alloc fail*/
- for (i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
- tree->numcodes = (unsigned)numcodes; /*number of symbols*/
- tree->maxbitlen = maxbitlen;
- return HuffmanTree_makeFromLengths2(tree);
-}
-
-
-/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
-static unsigned generateFixedLitLenTree(HuffmanTree* tree)
-{
- unsigned i, error = 0;
- unsigned* bitlen = (unsigned*)malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
- if (!bitlen) return 83; /*alloc fail*/
-
- /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
- for (i = 0; i <= 143; ++i) bitlen[i] = 8;
- for (i = 144; i <= 255; ++i) bitlen[i] = 9;
- for (i = 256; i <= 279; ++i) bitlen[i] = 7;
- for (i = 280; i <= 287; ++i) bitlen[i] = 8;
-
- error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
-
- free(bitlen);
- return error;
-}
-
-
-/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
-static unsigned generateFixedDistanceTree(HuffmanTree* tree)
-{
- unsigned i, error = 0;
- unsigned* bitlen = (unsigned*)malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
- if (!bitlen) return 83; /*alloc fail*/
-
- /*there are 32 distance codes, but 30-31 are unused*/
- for (i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
- error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
-
- free(bitlen);
- return error;
-}
-
-
-/*
- returns the code. The bit reader must already have been ensured at least 15 bits
-*/
-static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree)
-{
- unsigned short code = peekBits(reader, FIRSTBITS);
- unsigned short l = codetree->table_len[code];
- unsigned short value = codetree->table_value[code];
- if (l <= FIRSTBITS) {
- advanceBits(reader, l);
- return value;
- } else {
- unsigned index2;
- advanceBits(reader, FIRSTBITS);
- index2 = value + peekBits(reader, l - FIRSTBITS);
- advanceBits(reader, codetree->table_len[index2] - FIRSTBITS);
- return codetree->table_value[index2];
- }
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Inflator (Decompressor) / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-/*get the tree of a deflated block with fixed tree, as specified in the deflate specification
-Returns error code.*/
-static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
-{
- unsigned error = generateFixedLitLenTree(tree_ll);
- if (error) return error;
- return generateFixedDistanceTree(tree_d);
-}
-
-
-/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
-static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, LodePNGBitReader* reader)
-{
- /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
- unsigned error = 0;
- unsigned n, HLIT, HDIST, HCLEN, i;
-
- /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
- unsigned* bitlen_ll = 0; /*lit,len code lengths*/
- unsigned* bitlen_d = 0; /*dist code lengths*/
- /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
- unsigned* bitlen_cl = 0;
- HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
-
- if (!ensureBits17(reader, 14)) return 49; /*error: the bit pointer is or will go past the memory*/
-
- /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
- HLIT = readBits(reader, 5) + 257;
- /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
- HDIST = readBits(reader, 5) + 1;
- /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
- HCLEN = readBits(reader, 4) + 4;
-
- bitlen_cl = (unsigned*)malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
- if(!bitlen_cl) return 83 /*alloc fail*/;
-
- HuffmanTree_init(&tree_cl);
-
- while (!error) {
- /*read the code length codes out of 3 * (amount of code length codes) bits*/
- if (lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {
- ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/
- }
- for (i = 0; i != HCLEN; ++i) {
- ensureBits9(reader, 3); /*out of bounds already checked above */
- bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);
- }
- for (i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {
- bitlen_cl[CLCL_ORDER[i]] = 0;
- }
-
- error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
- if(error) break;
-
- /*now we can use this tree to read the lengths for the tree that this function will return*/
- bitlen_ll = (unsigned*)malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
- bitlen_d = (unsigned*)malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
- if (!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
- lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll));
- lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d));
-
- /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
- i = 0;
- while (i < HLIT + HDIST) {
- unsigned code;
- ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/
- code = huffmanDecodeSymbol(reader, &tree_cl);
- if (code <= 15) /*a length code*/ {
- if (i < HLIT) bitlen_ll[i] = code;
- else bitlen_d[i - HLIT] = code;
- ++i;
- } else if (code == 16) /*repeat previous*/ {
- unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
- unsigned value; /*set value to the previous code*/
-
- if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
-
- replength += readBits(reader, 2);
-
- if (i < HLIT + 1) value = bitlen_ll[i - 1];
- else value = bitlen_d[i - HLIT - 1];
- /*repeat this value in the next lengths*/
- for (n = 0; n < replength; ++n) {
- if (i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
- if (i < HLIT) bitlen_ll[i] = value;
- else bitlen_d[i - HLIT] = value;
- ++i;
- }
- } else if(code == 17) /*repeat "0" 3-10 times*/ {
- unsigned replength = 3; /*read in the bits that indicate repeat length*/
- replength += readBits(reader, 3);
-
- /*repeat this value in the next lengths*/
- for (n = 0; n < replength; ++n) {
- if (i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
-
- if (i < HLIT) bitlen_ll[i] = 0;
- else bitlen_d[i - HLIT] = 0;
- ++i;
- }
- } else if(code == 18) /*repeat "0" 11-138 times*/ {
- unsigned replength = 11; /*read in the bits that indicate repeat length*/
- replength += readBits(reader, 7);
-
- /*repeat this value in the next lengths*/
- for (n = 0; n < replength; ++n) {
- if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
-
- if(i < HLIT) bitlen_ll[i] = 0;
- else bitlen_d[i - HLIT] = 0;
- ++i;
- }
- } else /*if(code == INVALIDSYMBOL)*/ {
- ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
- }
- /*check if any of the ensureBits above went out of bounds*/
- if (reader->bp > reader->bitsize) {
- /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
- (10=no endcode, 11=wrong jump outside of tree)*/
- /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
- ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
- }
- }
- if (error) break;
-
- if (bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
-
- /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
- error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
- if (error) break;
- error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
-
- break; /*end of error-while*/
- }
-
- free(bitlen_cl);
- free(bitlen_ll);
- free(bitlen_d);
- HuffmanTree_cleanup(&tree_cl);
-
- return error;
-}
-
-
-/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/
-static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader, unsigned btype)
-{
- unsigned error = 0;
- HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
- HuffmanTree tree_d; /*the huffman tree for distance codes*/
-
- HuffmanTree_init(&tree_ll);
- HuffmanTree_init(&tree_d);
-
- if (btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d);
- else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);
-
- while (!error) /*decode all symbols until end reached, breaks at end code*/ {
- /*code_ll is literal, length or end code*/
- unsigned code_ll;
- ensureBits25(reader, 20); /* up to 15 for the huffman symbol, up to 5 for the length extra bits */
- code_ll = huffmanDecodeSymbol(reader, &tree_ll);
- if (code_ll <= 255) /*literal symbol*/ {
- if (!ucvector_resize(out, out->size + 1)) ERROR_BREAK(83 /*alloc fail*/);
- out->data[out->size - 1] = (unsigned char)code_ll;
- } else if (code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {
- unsigned code_d, distance;
- unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
- size_t start, backward, length;
-
- /*part 1: get length base*/
- length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
-
- /*part 2: get extra bits and add the value of that to length*/
- numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
- if (numextrabits_l != 0) {
- /* bits already ensured above */
- length += readBits(reader, numextrabits_l);
- }
-
- /*part 3: get distance code*/
- ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */
- code_d = huffmanDecodeSymbol(reader, &tree_d);
- if (code_d > 29) {
- if (code_d <= 31) {
- ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/
- } else /* if(code_d == INVALIDSYMBOL) */{
- ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
- }
- }
- distance = DISTANCEBASE[code_d];
-
- /*part 4: get extra bits from distance*/
- numextrabits_d = DISTANCEEXTRA[code_d];
- if (numextrabits_d != 0) {
- /* bits already ensured above */
- distance += readBits(reader, numextrabits_d);
- }
-
- /*part 5: fill in all the out[n] values based on the length and dist*/
- start = out->size;
- if (distance > start) ERROR_BREAK(52); /*too long backward distance*/
- backward = start - distance;
-
- if (!ucvector_resize(out, out->size + length)) ERROR_BREAK(83 /*alloc fail*/);
- if (distance < length) {
- size_t forward;
- lodepng_memcpy(out->data + start, out->data + backward, distance);
- start += distance;
- for (forward = distance; forward < length; ++forward) {
- out->data[start++] = out->data[backward++];
- }
- } else {
- lodepng_memcpy(out->data + start, out->data + backward, length);
- }
- } else if (code_ll == 256) {
- break; /*end code, break the loop*/
- } else /*if(code_ll == INVALIDSYMBOL)*/ {
- ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
- }
- /*check if any of the ensureBits above went out of bounds*/
- if (reader->bp > reader->bitsize) {
- /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
- (10=no endcode, 11=wrong jump outside of tree)*/
- /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
- ERROR_BREAK(51); /*error, bit pointer jumps past memory*/
- }
- }
-
- HuffmanTree_cleanup(&tree_ll);
- HuffmanTree_cleanup(&tree_d);
-
- return error;
-}
-
-
-static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader, const LodePNGDecompressSettings* settings)
-{
- size_t bytepos;
- size_t size = reader->size;
- unsigned LEN, NLEN, error = 0;
-
- /*go to first boundary of byte*/
- bytepos = (reader->bp + 7u) >> 3u;
-
- /*read LEN (2 bytes) and NLEN (2 bytes)*/
- if (bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/
- LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
- NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
-
- /*check if 16-bit NLEN is really the one's complement of LEN*/
- if (!settings->ignore_nlen && LEN + NLEN != 65535) {
- return 21; /*error: NLEN is not one's complement of LEN*/
- }
-
- if (!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/
-
- /*read the literal data: LEN bytes are now stored in the out buffer*/
- if (bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/
-
- lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN);
- bytepos += LEN;
-
- reader->bp = bytepos << 3u;
-
- return error;
-}
-
-
-static unsigned lodepng_inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings)
-{
- unsigned BFINAL = 0;
- LodePNGBitReader reader;
- unsigned error = LodePNGBitReader_init(&reader, in, insize);
-
- if (error) return error;
-
- while (!BFINAL) {
- unsigned BTYPE;
- if (!ensureBits9(&reader, 3)) return 52; /*error, bit pointer will jump past memory*/
- BFINAL = readBits(&reader, 1);
- BTYPE = readBits(&reader, 2);
-
- if (BTYPE == 3) return 20; /*error: invalid BTYPE*/
- else if (BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/
- else error = inflateHuffmanBlock(out, &reader, BTYPE); /*compression, BTYPE 01 or 10*/
-
- if (error) return error;
- }
-
- return error;
-}
-
-
-static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings)
-{
- if (settings->custom_inflate) {
- unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings);
- out->allocsize = out->size;
- return error;
- } else {
- return lodepng_inflatev(out, in, insize, settings);
- }
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Adler32 / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
-{
- unsigned s1 = adler & 0xffffu;
- unsigned s2 = (adler >> 16u) & 0xffffu;
-
- while (len != 0u) {
- unsigned i;
- /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
- unsigned amount = len > 5552u ? 5552u : len;
- len -= amount;
- for (i = 0; i != amount; ++i) {
- s1 += (*data++);
- s2 += s1;
- }
- s1 %= 65521u;
- s2 %= 65521u;
- }
-
- return (s2 << 16u) | s1;
-}
-
-/*Return the adler32 of the bytes data[0..len-1]*/
-static unsigned adler32(const unsigned char* data, unsigned len)
-{
- return update_adler32(1u, data, len);
-}
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Zlib / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-static unsigned lodepng_zlib_decompressv(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings)
-{
- unsigned error = 0;
- unsigned CM, CINFO, FDICT;
-
- if (insize < 2) return 53; /*error, size of zlib data too small*/
- /*read information from zlib header*/
- if ((in[0] * 256 + in[1]) % 31 != 0) {
- /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
- return 24;
- }
-
- CM = in[0] & 15;
- CINFO = (in[0] >> 4) & 15;
- /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
- FDICT = (in[1] >> 5) & 1;
- /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
-
- if (CM != 8 || CINFO > 7) {
- /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
- return 25;
- }
- if (FDICT != 0) {
- /*error: the specification of PNG says about the zlib stream:
- "The additional flags shall not specify a preset dictionary."*/
- return 26;
- }
-
- error = inflatev(out, in + 2, insize - 2, settings);
- if (error) return error;
-
- if (!settings->ignore_adler32) {
- unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
- unsigned checksum = adler32(out->data, (unsigned)(out->size));
- if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
- }
-
- return 0; /*no error*/
-}
-
-
-/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */
-static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings)
-{
- if(settings->custom_zlib) {
- return settings->custom_zlib(out, outsize, in, insize, settings);
- } else {
- unsigned error;
- ucvector v = ucvector_init(*out, *outsize);
- if (expected_size) {
- /*reserve the memory to avoid intermediate reallocations*/
- ucvector_resize(&v, *outsize + expected_size);
- v.size = *outsize;
- }
- error = lodepng_zlib_decompressv(&v, in, insize, settings);
- *out = v.data;
- *outsize = v.size;
- return error;
- }
-}
-
-
-static void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
-{
- settings->ignore_adler32 = 0;
- settings->ignore_nlen = 0;
- settings->custom_zlib = 0;
- settings->custom_inflate = 0;
- settings->custom_context = 0;
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* ////////////////////////////////////////////////////////////////////////// */
-/* // End of Zlib related code. Begin of PNG related code. // */
-/* ////////////////////////////////////////////////////////////////////////// */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-
-#if 0 //thorvg don't use crc
-/* CRC polynomial: 0xedb88320 */
-static unsigned lodepng_crc32_table[256] = {
- 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
- 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
- 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
- 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
- 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
- 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
- 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
- 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
- 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
- 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
- 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
- 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
- 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
- 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
- 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
- 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
- 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
- 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
- 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
- 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
- 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
- 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
- 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
- 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
- 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
- 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
- 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
- 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
- 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
- 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
- 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
- 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
-};
-
-
-/* Calculate CRC32 of buffer
- Return the CRC of the bytes buf[0..len-1]. */
-static unsigned lodepng_crc32(const unsigned char* data, size_t length)
-{
- unsigned r = 0xffffffffu;
- size_t i;
- for (i = 0; i < length; ++i) {
- r = lodepng_crc32_table[(r ^ data[i]) & 0xffu] ^ (r >> 8u);
- }
- return r ^ 0xffffffffu;
-}
-#endif
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Reading and writing PNG color channel bits / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,
-so LodePNGBitWriter and LodePNGBitReader can't be used for those. */
-
-static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
-{
- unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
- ++(*bitpointer);
- return result;
-}
-
-
-/* TODO: make this faster */
-static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
-{
- unsigned result = 0;
- size_t i;
- for (i = 0 ; i < nbits; ++i) {
- result <<= 1u;
- result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
- }
- return result;
-}
-
-
-static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
-{
- /*the current bit in bitstream may be 0 or 1 for this to work*/
- if (bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u))));
- else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u)));
- ++(*bitpointer);
-}
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / PNG chunks / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-/*
- The lodepng_chunk functions are normally not needed, except to traverse the
- unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
- It also allows traversing the chunks of an encoded PNG file yourself.
-
- The chunk pointer always points to the beginning of the chunk itself, that is
- the first byte of the 4 length bytes.
-
- In the PNG file format, chunks have the following format:
- -4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)
- -4 bytes chunk type (ASCII a-z,A-Z only, see below)
- -length bytes of data (may be 0 bytes if length was 0)
- -4 bytes of CRC, computed on chunk name + data
-
- The first chunk starts at the 8th byte of the PNG file, the entire rest of the file
- exists out of concatenated chunks with the above format.
-
- PNG standard chunk ASCII naming conventions:
- -First byte: uppercase = critical, lowercase = ancillary
- -Second byte: uppercase = public, lowercase = private
- -Third byte: must be uppercase
- -Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
-*/
-
-
-/*
- Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
- There must be at least 4 bytes to read from. If the result value is too large,
- it may be corrupt data.
-*/
-static unsigned lodepng_chunk_length(const unsigned char* chunk)
-{
- return lodepng_read32bitInt(&chunk[0]);
-}
-
-
-/* check if the type is the given type */
-static unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
-{
- if (lodepng_strlen(type) != 4) return 0;
- return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
-}
-
-
-/* 0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard) */
-static unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
-{
- return ((chunk[4] & 32) != 0);
-}
-
-
-static const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
-{
- return &chunk[8];
-}
-
-#if 0 //thorvg don't use crc
-/* returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!) */
-static unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
-{
- unsigned length = lodepng_chunk_length(chunk);
- unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
- /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
- unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
- if (CRC != checksum) return 1;
- else return 0;
-}
-#endif
-
-static const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end)
-{
- if (chunk >= end || end - chunk < 12) return end; /*too small to contain a chunk*/
- if (chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
- && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
- /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
- return chunk + 8;
- } else {
- size_t total_chunk_length;
- const unsigned char* result;
- if (lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;
- result = chunk + total_chunk_length;
- if (result < chunk) return end; /*pointer overflow*/
- return result;
- }
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / Color types, channels, bits / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.
-Return value is a LodePNG error code.*/
-static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd)
-{
- switch(colortype) {
- case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break;
- case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break;
- case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break;
- case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break;
- case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break;
- case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */
- default: return 31; /* invalid color type */
- }
- return 0; /*allowed color type / bits combination*/
-}
-
-
-static unsigned getNumColorChannels(LodePNGColorType colortype)
-{
- switch(colortype) {
- case LCT_GREY: return 1;
- case LCT_RGB: return 3;
- case LCT_PALETTE: return 1;
- case LCT_GREY_ALPHA: return 2;
- case LCT_RGBA: return 4;
- case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */
- default: return 0; /*invalid color type*/
- }
-}
-
-
-static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
-{
- /*bits per pixel is amount of channels * bits per channel*/
- return getNumColorChannels(colortype) * bitdepth;
-}
-
-
-static void lodepng_color_mode_init(LodePNGColorMode* info)
-{
- info->key_defined = 0;
- info->key_r = info->key_g = info->key_b = 0;
- info->colortype = LCT_RGBA;
- info->bitdepth = 8;
- info->palette = 0;
- info->palettesize = 0;
-}
-
-
-/*allocates palette memory if needed, and initializes all colors to black*/
-static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info)
-{
- size_t i;
- /*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/
- /*the palette must have room for up to 256 colors with 4 bytes each.*/
- if (!info->palette) info->palette = (unsigned char*)malloc(1024);
- if (!info->palette) return; /*alloc fail*/
- for (i = 0; i != 256; ++i) {
- /*Initialize all unused colors with black, the value used for invalid palette indices.
- This is an error according to the PNG spec, but common PNG decoders make it black instead.
- That makes color conversion slightly faster due to no error handling needed.*/
- info->palette[i * 4 + 0] = 0;
- info->palette[i * 4 + 1] = 0;
- info->palette[i * 4 + 2] = 0;
- info->palette[i * 4 + 3] = 255;
- }
-}
-
-static void lodepng_palette_clear(LodePNGColorMode* info)
-{
- if (info->palette) free(info->palette);
- info->palette = 0;
- info->palettesize = 0;
-}
-
-
-static void lodepng_color_mode_cleanup(LodePNGColorMode* info)
-{
- lodepng_palette_clear(info);
-}
-
-
-/*return value is error code (0 means no error)*/
-static unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
-{
- lodepng_color_mode_cleanup(dest);
- lodepng_memcpy(dest, source, sizeof(LodePNGColorMode));
- if (source->palette) {
- dest->palette = (unsigned char*)malloc(1024);
- if (!dest->palette && source->palettesize) return 83; /*alloc fail*/
- lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4);
- }
- return 0;
-}
-
-
-static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
-{
- size_t i;
- if (a->colortype != b->colortype) return 0;
- if (a->bitdepth != b->bitdepth) return 0;
- if (a->key_defined != b->key_defined) return 0;
- if (a->key_defined) {
- if(a->key_r != b->key_r) return 0;
- if(a->key_g != b->key_g) return 0;
- if(a->key_b != b->key_b) return 0;
- }
- if (a->palettesize != b->palettesize) return 0;
- for (i = 0; i != a->palettesize * 4; ++i) {
- if (a->palette[i] != b->palette[i]) return 0;
- }
- return 1;
-}
-
-
-static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
-{
- size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
- size_t n = (size_t)w * (size_t)h;
- return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;
-}
-
-
-/* Returns the byte size of a raw image buffer with given width, height and color mode */
-static size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
-{
- return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
-}
-
-
-/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
-and in addition has one extra byte per line: the filter byte. So this gives a larger
-result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */
-static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp)
-{
- /* + 1 for the filter byte, and possibly plus padding bits per line. */
- /* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */
- size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;
- return (size_t)h * line;
-}
-
-
-/* Safely checks whether size_t overflow can be caused due to amount of pixels.
- This check is overcautious rather than precise. If this check indicates no overflow,
- you can safely compute in a size_t (but not an unsigned):
- -(size_t)w * (size_t)h * 8
- -amount of bytes in IDAT (including filter, padding and Adam7 bytes)
- -amount of bytes in raw color model
- Returns 1 if overflow possible, 0 if not. */
-static int lodepng_pixel_overflow(unsigned w, unsigned h, const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor)
-{
- size_t bpp = LODEPNG_MAX(lodepng_get_bpp_lct(pngcolor->colortype, pngcolor->bitdepth), lodepng_get_bpp_lct(rawcolor->colortype, rawcolor->bitdepth));
- size_t numpixels, total;
- size_t line; /* bytes per line in worst case */
-
- if (lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
- if (lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
-
- /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */
- if (lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;
- if (lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;
-
- if (lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
- if (lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
-
- return 0; /* no overflow */
-}
-
-
-static void lodepng_info_init(LodePNGInfo* info)
-{
- lodepng_color_mode_init(&info->color);
- info->interlace_method = 0;
- info->compression_method = 0;
- info->filter_method = 0;
-}
-
-
-static void lodepng_info_cleanup(LodePNGInfo* info)
-{
- lodepng_color_mode_cleanup(&info->color);
-}
-
-
-/* index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to */
-static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
-{
- unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
- /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
- unsigned p = index & m;
- in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
- in = in << (bits * (m - p));
- if(p == 0) out[index * bits / 8u] = in;
- else out[index * bits / 8u] |= in;
-}
-
-/*
- One node of a color tree
- This is the data structure used to count the number of unique colors and to get a palette
- index for a color. It's like an octree, but because the alpha channel is used too, each
- node has 16 instead of 8 children.
-*/
-struct ColorTree
-{
- ColorTree* children[16]; /* up to 16 pointers to ColorTree of next level */
- int index; /* the payload. Only has a meaningful value if this is in the last level */
-};
-
-static void color_tree_init(ColorTree* tree)
-{
- lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children));
- tree->index = -1;
-}
-
-static void color_tree_cleanup(ColorTree* tree)
-{
- int i;
- for (i = 0; i != 16; ++i) {
- if(tree->children[i]) {
- color_tree_cleanup(tree->children[i]);
- free(tree->children[i]);
- }
- }
-}
-
-
-/* returns -1 if color not present, its index otherwise */
-static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
-{
- int bit = 0;
- for (bit = 0; bit < 8; ++bit) {
- int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
- if (!tree->children[i]) return -1;
- else tree = tree->children[i];
- }
- return tree ? tree->index : -1;
-}
-
-
-/* color is not allowed to already exist.
- Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")
- Returns error code, or 0 if ok */
-static unsigned color_tree_add(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
-{
- int bit;
- for (bit = 0; bit < 8; ++bit) {
- int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
- if (!tree->children[i]) {
- tree->children[i] = (ColorTree*)malloc(sizeof(ColorTree));
- if (!tree->children[i]) return 83; /*alloc fail*/
- color_tree_init(tree->children[i]);
- }
- tree = tree->children[i];
- }
- tree->index = (int)index;
- return 0;
-}
-
-/* put a pixel, given its RGBA color, into image of any color type */
-static unsigned rgba8ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
-{
- if (mode->colortype == LCT_GREY) {
- unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
- if (mode->bitdepth == 8) out[i] = gray;
- else if (mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
- else {
- /*take the most significant bits of gray*/
- gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u);
- addColorBits(out, i, mode->bitdepth, gray);
- }
- } else if (mode->colortype == LCT_RGB) {
- if (mode->bitdepth == 8) {
- out[i * 3 + 0] = r;
- out[i * 3 + 1] = g;
- out[i * 3 + 2] = b;
- } else {
- out[i * 6 + 0] = out[i * 6 + 1] = r;
- out[i * 6 + 2] = out[i * 6 + 3] = g;
- out[i * 6 + 4] = out[i * 6 + 5] = b;
- }
- } else if(mode->colortype == LCT_PALETTE) {
- int index = color_tree_get(tree, r, g, b, a);
- if (index < 0) return 82; /*color not in palette*/
- if (mode->bitdepth == 8) out[i] = index;
- else addColorBits(out, i, mode->bitdepth, (unsigned)index);
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
- if (mode->bitdepth == 8) {
- out[i * 2 + 0] = gray;
- out[i * 2 + 1] = a;
- } else if (mode->bitdepth == 16) {
- out[i * 4 + 0] = out[i * 4 + 1] = gray;
- out[i * 4 + 2] = out[i * 4 + 3] = a;
- }
- } else if (mode->colortype == LCT_RGBA) {
- if (mode->bitdepth == 8) {
- out[i * 4 + 0] = r;
- out[i * 4 + 1] = g;
- out[i * 4 + 2] = b;
- out[i * 4 + 3] = a;
- } else {
- out[i * 8 + 0] = out[i * 8 + 1] = r;
- out[i * 8 + 2] = out[i * 8 + 3] = g;
- out[i * 8 + 4] = out[i * 8 + 5] = b;
- out[i * 8 + 6] = out[i * 8 + 7] = a;
- }
- }
- return 0; /*no error*/
-}
-
-
-/* put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type */
-static void rgba16ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, unsigned short r, unsigned short g, unsigned short b, unsigned short a)
-{
- if (mode->colortype == LCT_GREY) {
- unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
- out[i * 2 + 0] = (gray >> 8) & 255;
- out[i * 2 + 1] = gray & 255;
- } else if (mode->colortype == LCT_RGB) {
- out[i * 6 + 0] = (r >> 8) & 255;
- out[i * 6 + 1] = r & 255;
- out[i * 6 + 2] = (g >> 8) & 255;
- out[i * 6 + 3] = g & 255;
- out[i * 6 + 4] = (b >> 8) & 255;
- out[i * 6 + 5] = b & 255;
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
- out[i * 4 + 0] = (gray >> 8) & 255;
- out[i * 4 + 1] = gray & 255;
- out[i * 4 + 2] = (a >> 8) & 255;
- out[i * 4 + 3] = a & 255;
- } else if (mode->colortype == LCT_RGBA) {
- out[i * 8 + 0] = (r >> 8) & 255;
- out[i * 8 + 1] = r & 255;
- out[i * 8 + 2] = (g >> 8) & 255;
- out[i * 8 + 3] = g & 255;
- out[i * 8 + 4] = (b >> 8) & 255;
- out[i * 8 + 5] = b & 255;
- out[i * 8 + 6] = (a >> 8) & 255;
- out[i * 8 + 7] = a & 255;
- }
-}
-
-
-/* Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type. */
-static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode)
-{
- if (mode->colortype == LCT_GREY) {
- if (mode->bitdepth == 8) {
- *r = *g = *b = in[i];
- if (mode->key_defined && *r == mode->key_r) *a = 0;
- else *a = 255;
- } else if (mode->bitdepth == 16) {
- *r = *g = *b = in[i * 2 + 0];
- if (mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
- else *a = 255;
- } else {
- unsigned highest = ((1U << mode->bitdepth) - 1U); /* highest possible value for this bit depth */
- size_t j = i * mode->bitdepth;
- unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
- *r = *g = *b = (value * 255) / highest;
- if (mode->key_defined && value == mode->key_r) *a = 0;
- else *a = 255;
- }
- } else if (mode->colortype == LCT_RGB) {
- if (mode->bitdepth == 8) {
- *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
- if (mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
- else *a = 255;
- } else {
- *r = in[i * 6 + 0];
- *g = in[i * 6 + 2];
- *b = in[i * 6 + 4];
- if (mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
- && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
- && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
- else *a = 255;
- }
- } else if (mode->colortype == LCT_PALETTE) {
- unsigned index;
- if (mode->bitdepth == 8) index = in[i];
- else {
- size_t j = i * mode->bitdepth;
- index = readBitsFromReversedStream(&j, in, mode->bitdepth);
- }
- /* out of bounds of palette not checked: see lodepng_color_mode_alloc_palette. */
- *r = mode->palette[index * 4 + 0];
- *g = mode->palette[index * 4 + 1];
- *b = mode->palette[index * 4 + 2];
- *a = mode->palette[index * 4 + 3];
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- if (mode->bitdepth == 8) {
- *r = *g = *b = in[i * 2 + 0];
- *a = in[i * 2 + 1];
- } else {
- *r = *g = *b = in[i * 4 + 0];
- *a = in[i * 4 + 2];
- }
- } else if (mode->colortype == LCT_RGBA) {
- if (mode->bitdepth == 8) {
- *r = in[i * 4 + 0];
- *g = in[i * 4 + 1];
- *b = in[i * 4 + 2];
- *a = in[i * 4 + 3];
- } else {
- *r = in[i * 8 + 0];
- *g = in[i * 8 + 2];
- *b = in[i * 8 + 4];
- *a = in[i * 8 + 6];
- }
- }
-}
-
-
-/* Similar to getPixelColorRGBA8, but with all the for loops inside of the color
- mode test cases, optimized to convert the colors much faster, when converting
- to the common case of RGBA with 8 bit per channel. buffer must be RGBA with
- enough memory.*/
-static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, const unsigned char* LODEPNG_RESTRICT in, const LodePNGColorMode* mode)
-{
- unsigned num_channels = 4;
- size_t i;
- if (mode->colortype == LCT_GREY) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i];
- buffer[3] = 255;
- }
- if (mode->key_defined) {
- buffer -= numpixels * num_channels;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- if(buffer[0] == mode->key_r) buffer[3] = 0;
- }
- }
- } else if (mode->bitdepth == 16) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 2];
- buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
- }
- } else {
- unsigned highest = ((1U << mode->bitdepth) - 1U); /* highest possible value for this bit depth */
- size_t j = 0;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
- buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
- buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
- }
- }
- } else if (mode->colortype == LCT_RGB) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- //lodepng_memcpy(buffer, &in[i * 3], 3);
- //Convert colortype to LCT_BGR?
- buffer[0] = in[i * 3 + 2];
- buffer[1] = in[i * 3 + 1];
- buffer[2] = in[i * 3 + 0];
- buffer[3] = 255;
- }
- if (mode->key_defined) {
- buffer -= numpixels * num_channels;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- if (buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;
- }
- }
- } else {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = in[i * 6 + 0];
- buffer[1] = in[i * 6 + 2];
- buffer[2] = in[i * 6 + 4];
- buffer[3] = mode->key_defined
- && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
- && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
- && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
- }
- }
- } else if (mode->colortype == LCT_PALETTE) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned index = in[i];
- /* out of bounds of palette not checked: see lodepng_color_mode_alloc_palette. */
- lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
- }
- } else {
- size_t j = 0;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
- /* out of bounds of palette not checked: see lodepng_color_mode_alloc_palette. */
- lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
- }
- }
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
- buffer[3] = in[i * 2 + 1];
- }
- } else {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
- buffer[3] = in[i * 4 + 2];
- }
- }
- } else if (mode->colortype == LCT_RGBA) {
- if (mode->bitdepth == 8) {
- lodepng_memcpy(buffer, in, numpixels * 4);
- } else {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = in[i * 8 + 0];
- buffer[1] = in[i * 8 + 2];
- buffer[2] = in[i * 8 + 4];
- buffer[3] = in[i * 8 + 6];
- }
- }
- }
-}
-
-
-/* Similar to getPixelColorsRGBA8, but with 3-channel RGB output. */
-static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, const unsigned char* LODEPNG_RESTRICT in, const LodePNGColorMode* mode)
-{
- const unsigned num_channels = 3;
- size_t i;
- if (mode->colortype == LCT_GREY) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i];
- }
- } else if (mode->bitdepth == 16) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 2];
- }
- } else {
- unsigned highest = ((1U << mode->bitdepth) - 1U); /* highest possible value for this bit depth */
- size_t j = 0;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
- buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
- }
- }
- } else if (mode->colortype == LCT_RGB) {
- if (mode->bitdepth == 8) {
- lodepng_memcpy(buffer, in, numpixels * 3);
- } else {
- for(i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = in[i * 6 + 0];
- buffer[1] = in[i * 6 + 2];
- buffer[2] = in[i * 6 + 4];
- }
- }
- } else if (mode->colortype == LCT_PALETTE) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned index = in[i];
- /* out of bounds of palette not checked: see lodepng_color_mode_alloc_palette. */
- lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
- }
- } else {
- size_t j = 0;
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
- /* out of bounds of palette not checked: see lodepng_color_mode_alloc_palette. */
- lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
- }
- }
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- if (mode->bitdepth == 8) {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
- }
- } else {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
- }
- }
- } else if (mode->colortype == LCT_RGBA) {
- if (mode->bitdepth == 8) {
- for(i = 0; i != numpixels; ++i, buffer += num_channels) {
- lodepng_memcpy(buffer, &in[i * 4], 3);
- }
- } else {
- for (i = 0; i != numpixels; ++i, buffer += num_channels) {
- buffer[0] = in[i * 8 + 0];
- buffer[1] = in[i * 8 + 2];
- buffer[2] = in[i * 8 + 4];
- }
- }
- }
-}
-
-
-/* Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
- given color type, but the given color type must be 16-bit itself. */
-static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode)
-{
- if (mode->colortype == LCT_GREY) {
- *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
- if (mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
- else *a = 65535;
- } else if (mode->colortype == LCT_RGB) {
- *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
- *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
- *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
- if (mode->key_defined
- && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
- && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
- && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
- else *a = 65535;
- } else if (mode->colortype == LCT_GREY_ALPHA) {
- *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
- *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
- } else if (mode->colortype == LCT_RGBA) {
- *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
- *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
- *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
- *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
- }
-}
-
-/*
- Converts raw buffer from one color type to another color type, based on
- LodePNGColorMode structs to describe the input and output color type.
- See the reference manual at the end of this header file to see which color conversions are supported.
- return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
- The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
- of the output color type (lodepng_get_bpp).
- For < 8 bpp images, there should not be padding bits at the end of scanlines.
- For 16-bit per channel colors, uses big endian format like PNG does.
- Return value is LodePNG error code
-*/
-static unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h)
-{
- size_t i;
- ColorTree tree;
- size_t numpixels = (size_t)w * (size_t)h;
- unsigned error = 0;
-
- if (mode_in->colortype == LCT_PALETTE && !mode_in->palette) {
- return 107; /* error: must provide palette if input mode is palette */
- }
-
- if (lodepng_color_mode_equal(mode_out, mode_in)) {
- size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
- lodepng_memcpy(out, in, numbytes);
- return 0;
- }
-
- if (mode_out->colortype == LCT_PALETTE) {
- size_t palettesize = mode_out->palettesize;
- const unsigned char* palette = mode_out->palette;
- size_t palsize = (size_t)1u << mode_out->bitdepth;
- /* if the user specified output palette but did not give the values, assume
- they want the values of the input color type (assuming that one is palette).
- Note that we never create a new palette ourselves.*/
- if (palettesize == 0) {
- palettesize = mode_in->palettesize;
- palette = mode_in->palette;
- /* if the input was also palette with same bitdepth, then the color types are also
- equal, so copy literally. This to preserve the exact indices that were in the PNG
- even in case there are duplicate colors in the palette.*/
- if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
- size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
- lodepng_memcpy(out, in, numbytes);
- return 0;
- }
- }
- if (palettesize < palsize) palsize = palettesize;
- color_tree_init(&tree);
- for (i = 0; i != palsize; ++i) {
- const unsigned char* p = &palette[i * 4];
- error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
- if (error) break;
- }
- }
-
- if (!error) {
- if (mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
- for (i = 0; i != numpixels; ++i) {
- unsigned short r = 0, g = 0, b = 0, a = 0;
- getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
- rgba16ToPixel(out, i, mode_out, r, g, b, a);
- }
- } else if (mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
- getPixelColorsRGBA8(out, numpixels, in, mode_in);
- } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
- getPixelColorsRGB8(out, numpixels, in, mode_in);
- } else {
- unsigned char r = 0, g = 0, b = 0, a = 0;
- for (i = 0; i != numpixels; ++i) {
- getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
- error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
- if (error) break;
- }
- }
- }
-
- if (mode_out->colortype == LCT_PALETTE) {
- color_tree_cleanup(&tree);
- }
-
- return error;
-}
-
-
-/* Paeth predictor, used by PNG filter type 4
- The parameters are of type short, but should come from unsigned chars, the shorts
- are only needed to make the paeth calculation correct.
-*/
-static unsigned char paethPredictor(short a, short b, short c)
-{
- short pa = LODEPNG_ABS(b - c);
- short pb = LODEPNG_ABS(a - c);
- short pc = LODEPNG_ABS(a + b - c - c);
- /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */
- if (pb < pa) { a = b; pa = pb; }
- return (pc < pa) ? c : a;
-}
-
-
-/*shared values used by multiple Adam7 related functions*/
-static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
-static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
-static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
-static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
-
-/* Outputs various dimensions and positions in the image related to the Adam7 reduced images.
- passw: output containing the width of the 7 passes
- passh: output containing the height of the 7 passes
- filter_passstart: output containing the index of the start and end of each
- reduced image with filter bytes
- padded_passstart output containing the index of the start and end of each
- reduced image when without filter bytes but with padded scanlines
- passstart: output containing the index of the start and end of each reduced
- image without padding between scanlines, but still padding between the images
- w, h: width and height of non-interlaced image
- bpp: bits per pixel
- "padded" is only relevant if bpp is less than 8 and a scanline or image does not
- end at a full byte */
-static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
-{
- /* the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass */
- unsigned i;
-
- /* calculate width and height in pixels of each pass */
- for (i = 0; i != 7; ++i) {
- passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
- passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
- if(passw[i] == 0) passh[i] = 0;
- if(passh[i] == 0) passw[i] = 0;
- }
-
- filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
- for (i = 0; i != 7; ++i) {
- /* if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte) */
- filter_passstart[i + 1] = filter_passstart[i]
- + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);
- /* bits padded if needed to fill full byte at end of each scanline */
- padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);
- /* only padded at end of reduced image */
- passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;
- }
-}
-
-
-/* ////////////////////////////////////////////////////////////////////////// */
-/* / PNG Decoder / */
-/* ////////////////////////////////////////////////////////////////////////// */
-
-static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned char filterType, size_t length)
-{
- /* For PNG filter method 0
- unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
- the filter works byte per byte (bytewidth = 1)
- precon is the previous unfiltered scanline, recon the result, scanline the current one
- the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
- recon and scanline MAY be the same memory address! precon must be disjoint. */
-
- size_t i;
- switch (filterType) {
- case 0: {
- if (bytewidth == 4) {
- for (i = 0; i < length; i += 4) {
- //RGBA -> BGRA
- recon[i + 0] = scanline[i + 2];
- recon[i + 1] = scanline[i + 1];
- recon[i + 2] = scanline[i + 0];
- recon[i + 3] = scanline[i + 3];
- }
- } else {
- for (i = 0; i != length; ++i) recon[i] = scanline[i];
- }
- break;
- }
- case 1: {
- for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
- for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
- break;
- }
- case 2: {
- if (precon) {
- for (i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
- } else {
- for (i = 0; i != length; ++i) recon[i] = scanline[i];
- }
- break;
- }
- case 3: {
- if (precon) {
- for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);
- for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1u);
- } else {
- for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
- for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1u);
- }
- break;
- }
- case 4: {
- if (precon) {
- for (i = 0; i != bytewidth; ++i) {
- recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
- }
-
- /* Unroll independent paths of the paeth predictor. A 6x and 8x version would also be possible but that
- adds too much code. Whether this actually speeds anything up at all depends on compiler and settings. */
- if (bytewidth >= 4) {
- for (; i + 3 < length; i += 4) {
- size_t j = i - bytewidth;
- unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];
- unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];
- unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];
- unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2], q3 = precon[j + 3];
- recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
- recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
- recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
- recon[i + 3] = s3 + paethPredictor(r3, p3, q3);
- }
- } else if (bytewidth >= 3) {
- for (; i + 2 < length; i += 3) {
- size_t j = i - bytewidth;
- unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];
- unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];
- unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];
- unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2];
- recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
- recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
- recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
- }
- } else if (bytewidth >= 2) {
- for (; i + 1 < length; i += 2) {
- size_t j = i - bytewidth;
- unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];
- unsigned char r0 = recon[j + 0], r1 = recon[j + 1];
- unsigned char p0 = precon[i + 0], p1 = precon[i + 1];
- unsigned char q0 = precon[j + 0], q1 = precon[j + 1];
- recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
- recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
- }
- }
-
- for (; i != length; ++i) {
- recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
- }
- } else {
- for (i = 0; i != bytewidth; ++i) {
- recon[i] = scanline[i];
- }
- for (i = bytewidth; i < length; ++i) {
- /* paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth] */
- recon[i] = (scanline[i] + recon[i - bytewidth]);
- }
- }
- break;
- }
- default: return 36; /* error: invalid filter type given */
- }
- return 0;
-}
-
-
-static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
-{
- /* For PNG filter method 0
- this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
- out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
- w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
- in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) */
-
- unsigned y;
- unsigned char* prevline = 0;
-
- /* bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise */
- size_t bytewidth = (bpp + 7u) / 8u;
- /* the width of a scanline in bytes, not including the filter type */
- size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;
-
- for (y = 0; y < h; ++y) {
- size_t outindex = linebytes * y;
- size_t inindex = (1 + linebytes) * y; /* the extra filterbyte added to each row */
- unsigned char filterType = in[inindex];
- CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
- prevline = &out[outindex];
- }
-
- return 0;
-}
-
-/* in: Adam7 interlaced image, with no padding bits between scanlines, but between
- reduced images so that each reduced image starts at a byte.
- out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
- bpp: bits per pixel
- out has the following size in bits: w * h * bpp.
- in is possibly bigger due to padding bits between reduced images.
- out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
- (because that's likely a little bit faster)
- NOTE: comments about padding bits are only relevant if bpp < 8 */
-static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
-{
- unsigned passw[7], passh[7];
- size_t filter_passstart[8], padded_passstart[8], passstart[8];
- unsigned i;
-
- Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
-
- if (bpp >= 8) {
- for(i = 0; i != 7; ++i) {
- unsigned x, y, b;
- size_t bytewidth = bpp / 8u;
- for (y = 0; y < passh[i]; ++y)
- for (x = 0; x < passw[i]; ++x) {
- size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
- size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w + ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth;
- for (b = 0; b < bytewidth; ++b) {
- out[pixeloutstart + b] = in[pixelinstart + b];
- }
- }
- }
- } else /* bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers */ {
- for (i = 0; i != 7; ++i) {
- unsigned x, y, b;
- unsigned ilinebits = bpp * passw[i];
- unsigned olinebits = bpp * w;
- size_t obp, ibp; /* bit pointers (for out and in buffer) */
- for (y = 0; y < passh[i]; ++y)
- for (x = 0; x < passw[i]; ++x) {
- ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
- obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp;
- for (b = 0; b < bpp; ++b) {
- unsigned char bit = readBitFromReversedStream(&ibp, in);
- setBitOfReversedStream(&obp, out, bit);
- }
- }
- }
- }
-}
-
-
-static void removePaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h)
-{
- /* After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
- to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
- for the Adam7 code, the color convert code and the output to the user.
- in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
- have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
- also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
- only useful if (ilinebits - olinebits) is a value in the range 1..7 */
- unsigned y;
- size_t diff = ilinebits - olinebits;
- size_t ibp = 0, obp = 0; /*input and output bit pointers*/
- for (y = 0; y < h; ++y) {
- size_t x;
- for (x = 0; x < olinebits; ++x) {
- unsigned char bit = readBitFromReversedStream(&ibp, in);
- setBitOfReversedStream(&obp, out, bit);
- }
- ibp += diff;
- }
-}
-
-
-/* out must be buffer big enough to contain full image, and in must contain the full decompressed data from
- the IDAT chunks (with filter index bytes and possible padding bits)
- return value is error */
-static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, unsigned w, unsigned h, const LodePNGInfo* info_png)
-{
- /* This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
- Steps:
- *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)
- *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
- NOTE: the in buffer will be overwritten with intermediate data! */
- unsigned bpp = lodepng_get_bpp_lct(info_png->color.colortype, info_png->color.bitdepth);
- if (bpp == 0) return 31; /* error: invalid colortype */
-
- if (info_png->interlace_method == 0) {
- if (bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
- CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
- removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);
- }
- /* we can immediately filter into the out buffer, no other steps needed */
- else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
- } else /* interlace_method is 1 (Adam7) */ {
- unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
- unsigned i;
-
- Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
-
- for (i = 0; i != 7; ++i) {
- CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
- /* TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
- move bytes instead of bits or move not at all */
- if (bpp < 8) {
- /* remove padding bits in scanlines; after this there still may be padding
- bits between the different reduced images: each reduced image still starts nicely at a byte */
- removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);
- }
- }
- Adam7_deinterlace(out, in, w, h, bpp);
- }
- return 0;
-}
-
-
-static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
-{
- unsigned pos = 0, i;
- color->palettesize = chunkLength / 3u;
- if (color->palettesize == 0 || color->palettesize > 256) return 38; /* error: palette too small or big */
- lodepng_color_mode_alloc_palette(color);
- if (!color->palette && color->palettesize) {
- color->palettesize = 0;
- return 83; /* alloc fail */
- }
-
- for (i = 0; i != color->palettesize; ++i) {
- color->palette[4 * i + 0] = data[pos++]; /*R*/
- color->palette[4 * i + 1] = data[pos++]; /*G*/
- color->palette[4 * i + 2] = data[pos++]; /*B*/
- color->palette[4 * i + 3] = 255; /*alpha*/
- }
-
- return 0; /* OK */
-}
-
-
-static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
-{
- unsigned i;
- if (color->colortype == LCT_PALETTE) {
- /* error: more alpha values given than there are palette entries */
- if (chunkLength > color->palettesize) return 39;
-
- for (i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
- } else if (color->colortype == LCT_GREY) {
- /* error: this chunk must be 2 bytes for grayscale image */
- if (chunkLength != 2) return 30;
-
- color->key_defined = 1;
- color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
- } else if (color->colortype == LCT_RGB) {
- /* error: this chunk must be 6 bytes for RGB image */
- if (chunkLength != 6) return 41;
-
- color->key_defined = 1;
- color->key_r = 256u * data[0] + data[1];
- color->key_g = 256u * data[2] + data[3];
- color->key_b = 256u * data[4] + data[5];
- }
- else return 42; /* error: tRNS chunk not allowed for other color models */
-
- return 0; /* OK */
-}
-
-
-/* read a PNG, the result will be in the same color type as the PNG (hence "generic") */
-static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize)
-{
- unsigned char IEND = 0;
- const unsigned char* chunk;
- unsigned char* idat; /*the data from idat chunks, zlib compressed*/
- size_t idatsize = 0;
- unsigned char* scanlines = 0;
- size_t scanlines_size = 0, expected_size = 0;
- size_t outsize = 0;
-
- /* safe output values in case error happens */
- *out = 0;
- *w = *h = 0;
-
- state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
- if (state->error) return;
-
- if (lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
- CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
- }
-
- /*the input filesize is a safe upper bound for the sum of idat chunks size*/
- idat = (unsigned char*)malloc(insize);
- if (!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/
-
- chunk = &in[33]; /*first byte of the first chunk after the header*/
-
- /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
- IDAT data is put at the start of the in buffer*/
- while (!IEND && !state->error) {
- unsigned chunkLength;
- const unsigned char* data; /*the data in the chunk*/
-
- /*error: size of the in buffer too small to contain next chunk*/
- if ((size_t)((chunk - in) + 12) > insize || chunk < in) {
- if (state->decoder.ignore_end) break; /*other errors may still happen though*/
- CERROR_BREAK(state->error, 30);
- }
-
- /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
- chunkLength = lodepng_chunk_length(chunk);
- /*error: chunk length larger than the max PNG chunk size*/
- if (chunkLength > 2147483647) {
- if (state->decoder.ignore_end) break; /*other errors may still happen though*/
- CERROR_BREAK(state->error, 63);
- }
-
- if ((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) {
- CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
- }
-
- data = lodepng_chunk_data_const(chunk);
-
- /*for unknown chunk order*/
- //unsigned unknown = 0;
-
- /*IDAT chunk, containing compressed image data*/
- if (lodepng_chunk_type_equals(chunk, "IDAT")) {
- size_t newsize;
- if (lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
- if (newsize > insize) CERROR_BREAK(state->error, 95);
- lodepng_memcpy(idat + idatsize, data, chunkLength);
- idatsize += chunkLength;
- } else if (lodepng_chunk_type_equals(chunk, "IEND")) {
- /*IEND chunk*/
- IEND = 1;
- } else if (lodepng_chunk_type_equals(chunk, "PLTE")) {
- /*palette chunk (PLTE)*/
- state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
- if (state->error) break;
- } else if (lodepng_chunk_type_equals(chunk, "tRNS")) {
- /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
- in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
- affects the alpha channel of pixels. */
- state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
- if (state->error) break;
- } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {
- /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
- if (!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
- CERROR_BREAK(state->error, 69);
- }
- //unknown = 1;
- }
-
-#if 0 //We don't use CRC
- if (!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {
- if (lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
- }
-#endif
- if (!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize);
- }
-
- if (state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) {
- state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */
- }
-
- if (!state->error) {
- /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
- If the decompressed size does not match the prediction, the image must be corrupt.*/
- if (state->info_png.interlace_method == 0) {
- size_t bpp = lodepng_get_bpp_lct(state->info_png.color.colortype, state->info_png.color.bitdepth);
- expected_size = lodepng_get_raw_size_idat(*w, *h, bpp);
- } else {
- size_t bpp = lodepng_get_bpp_lct(state->info_png.color.colortype, state->info_png.color.bitdepth);
- /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/
- expected_size = 0;
- expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp);
- if (*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp);
- expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp);
- if (*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp);
- expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp);
- if (*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp);
- expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp);
- }
- state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings);
- }
-
- if (!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/
- free(idat);
-
- if (!state->error) {
- outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
- *out = (unsigned char*)malloc(outsize);
- if (!*out) state->error = 83; /*alloc fail*/
- }
- if (!state->error) {
- lodepng_memset(*out, 0, outsize);
- state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);
- }
- free(scanlines);
-}
-
-
-static void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
-{
- settings->color_convert = 1;
- settings->ignore_crc = 0;
- settings->ignore_critical = 0;
- settings->ignore_end = 0;
- lodepng_decompress_settings_init(&settings->zlibsettings);
-}
-
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-/*read the information from the header and store it in the LodePNGInfo. return value is error*/
-unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize)
-{
- unsigned width, height;
- LodePNGInfo* info = &state->info_png;
- if (insize == 0 || in == 0) {
- CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
- }
- if (insize < 33) {
- CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
- }
-
- /* when decoding a new PNG image, make sure all parameters created after previous decoding are reset */
- /* TODO: remove this. One should use a new LodePNGState for new sessions */
- lodepng_info_cleanup(info);
- lodepng_info_init(info);
-
- if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
- CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
- }
- if (lodepng_chunk_length(in + 8) != 13) {
- CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
- }
- if (!lodepng_chunk_type_equals(in + 8, "IHDR")) {
- CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
- }
-
- /*read the values given in the header*/
- width = lodepng_read32bitInt(&in[16]);
- height = lodepng_read32bitInt(&in[20]);
- /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/
- if (w) *w = width;
- if (h) *h = height;
- info->color.bitdepth = in[24];
- info->color.colortype = (LodePNGColorType)in[25];
- info->compression_method = in[26];
- info->filter_method = in[27];
- info->interlace_method = in[28];
-
- /*errors returned only after the parsing so other values are still output*/
-
- /*error: invalid image size*/
- if (width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);
- /*error: invalid colortype or bitdepth combination*/
- state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
- if (state->error) return state->error;
- /*error: only compression method 0 is allowed in the specification*/
- if (info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
- /*error: only filter method 0 is allowed in the specification*/
- if (info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
- /*error: only interlace methods 0 and 1 exist in the specification*/
- if (info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
-
-#if 0 //thorvg don't use crc
- if (!state->decoder.ignore_crc) {
- unsigned CRC = lodepng_read32bitInt(&in[29]);
- unsigned checksum = lodepng_crc32(&in[12], 17);
- if (CRC != checksum) {
- CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
- }
- }
-#endif
- return state->error;
-}
-
-
-unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize)
-{
- *out = 0;
- decodeGeneric(out, w, h, state, in, insize);
- if (state->error) return state->error;
- if (!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
- /*same color type, no copying or converting of data needed*/
- /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
- the raw image has to the end user*/
- if (!state->decoder.color_convert) {
- state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
- if (state->error) return state->error;
- }
- } else { /*color conversion needed*/
- unsigned char* data = *out;
- size_t outsize;
-
- /*TODO: check if this works according to the statement in the documentation: "The converter can convert
- from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
- if (!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) && !(state->info_raw.bitdepth == 8)) {
- return 56; /*unsupported color mode conversion*/
- }
-
- outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
- *out = (unsigned char*)malloc(outsize);
- if (!(*out)) {
- state->error = 83; /*alloc fail*/
- }
- else state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h);
- free(data);
- }
- return state->error;
-}
-
-
-void lodepng_state_init(LodePNGState* state)
-{
- lodepng_decoder_settings_init(&state->decoder);
- lodepng_color_mode_init(&state->info_raw);
- lodepng_info_init(&state->info_png);
- state->error = 1;
-}
-
-
-void lodepng_state_cleanup(LodePNGState* state)
-{
- lodepng_color_mode_cleanup(&state->info_raw);
- lodepng_info_cleanup(&state->info_png);
-}
diff --git a/thirdparty/thorvg/src/loaders/png/tvgLodePng.h b/thirdparty/thorvg/src/loaders/png/tvgLodePng.h
deleted file mode 100644
index 0cdac7cbea..0000000000
--- a/thirdparty/thorvg/src/loaders/png/tvgLodePng.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (c) 2020 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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.
- */
-
-/*
- LodePNG version 20200306
-
- Copyright (c) 2005-2020 Lode Vandevenne
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source
- distribution.
-*/
-
-#ifndef _TVG_LODEPNG_H_
-#define _TVG_LODEPNG_H_
-
-#include <stddef.h>
-
-/*The PNG color types (also used for raw image).*/
-enum LodePNGColorType
-{
- LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/
- LCT_RGB = 2, /*RGB: 8,16 bit*/
- LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/
- LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/
- LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/
- /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid
- byte value from 0 to 255 that could be present in an invalid PNG file header. Do
- not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use
- the valid color type names above, or numeric values like 1 or 7 when checking for
- particular disallowed color type byte values, or cast to integer to print it.*/
- LCT_MAX_OCTET_VALUE = 255
-};
-
-/*Settings for zlib decompression*/
-struct LodePNGDecompressSettings
-{
- /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */
- unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
- unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/
-
- /*use custom zlib decoder instead of built in one (default: null)*/
- unsigned (*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*);
- /*use custom deflate decoder instead of built in one (default: null) if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate)*/
- unsigned (*custom_inflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*);
-
- const void* custom_context; /*optional custom settings for custom functions*/
-};
-
-/*
- Color mode of an image. Contains all information required to decode the pixel
- bits to RGBA colors. This information is the same as used in the PNG file
- format, and is used both for PNG and raw image data in LodePNG.
-*/
-struct LodePNGColorMode
-{
- /*header (IHDR)*/
- LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
- unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/
-
- /*
- palette (PLTE and tRNS)
-
- Dynamically allocated with the colors of the palette, including alpha.
- This field may not be allocated directly, use lodepng_color_mode_init first,
- then lodepng_palette_add per color to correctly initialize it (to ensure size
- of exactly 1024 bytes).
-
- The alpha channels must be set as well, set them to 255 for opaque images.
-
- When decoding, by default you can ignore this palette, since LodePNG already
- fills the palette colors in the pixels of the raw RGBA output.
-
- The palette is only supported for color type 3.
- */
- unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/
- size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/
-
- /*
- transparent color key (tRNS)
-
- This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
- For grayscale PNGs, r, g and b will all 3 be set to the same.
-
- When decoding, by default you can ignore this information, since LodePNG sets
- pixels with this key to transparent already in the raw RGBA output.
-
- The color key is only supported for color types 0 and 2.
- */
- unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
- unsigned key_r; /*red/grayscale component of color key*/
- unsigned key_g; /*green component of color key*/
- unsigned key_b; /*blue component of color key*/
-};
-
-/*Information about the PNG image, except pixels, width and height.*/
-struct LodePNGInfo
-{
- /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
- unsigned compression_method;/*compression method of the original file. Always 0.*/
- unsigned filter_method; /*filter method of the original file*/
- unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/
- LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/
-};
-
-/*
- Settings for the decoder. This contains settings for the PNG and the Zlib
- decoder, but not the Info settings from the Info structs.
-*/
-struct LodePNGDecoderSettings
-{
- LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
-
- /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */
- unsigned ignore_crc; /*ignore CRC checksums*/
- unsigned ignore_critical; /*ignore unknown critical chunks*/
- unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/
- /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable
- errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some
- strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters
- in string keys, etc... */
-
- unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
-};
-
-/*The settings, state and information for extended encoding and decoding.*/
-struct LodePNGState
-{
- LodePNGDecoderSettings decoder; /*the decoding settings*/
- LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
- LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
- unsigned error;
-};
-
-void lodepng_state_init(LodePNGState* state);
-void lodepng_state_cleanup(LodePNGState* state);
-unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize);
-unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize);
-
-#endif //_TVG_LODEPNG_H_
diff --git a/thirdparty/thorvg/src/loaders/png/tvgPngLoader.cpp b/thirdparty/thorvg/src/loaders/png/tvgPngLoader.cpp
deleted file mode 100644
index 3e293176b7..0000000000
--- a/thirdparty/thorvg/src/loaders/png/tvgPngLoader.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2021 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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 <memory.h>
-#include "tvgLoader.h"
-#include "tvgPngLoader.h"
-
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-
-static inline uint32_t PREMULTIPLY(uint32_t c)
-{
- auto a = (c >> 24);
- return (c & 0xff000000) + ((((c >> 8) & 0xff) * a) & 0xff00) + ((((c & 0x00ff00ff) * a) >> 8) & 0x00ff00ff);
-}
-
-
-static void _premultiply(uint32_t* data, uint32_t w, uint32_t h)
-{
- auto buffer = data;
- for (uint32_t y = 0; y < h; ++y, buffer += w) {
- auto src = buffer;
- for (uint32_t x = 0; x < w; ++x, ++src) {
- *src = PREMULTIPLY(*src);
- }
- }
-}
-
-
-void PngLoader::clear()
-{
- lodepng_state_cleanup(&state);
-
- if (freeData) free(data);
- data = nullptr;
- size = 0;
- freeData = false;
-}
-
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-PngLoader::PngLoader()
-{
- lodepng_state_init(&state);
-}
-
-
-PngLoader::~PngLoader()
-{
- if (freeData) free(data);
- free(image);
-}
-
-
-bool PngLoader::open(const string& path)
-{
- clear();
-
- auto pngFile = fopen(path.c_str(), "rb");
- if (!pngFile) return false;
-
- auto ret = false;
-
- //determine size
- if (fseek(pngFile, 0, SEEK_END) < 0) goto finalize;
- if (((size = ftell(pngFile)) < 1)) goto finalize;
- if (fseek(pngFile, 0, SEEK_SET)) goto finalize;
-
- data = (unsigned char *) malloc(size);
- if (!data) goto finalize;
-
- freeData = true;
-
- if (fread(data, size, 1, pngFile) < 1) goto failure;
-
- lodepng_state_init(&state);
-
- unsigned int width, height;
- if (lodepng_inspect(&width, &height, &state, data, size) > 0) goto failure;
-
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- ret = true;
-
- goto finalize;
-
-failure:
- clear();
-
-finalize:
- fclose(pngFile);
- return ret;
-}
-
-
-bool PngLoader::open(const char* data, uint32_t size, bool copy)
-{
- clear();
-
- lodepng_state_init(&state);
-
- unsigned int width, height;
- if (lodepng_inspect(&width, &height, &state, (unsigned char*)(data), size) > 0) return false;
-
- if (copy) {
- this->data = (unsigned char *) malloc(size);
- if (!this->data) return false;
- memcpy((unsigned char *)this->data, data, size);
- freeData = true;
- } else {
- this->data = (unsigned char *) data;
- freeData = false;
- }
-
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- this->size = size;
-
- return true;
-}
-
-
-bool PngLoader::read()
-{
- if (!data || w <= 0 || h <= 0) return false;
-
- TaskScheduler::request(this);
-
- return true;
-}
-
-
-bool PngLoader::close()
-{
- this->done();
- clear();
- return true;
-}
-
-
-unique_ptr<Surface> PngLoader::bitmap()
-{
- this->done();
-
- if (!image) return nullptr;
-
- auto surface = static_cast<Surface*>(malloc(sizeof(Surface)));
- surface->buffer = (uint32_t*)(image);
- surface->stride = w;
- surface->w = w;
- surface->h = h;
- surface->cs = SwCanvas::ARGB8888;
-
- return unique_ptr<Surface>(surface);
-}
-
-
-void PngLoader::run(unsigned tid)
-{
- if (image) {
- free(image);
- image = nullptr;
- }
- auto width = static_cast<unsigned>(w);
- auto height = static_cast<unsigned>(h);
-
- lodepng_decode(&image, &width, &height, &state, data, size);
-
- _premultiply((uint32_t*)(image), width, height);
-}
diff --git a/thirdparty/thorvg/src/loaders/png/tvgPngLoader.h b/thirdparty/thorvg/src/loaders/png/tvgPngLoader.h
deleted file mode 100644
index 8f07f6418f..0000000000
--- a/thirdparty/thorvg/src/loaders/png/tvgPngLoader.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2021 - 2022 Samsung Electronics Co., Ltd. All rights reserved.
-
- * 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 _TVG_PNG_LOADER_H_
-#define _TVG_PNG_LOADER_H_
-
-#include "tvgLodePng.h"
-#include "tvgTaskScheduler.h"
-
-
-class PngLoader : public LoadModule, public Task
-{
-private:
- LodePNGState state;
- unsigned char* data = nullptr;
- unsigned char *image = nullptr;
- unsigned long size = 0;
- bool freeData = false;
-
- void clear();
-
-public:
- PngLoader();
- ~PngLoader();
-
- using LoadModule::open;
- bool open(const string& path) override;
- bool open(const char* data, uint32_t size, bool copy) override;
- bool read() override;
- bool close() override;
-
- unique_ptr<Surface> bitmap() override;
- void run(unsigned tid) override;
-};
-
-#endif //_TVG_PNG_LOADER_H_
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
index d7c51bdc30..c373da2dd5 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
@@ -26,8 +26,8 @@
#ifdef _WIN32
#include <malloc.h>
-#elif defined(__FreeBSD__)
- #include <stdlib.h>
+#elif __FreeBSD__
+ #include<stdlib.h>
#else
#include <alloca.h>
#endif
@@ -390,7 +390,7 @@ bool simpleXmlParse(const char* buf, unsigned bufLength, bool strip, simpleXMLCb
if (p) {
//Invalid case: '<' nested
- if (*p == '<') return false;
+ if (*p == '<' && type != SimpleXMLType::Doctype) return false;
const char *start, *end;
start = itr + 1 + toff;
diff --git a/thirdparty/thorvg/src/loaders/tvg/tvgTvgBinInterpreter.cpp b/thirdparty/thorvg/src/loaders/tvg/tvgTvgBinInterpreter.cpp
index 66de860aaa..62a75ecd3d 100644
--- a/thirdparty/thorvg/src/loaders/tvg/tvgTvgBinInterpreter.cpp
+++ b/thirdparty/thorvg/src/loaders/tvg/tvgTvgBinInterpreter.cpp
@@ -23,8 +23,8 @@
#ifdef _WIN32
#include <malloc.h>
-#elif defined(__FreeBSD__)
- #include <stdlib.h>
+#elif __FreeBSD__
+ #include<stdlib.h>
#else
#include <alloca.h>
#endif
diff --git a/thirdparty/thorvg/src/savers/tvg/tvgTvgSaver.cpp b/thirdparty/thorvg/src/savers/tvg/tvgTvgSaver.cpp
index fca313b430..adf85836c3 100644
--- a/thirdparty/thorvg/src/savers/tvg/tvgTvgSaver.cpp
+++ b/thirdparty/thorvg/src/savers/tvg/tvgTvgSaver.cpp
@@ -28,8 +28,8 @@
#ifdef _WIN32
#include <malloc.h>
-#elif defined(__FreeBSD__)
- #include <stdlib.h>
+#elif __FreeBSD__
+ #include<stdlib.h>
#else
#include <alloca.h>
#endif
diff --git a/thirdparty/thorvg/update-thorvg.sh b/thirdparty/thorvg/update-thorvg.sh
index a3b73a7135..f2fd2a80e4 100755
--- a/thirdparty/thorvg/update-thorvg.sh
+++ b/thirdparty/thorvg/update-thorvg.sh
@@ -1,12 +1,12 @@
-VERSION=0.8.1
+VERSION=0.8.2
rm -rf AUTHORS inc LICENSE src *.zip
-curl -L -O https://github.com/Samsung/thorvg/archive/$VERSION.zip
+curl -L -O https://github.com/Samsung/thorvg/archive/v$VERSION.zip
bsdtar --strip-components=1 -xvf *.zip
rm *.zip
-rm -rf .github docs pc res test tools .git* *.md *.txt wasm_build.sh
+rm -rf .github docs pc res test tools tvgcompat .git* *.md *.txt wasm_build.sh
find . -type f -name 'meson.build' -delete
rm -rf src/bin src/bindings src/examples src/wasm
-rm -rf src/lib/gl_engine tvgcompat
+rm -rf src/lib/gl_engine src/loaders/external_jpg src/loaders/png
cat << EOF > inc/config.h
#ifndef THORVG_CONFIG_H
#define THORVG_CONFIG_H